0.pre7.56:
[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 /* FIXME: (1) Shouldn't this be defined in sbcl.h? */
1797 #define FUN_RAW_ADDR_OFFSET (6*sizeof(lispobj) - FUN_POINTER_LOWTAG)
1798
1799 static lispobj trans_fun_header(lispobj object);
1800 static lispobj trans_boxed(lispobj object);
1801
1802 static int
1803 scav_fun_pointer(lispobj *where, lispobj object)
1804 {
1805     lispobj *first_pointer;
1806     lispobj copy;
1807
1808     gc_assert(is_lisp_pointer(object));
1809
1810     /* Object is a pointer into from space - no a FP. */
1811     first_pointer = (lispobj *) native_pointer(object);
1812
1813     /* must transport object -- object may point to either a function
1814      * header, a closure function header, or to a closure header. */
1815
1816     switch (TypeOf(*first_pointer)) {
1817     case type_SimpleFunHeader:
1818     case type_ClosureFunHeader:
1819         copy = trans_fun_header(object);
1820         break;
1821     default:
1822         copy = trans_boxed(object);
1823         break;
1824     }
1825
1826     if (copy != object) {
1827         /* Set forwarding pointer */
1828         first_pointer[0] = 0x01;
1829         first_pointer[1] = copy;
1830     }
1831
1832     gc_assert(is_lisp_pointer(copy));
1833     gc_assert(!from_space_p(copy));
1834
1835     *where = copy;
1836
1837     return 1;
1838 }
1839
1840 /* Scan a x86 compiled code object, looking for possible fixups that
1841  * have been missed after a move.
1842  *
1843  * Two types of fixups are needed:
1844  * 1. Absolute fixups to within the code object.
1845  * 2. Relative fixups to outside the code object.
1846  *
1847  * Currently only absolute fixups to the constant vector, or to the
1848  * code area are checked. */
1849 void
1850 sniff_code_object(struct code *code, unsigned displacement)
1851 {
1852     int nheader_words, ncode_words, nwords;
1853     void *p;
1854     void *constants_start_addr, *constants_end_addr;
1855     void *code_start_addr, *code_end_addr;
1856     int fixup_found = 0;
1857
1858     if (!check_code_fixups)
1859         return;
1860
1861     ncode_words = fixnum_value(code->code_size);
1862     nheader_words = HeaderValue(*(lispobj *)code);
1863     nwords = ncode_words + nheader_words;
1864
1865     constants_start_addr = (void *)code + 5*4;
1866     constants_end_addr = (void *)code + nheader_words*4;
1867     code_start_addr = (void *)code + nheader_words*4;
1868     code_end_addr = (void *)code + nwords*4;
1869
1870     /* Work through the unboxed code. */
1871     for (p = code_start_addr; p < code_end_addr; p++) {
1872         void *data = *(void **)p;
1873         unsigned d1 = *((unsigned char *)p - 1);
1874         unsigned d2 = *((unsigned char *)p - 2);
1875         unsigned d3 = *((unsigned char *)p - 3);
1876         unsigned d4 = *((unsigned char *)p - 4);
1877 #if QSHOW
1878         unsigned d5 = *((unsigned char *)p - 5);
1879         unsigned d6 = *((unsigned char *)p - 6);
1880 #endif
1881
1882         /* Check for code references. */
1883         /* Check for a 32 bit word that looks like an absolute
1884            reference to within the code adea of the code object. */
1885         if ((data >= (code_start_addr-displacement))
1886             && (data < (code_end_addr-displacement))) {
1887             /* function header */
1888             if ((d4 == 0x5e)
1889                 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) == (unsigned)code)) {
1890                 /* Skip the function header */
1891                 p += 6*4 - 4 - 1;
1892                 continue;
1893             }
1894             /* the case of PUSH imm32 */
1895             if (d1 == 0x68) {
1896                 fixup_found = 1;
1897                 FSHOW((stderr,
1898                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1899                        p, d6, d5, d4, d3, d2, d1, data));
1900                 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1901             }
1902             /* the case of MOV [reg-8],imm32 */
1903             if ((d3 == 0xc7)
1904                 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1905                     || d2==0x45 || d2==0x46 || d2==0x47)
1906                 && (d1 == 0xf8)) {
1907                 fixup_found = 1;
1908                 FSHOW((stderr,
1909                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1910                        p, d6, d5, d4, d3, d2, d1, data));
1911                 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1912             }
1913             /* the case of LEA reg,[disp32] */
1914             if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1915                 fixup_found = 1;
1916                 FSHOW((stderr,
1917                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1918                        p, d6, d5, d4, d3, d2, d1, data));
1919                 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1920             }
1921         }
1922
1923         /* Check for constant references. */
1924         /* Check for a 32 bit word that looks like an absolute
1925            reference to within the constant vector. Constant references
1926            will be aligned. */
1927         if ((data >= (constants_start_addr-displacement))
1928             && (data < (constants_end_addr-displacement))
1929             && (((unsigned)data & 0x3) == 0)) {
1930             /*  Mov eax,m32 */
1931             if (d1 == 0xa1) {
1932                 fixup_found = 1;
1933                 FSHOW((stderr,
1934                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1935                        p, d6, d5, d4, d3, d2, d1, data));
1936                 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1937             }
1938
1939             /*  the case of MOV m32,EAX */
1940             if (d1 == 0xa3) {
1941                 fixup_found = 1;
1942                 FSHOW((stderr,
1943                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1944                        p, d6, d5, d4, d3, d2, d1, data));
1945                 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1946             }
1947
1948             /* the case of CMP m32,imm32 */             
1949             if ((d1 == 0x3d) && (d2 == 0x81)) {
1950                 fixup_found = 1;
1951                 FSHOW((stderr,
1952                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1953                        p, d6, d5, d4, d3, d2, d1, data));
1954                 /* XX Check this */
1955                 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1956             }
1957
1958             /* Check for a mod=00, r/m=101 byte. */
1959             if ((d1 & 0xc7) == 5) {
1960                 /* Cmp m32,reg */
1961                 if (d2 == 0x39) {
1962                     fixup_found = 1;
1963                     FSHOW((stderr,
1964                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1965                            p, d6, d5, d4, d3, d2, d1, data));
1966                     FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1967                 }
1968                 /* the case of CMP reg32,m32 */
1969                 if (d2 == 0x3b) {
1970                     fixup_found = 1;
1971                     FSHOW((stderr,
1972                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1973                            p, d6, d5, d4, d3, d2, d1, data));
1974                     FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1975                 }
1976                 /* the case of MOV m32,reg32 */
1977                 if (d2 == 0x89) {
1978                     fixup_found = 1;
1979                     FSHOW((stderr,
1980                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1981                            p, d6, d5, d4, d3, d2, d1, data));
1982                     FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1983                 }
1984                 /* the case of MOV reg32,m32 */
1985                 if (d2 == 0x8b) {
1986                     fixup_found = 1;
1987                     FSHOW((stderr,
1988                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1989                            p, d6, d5, d4, d3, d2, d1, data));
1990                     FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1991                 }
1992                 /* the case of LEA reg32,m32 */
1993                 if (d2 == 0x8d) {
1994                     fixup_found = 1;
1995                     FSHOW((stderr,
1996                            "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1997                            p, d6, d5, d4, d3, d2, d1, data));
1998                     FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1999                 }
2000             }
2001         }
2002     }
2003
2004     /* If anything was found, print some information on the code
2005      * object. */
2006     if (fixup_found) {
2007         FSHOW((stderr,
2008                "/compiled code object at %x: header words = %d, code words = %d\n",
2009                code, nheader_words, ncode_words));
2010         FSHOW((stderr,
2011                "/const start = %x, end = %x\n",
2012                constants_start_addr, constants_end_addr));
2013         FSHOW((stderr,
2014                "/code start = %x, end = %x\n",
2015                code_start_addr, code_end_addr));
2016     }
2017 }
2018
2019 static void
2020 apply_code_fixups(struct code *old_code, struct code *new_code)
2021 {
2022     int nheader_words, ncode_words, nwords;
2023     void *constants_start_addr, *constants_end_addr;
2024     void *code_start_addr, *code_end_addr;
2025     lispobj fixups = NIL;
2026     unsigned displacement = (unsigned)new_code - (unsigned)old_code;
2027     struct vector *fixups_vector;
2028
2029     ncode_words = fixnum_value(new_code->code_size);
2030     nheader_words = HeaderValue(*(lispobj *)new_code);
2031     nwords = ncode_words + nheader_words;
2032     /* FSHOW((stderr,
2033              "/compiled code object at %x: header words = %d, code words = %d\n",
2034              new_code, nheader_words, ncode_words)); */
2035     constants_start_addr = (void *)new_code + 5*4;
2036     constants_end_addr = (void *)new_code + nheader_words*4;
2037     code_start_addr = (void *)new_code + nheader_words*4;
2038     code_end_addr = (void *)new_code + nwords*4;
2039     /*
2040     FSHOW((stderr,
2041            "/const start = %x, end = %x\n",
2042            constants_start_addr,constants_end_addr));
2043     FSHOW((stderr,
2044            "/code start = %x; end = %x\n",
2045            code_start_addr,code_end_addr));
2046     */
2047
2048     /* The first constant should be a pointer to the fixups for this
2049        code objects. Check. */
2050     fixups = new_code->constants[0];
2051
2052     /* It will be 0 or the unbound-marker if there are no fixups, and
2053      * will be an other pointer if it is valid. */
2054     if ((fixups == 0) || (fixups == type_UnboundMarker) ||
2055         !is_lisp_pointer(fixups)) {
2056         /* Check for possible errors. */
2057         if (check_code_fixups)
2058             sniff_code_object(new_code, displacement);
2059
2060         /*fprintf(stderr,"Fixups for code object not found!?\n");
2061           fprintf(stderr,"*** Compiled code object at %x: header_words=%d code_words=%d .\n",
2062           new_code, nheader_words, ncode_words);
2063           fprintf(stderr,"*** Const. start = %x; end= %x; Code start = %x; end = %x\n",
2064           constants_start_addr,constants_end_addr,
2065           code_start_addr,code_end_addr);*/
2066         return;
2067     }
2068
2069     fixups_vector = (struct vector *)native_pointer(fixups);
2070
2071     /* Could be pointing to a forwarding pointer. */
2072     if (is_lisp_pointer(fixups) &&
2073         (find_page_index((void*)fixups_vector) != -1) &&
2074         (fixups_vector->header == 0x01)) {
2075         /* If so, then follow it. */
2076         /*SHOW("following pointer to a forwarding pointer");*/
2077         fixups_vector = (struct vector *)native_pointer((lispobj)fixups_vector->length);
2078     }
2079
2080     /*SHOW("got fixups");*/
2081
2082     if (TypeOf(fixups_vector->header) == type_SimpleArrayUnsignedByte32) {
2083         /* Got the fixups for the code block. Now work through the vector,
2084            and apply a fixup at each address. */
2085         int length = fixnum_value(fixups_vector->length);
2086         int i;
2087         for (i = 0; i < length; i++) {
2088             unsigned offset = fixups_vector->data[i];
2089             /* Now check the current value of offset. */
2090             unsigned old_value =
2091                 *(unsigned *)((unsigned)code_start_addr + offset);
2092
2093             /* If it's within the old_code object then it must be an
2094              * absolute fixup (relative ones are not saved) */
2095             if ((old_value >= (unsigned)old_code)
2096                 && (old_value < ((unsigned)old_code + nwords*4)))
2097                 /* So add the dispacement. */
2098                 *(unsigned *)((unsigned)code_start_addr + offset) =
2099                     old_value + displacement;
2100             else
2101                 /* It is outside the old code object so it must be a
2102                  * relative fixup (absolute fixups are not saved). So
2103                  * subtract the displacement. */
2104                 *(unsigned *)((unsigned)code_start_addr + offset) =
2105                     old_value - displacement;
2106         }
2107     }
2108
2109     /* Check for possible errors. */
2110     if (check_code_fixups) {
2111         sniff_code_object(new_code,displacement);
2112     }
2113 }
2114
2115 static struct code *
2116 trans_code(struct code *code)
2117 {
2118     struct code *new_code;
2119     lispobj l_code, l_new_code;
2120     int nheader_words, ncode_words, nwords;
2121     unsigned long displacement;
2122     lispobj fheaderl, *prev_pointer;
2123
2124     /* FSHOW((stderr,
2125              "\n/transporting code object located at 0x%08x\n",
2126              (unsigned long) code)); */
2127
2128     /* If object has already been transported, just return pointer. */
2129     if (*((lispobj *)code) == 0x01)
2130         return (struct code*)(((lispobj *)code)[1]);
2131
2132     gc_assert(TypeOf(code->header) == type_CodeHeader);
2133
2134     /* Prepare to transport the code vector. */
2135     l_code = (lispobj) code | OTHER_POINTER_LOWTAG;
2136
2137     ncode_words = fixnum_value(code->code_size);
2138     nheader_words = HeaderValue(code->header);
2139     nwords = ncode_words + nheader_words;
2140     nwords = CEILING(nwords, 2);
2141
2142     l_new_code = copy_large_object(l_code, nwords);
2143     new_code = (struct code *) native_pointer(l_new_code);
2144
2145     /* may not have been moved.. */
2146     if (new_code == code)
2147         return new_code;
2148
2149     displacement = l_new_code - l_code;
2150
2151     /*
2152     FSHOW((stderr,
2153            "/old code object at 0x%08x, new code object at 0x%08x\n",
2154            (unsigned long) code,
2155            (unsigned long) new_code));
2156     FSHOW((stderr, "/Code object is %d words long.\n", nwords));
2157     */
2158
2159     /* Set forwarding pointer. */
2160     ((lispobj *)code)[0] = 0x01;
2161     ((lispobj *)code)[1] = l_new_code;
2162
2163     /* Set forwarding pointers for all the function headers in the
2164      * code object. Also fix all self pointers. */
2165
2166     fheaderl = code->entry_points;
2167     prev_pointer = &new_code->entry_points;
2168
2169     while (fheaderl != NIL) {
2170         struct simple_fun *fheaderp, *nfheaderp;
2171         lispobj nfheaderl;
2172
2173         fheaderp = (struct simple_fun *) native_pointer(fheaderl);
2174         gc_assert(TypeOf(fheaderp->header) == type_SimpleFunHeader);
2175
2176         /* Calculate the new function pointer and the new */
2177         /* function header. */
2178         nfheaderl = fheaderl + displacement;
2179         nfheaderp = (struct simple_fun *) native_pointer(nfheaderl);
2180
2181         /* Set forwarding pointer. */
2182         ((lispobj *)fheaderp)[0] = 0x01;
2183         ((lispobj *)fheaderp)[1] = nfheaderl;
2184
2185         /* Fix self pointer. */
2186         nfheaderp->self = nfheaderl + FUN_RAW_ADDR_OFFSET;
2187
2188         *prev_pointer = nfheaderl;
2189
2190         fheaderl = fheaderp->next;
2191         prev_pointer = &nfheaderp->next;
2192     }
2193
2194     /*  sniff_code_object(new_code,displacement);*/
2195     apply_code_fixups(code,new_code);
2196
2197     return new_code;
2198 }
2199
2200 static int
2201 scav_code_header(lispobj *where, lispobj object)
2202 {
2203     struct code *code;
2204     int n_header_words, n_code_words, n_words;
2205     lispobj entry_point;        /* tagged pointer to entry point */
2206     struct simple_fun *function_ptr; /* untagged pointer to entry point */
2207
2208     code = (struct code *) where;
2209     n_code_words = fixnum_value(code->code_size);
2210     n_header_words = HeaderValue(object);
2211     n_words = n_code_words + n_header_words;
2212     n_words = CEILING(n_words, 2);
2213
2214     /* Scavenge the boxed section of the code data block. */
2215     scavenge(where + 1, n_header_words - 1);
2216
2217     /* Scavenge the boxed section of each function object in the */
2218     /* code data block. */
2219     for (entry_point = code->entry_points;
2220          entry_point != NIL;
2221          entry_point = function_ptr->next) {
2222
2223         gc_assert(is_lisp_pointer(entry_point));
2224
2225         function_ptr = (struct simple_fun *) native_pointer(entry_point);
2226         gc_assert(TypeOf(function_ptr->header) == type_SimpleFunHeader);
2227
2228         scavenge(&function_ptr->name, 1);
2229         scavenge(&function_ptr->arglist, 1);
2230         scavenge(&function_ptr->type, 1);
2231     }
2232         
2233     return n_words;
2234 }
2235
2236 static lispobj
2237 trans_code_header(lispobj object)
2238 {
2239     struct code *ncode;
2240
2241     ncode = trans_code((struct code *) native_pointer(object));
2242     return (lispobj) ncode | OTHER_POINTER_LOWTAG;
2243 }
2244
2245 static int
2246 size_code_header(lispobj *where)
2247 {
2248     struct code *code;
2249     int nheader_words, ncode_words, nwords;
2250
2251     code = (struct code *) where;
2252         
2253     ncode_words = fixnum_value(code->code_size);
2254     nheader_words = HeaderValue(code->header);
2255     nwords = ncode_words + nheader_words;
2256     nwords = CEILING(nwords, 2);
2257
2258     return nwords;
2259 }
2260
2261 static int
2262 scav_return_pc_header(lispobj *where, lispobj object)
2263 {
2264     lose("attempted to scavenge a return PC header where=0x%08x object=0x%08x",
2265          (unsigned long) where,
2266          (unsigned long) object);
2267     return 0; /* bogus return value to satisfy static type checking */
2268 }
2269
2270 static lispobj
2271 trans_return_pc_header(lispobj object)
2272 {
2273     struct simple_fun *return_pc;
2274     unsigned long offset;
2275     struct code *code, *ncode;
2276
2277     SHOW("/trans_return_pc_header: Will this work?");
2278
2279     return_pc = (struct simple_fun *) native_pointer(object);
2280     offset = HeaderValue(return_pc->header) * 4;
2281
2282     /* Transport the whole code object. */
2283     code = (struct code *) ((unsigned long) return_pc - offset);
2284     ncode = trans_code(code);
2285
2286     return ((lispobj) ncode + offset) | OTHER_POINTER_LOWTAG;
2287 }
2288
2289 /* On the 386, closures hold a pointer to the raw address instead of the
2290  * function object. */
2291 #ifdef __i386__
2292 static int
2293 scav_closure_header(lispobj *where, lispobj object)
2294 {
2295     struct closure *closure;
2296     lispobj fun;
2297
2298     closure = (struct closure *)where;
2299     fun = closure->fun - FUN_RAW_ADDR_OFFSET;
2300     scavenge(&fun, 1);
2301     /* The function may have moved so update the raw address. But
2302      * don't write unnecessarily. */
2303     if (closure->fun != fun + FUN_RAW_ADDR_OFFSET)
2304         closure->fun = fun + FUN_RAW_ADDR_OFFSET;
2305
2306     return 2;
2307 }
2308 #endif
2309
2310 static int
2311 scav_fun_header(lispobj *where, lispobj object)
2312 {
2313     lose("attempted to scavenge a function header where=0x%08x object=0x%08x",
2314          (unsigned long) where,
2315          (unsigned long) object);
2316     return 0; /* bogus return value to satisfy static type checking */
2317 }
2318
2319 static lispobj
2320 trans_fun_header(lispobj object)
2321 {
2322     struct simple_fun *fheader;
2323     unsigned long offset;
2324     struct code *code, *ncode;
2325
2326     fheader = (struct simple_fun *) native_pointer(object);
2327     offset = HeaderValue(fheader->header) * 4;
2328
2329     /* Transport the whole code object. */
2330     code = (struct code *) ((unsigned long) fheader - offset);
2331     ncode = trans_code(code);
2332
2333     return ((lispobj) ncode + offset) | FUN_POINTER_LOWTAG;
2334 }
2335 \f
2336 /*
2337  * instances
2338  */
2339
2340 static int
2341 scav_instance_pointer(lispobj *where, lispobj object)
2342 {
2343     lispobj copy, *first_pointer;
2344
2345     /* Object is a pointer into from space - not a FP. */
2346     copy = trans_boxed(object);
2347
2348     gc_assert(copy != object);
2349
2350     first_pointer = (lispobj *) native_pointer(object);
2351
2352     /* Set forwarding pointer. */
2353     first_pointer[0] = 0x01;
2354     first_pointer[1] = copy;
2355     *where = copy;
2356
2357     return 1;
2358 }
2359 \f
2360 /*
2361  * lists and conses
2362  */
2363
2364 static lispobj trans_list(lispobj object);
2365
2366 static int
2367 scav_list_pointer(lispobj *where, lispobj object)
2368 {
2369     lispobj first, *first_pointer;
2370
2371     gc_assert(is_lisp_pointer(object));
2372
2373     /* Object is a pointer into from space - not FP. */
2374
2375     first = trans_list(object);
2376     gc_assert(first != object);
2377
2378     first_pointer = (lispobj *) native_pointer(object);
2379
2380     /* Set forwarding pointer */
2381     first_pointer[0] = 0x01;
2382     first_pointer[1] = first;
2383
2384     gc_assert(is_lisp_pointer(first));
2385     gc_assert(!from_space_p(first));
2386     *where = first;
2387     return 1;
2388 }
2389
2390 static lispobj
2391 trans_list(lispobj object)
2392 {
2393     lispobj new_list_pointer;
2394     struct cons *cons, *new_cons;
2395     lispobj cdr;
2396
2397     gc_assert(from_space_p(object));
2398
2399     cons = (struct cons *) native_pointer(object);
2400
2401     /* Copy 'object'. */
2402     new_cons = (struct cons *) gc_quick_alloc(sizeof(struct cons));
2403     new_cons->car = cons->car;
2404     new_cons->cdr = cons->cdr; /* updated later */
2405     new_list_pointer = (lispobj)new_cons | lowtagof(object);
2406
2407     /* Grab the cdr before it is clobbered. */
2408     cdr = cons->cdr;
2409
2410     /* Set forwarding pointer (clobbers start of list). */
2411     cons->car = 0x01;
2412     cons->cdr = new_list_pointer;
2413
2414     /* Try to linearize the list in the cdr direction to help reduce
2415      * paging. */
2416     while (1) {
2417         lispobj  new_cdr;
2418         struct cons *cdr_cons, *new_cdr_cons;
2419
2420         if (lowtagof(cdr) != LIST_POINTER_LOWTAG || !from_space_p(cdr)
2421             || (*((lispobj *)native_pointer(cdr)) == 0x01))
2422             break;
2423
2424         cdr_cons = (struct cons *) native_pointer(cdr);
2425
2426         /* Copy 'cdr'. */
2427         new_cdr_cons = (struct cons*) gc_quick_alloc(sizeof(struct cons));
2428         new_cdr_cons->car = cdr_cons->car;
2429         new_cdr_cons->cdr = cdr_cons->cdr;
2430         new_cdr = (lispobj)new_cdr_cons | lowtagof(cdr);
2431
2432         /* Grab the cdr before it is clobbered. */
2433         cdr = cdr_cons->cdr;
2434
2435         /* Set forwarding pointer. */
2436         cdr_cons->car = 0x01;
2437         cdr_cons->cdr = new_cdr;
2438
2439         /* Update the cdr of the last cons copied into new space to
2440          * keep the newspace scavenge from having to do it. */
2441         new_cons->cdr = new_cdr;
2442
2443         new_cons = new_cdr_cons;
2444     }
2445
2446     return new_list_pointer;
2447 }
2448
2449 \f
2450 /*
2451  * scavenging and transporting other pointers
2452  */
2453
2454 static int
2455 scav_other_pointer(lispobj *where, lispobj object)
2456 {
2457     lispobj first, *first_pointer;
2458
2459     gc_assert(is_lisp_pointer(object));
2460
2461     /* Object is a pointer into from space - not FP. */
2462     first_pointer = (lispobj *) native_pointer(object);
2463
2464     first = (transother[TypeOf(*first_pointer)])(object);
2465
2466     if (first != object) {
2467         /* Set forwarding pointer. */
2468         first_pointer[0] = 0x01;
2469         first_pointer[1] = first;
2470         *where = first;
2471     }
2472
2473     gc_assert(is_lisp_pointer(first));
2474     gc_assert(!from_space_p(first));
2475
2476     return 1;
2477 }
2478 \f
2479 /*
2480  * immediate, boxed, and unboxed objects
2481  */
2482
2483 static int
2484 size_pointer(lispobj *where)
2485 {
2486     return 1;
2487 }
2488
2489 static int
2490 scav_immediate(lispobj *where, lispobj object)
2491 {
2492     return 1;
2493 }
2494
2495 static lispobj
2496 trans_immediate(lispobj object)
2497 {
2498     lose("trying to transport an immediate");
2499     return NIL; /* bogus return value to satisfy static type checking */
2500 }
2501
2502 static int
2503 size_immediate(lispobj *where)
2504 {
2505     return 1;
2506 }
2507
2508
2509 static int
2510 scav_boxed(lispobj *where, lispobj object)
2511 {
2512     return 1;
2513 }
2514
2515 static lispobj
2516 trans_boxed(lispobj object)
2517 {
2518     lispobj header;
2519     unsigned long length;
2520
2521     gc_assert(is_lisp_pointer(object));
2522
2523     header = *((lispobj *) native_pointer(object));
2524     length = HeaderValue(header) + 1;
2525     length = CEILING(length, 2);
2526
2527     return copy_object(object, length);
2528 }
2529
2530 static lispobj
2531 trans_boxed_large(lispobj object)
2532 {
2533     lispobj header;
2534     unsigned long length;
2535
2536     gc_assert(is_lisp_pointer(object));
2537
2538     header = *((lispobj *) native_pointer(object));
2539     length = HeaderValue(header) + 1;
2540     length = CEILING(length, 2);
2541
2542     return copy_large_object(object, length);
2543 }
2544
2545 static int
2546 size_boxed(lispobj *where)
2547 {
2548     lispobj header;
2549     unsigned long length;
2550
2551     header = *where;
2552     length = HeaderValue(header) + 1;
2553     length = CEILING(length, 2);
2554
2555     return length;
2556 }
2557
2558 static int
2559 scav_fdefn(lispobj *where, lispobj object)
2560 {
2561     struct fdefn *fdefn;
2562
2563     fdefn = (struct fdefn *)where;
2564
2565     /* FSHOW((stderr, "scav_fdefn, function = %p, raw_addr = %p\n", 
2566        fdefn->fun, fdefn->raw_addr)); */
2567
2568     if ((char *)(fdefn->fun + FUN_RAW_ADDR_OFFSET) == fdefn->raw_addr) {
2569         scavenge(where + 1, sizeof(struct fdefn)/sizeof(lispobj) - 1);
2570
2571         /* Don't write unnecessarily. */
2572         if (fdefn->raw_addr != (char *)(fdefn->fun + FUN_RAW_ADDR_OFFSET))
2573             fdefn->raw_addr = (char *)(fdefn->fun + FUN_RAW_ADDR_OFFSET);
2574
2575         return sizeof(struct fdefn) / sizeof(lispobj);
2576     } else {
2577         return 1;
2578     }
2579 }
2580
2581 static int
2582 scav_unboxed(lispobj *where, lispobj object)
2583 {
2584     unsigned long length;
2585
2586     length = HeaderValue(object) + 1;
2587     length = CEILING(length, 2);
2588
2589     return length;
2590 }
2591
2592 static lispobj
2593 trans_unboxed(lispobj object)
2594 {
2595     lispobj header;
2596     unsigned long length;
2597
2598
2599     gc_assert(is_lisp_pointer(object));
2600
2601     header = *((lispobj *) native_pointer(object));
2602     length = HeaderValue(header) + 1;
2603     length = CEILING(length, 2);
2604
2605     return copy_unboxed_object(object, length);
2606 }
2607
2608 static lispobj
2609 trans_unboxed_large(lispobj object)
2610 {
2611     lispobj header;
2612     unsigned long length;
2613
2614
2615     gc_assert(is_lisp_pointer(object));
2616
2617     header = *((lispobj *) native_pointer(object));
2618     length = HeaderValue(header) + 1;
2619     length = CEILING(length, 2);
2620
2621     return copy_large_unboxed_object(object, length);
2622 }
2623
2624 static int
2625 size_unboxed(lispobj *where)
2626 {
2627     lispobj header;
2628     unsigned long length;
2629
2630     header = *where;
2631     length = HeaderValue(header) + 1;
2632     length = CEILING(length, 2);
2633
2634     return length;
2635 }
2636 \f
2637 /*
2638  * vector-like objects
2639  */
2640
2641 #define NWORDS(x,y) (CEILING((x),(y)) / (y))
2642
2643 static int
2644 scav_string(lispobj *where, lispobj object)
2645 {
2646     struct vector *vector;
2647     int length, nwords;
2648
2649     /* NOTE: Strings contain one more byte of data than the length */
2650     /* slot indicates. */
2651
2652     vector = (struct vector *) where;
2653     length = fixnum_value(vector->length) + 1;
2654     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2655
2656     return nwords;
2657 }
2658
2659 static lispobj
2660 trans_string(lispobj object)
2661 {
2662     struct vector *vector;
2663     int length, nwords;
2664
2665     gc_assert(is_lisp_pointer(object));
2666
2667     /* NOTE: A string contains one more byte of data (a terminating
2668      * '\0' to help when interfacing with C functions) than indicated
2669      * by the length slot. */
2670
2671     vector = (struct vector *) native_pointer(object);
2672     length = fixnum_value(vector->length) + 1;
2673     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2674
2675     return copy_large_unboxed_object(object, nwords);
2676 }
2677
2678 static int
2679 size_string(lispobj *where)
2680 {
2681     struct vector *vector;
2682     int length, nwords;
2683
2684     /* NOTE: A string contains one more byte of data (a terminating
2685      * '\0' to help when interfacing with C functions) than indicated
2686      * by the length slot. */
2687
2688     vector = (struct vector *) where;
2689     length = fixnum_value(vector->length) + 1;
2690     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2691
2692     return nwords;
2693 }
2694
2695 /* FIXME: What does this mean? */
2696 int gencgc_hash = 1;
2697
2698 static int
2699 scav_vector(lispobj *where, lispobj object)
2700 {
2701     unsigned int kv_length;
2702     lispobj *kv_vector;
2703     unsigned int length = 0; /* (0 = dummy to stop GCC warning) */
2704     lispobj *hash_table;
2705     lispobj empty_symbol;
2706     unsigned int *index_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2707     unsigned int *next_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2708     unsigned int *hash_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2709     lispobj weak_p_obj;
2710     unsigned next_vector_length = 0;
2711
2712     /* FIXME: A comment explaining this would be nice. It looks as
2713      * though SB-VM:VECTOR-VALID-HASHING-SUBTYPE is set for EQ-based
2714      * hash tables in the Lisp HASH-TABLE code, and nowhere else. */
2715     if (HeaderValue(object) != subtype_VectorValidHashing)
2716         return 1;
2717
2718     if (!gencgc_hash) {
2719         /* This is set for backward compatibility. FIXME: Do we need
2720          * this any more? */
2721         *where = (subtype_VectorMustRehash << N_TYPE_BITS) | type_SimpleVector;
2722         return 1;
2723     }
2724
2725     kv_length = fixnum_value(where[1]);
2726     kv_vector = where + 2;  /* Skip the header and length. */
2727     /*FSHOW((stderr,"/kv_length = %d\n", kv_length));*/
2728
2729     /* Scavenge element 0, which may be a hash-table structure. */
2730     scavenge(where+2, 1);
2731     if (!is_lisp_pointer(where[2])) {
2732         lose("no pointer at %x in hash table", where[2]);
2733     }
2734     hash_table = (lispobj *)native_pointer(where[2]);
2735     /*FSHOW((stderr,"/hash_table = %x\n", hash_table));*/
2736     if (TypeOf(hash_table[0]) != type_InstanceHeader) {
2737         lose("hash table not instance (%x at %x)", hash_table[0], hash_table);
2738     }
2739
2740     /* Scavenge element 1, which should be some internal symbol that
2741      * the hash table code reserves for marking empty slots. */
2742     scavenge(where+3, 1);
2743     if (!is_lisp_pointer(where[3])) {
2744         lose("not empty-hash-table-slot symbol pointer: %x", where[3]);
2745     }
2746     empty_symbol = where[3];
2747     /* fprintf(stderr,"* empty_symbol = %x\n", empty_symbol);*/
2748     if (TypeOf(*(lispobj *)native_pointer(empty_symbol)) != type_SymbolHeader) {
2749         lose("not a symbol where empty-hash-table-slot symbol expected: %x",
2750              *(lispobj *)native_pointer(empty_symbol));
2751     }
2752
2753     /* Scavenge hash table, which will fix the positions of the other
2754      * needed objects. */
2755     scavenge(hash_table, 16);
2756
2757     /* Cross-check the kv_vector. */
2758     if (where != (lispobj *)native_pointer(hash_table[9])) {
2759         lose("hash_table table!=this table %x", hash_table[9]);
2760     }
2761
2762     /* WEAK-P */
2763     weak_p_obj = hash_table[10];
2764
2765     /* index vector */
2766     {
2767         lispobj index_vector_obj = hash_table[13];
2768
2769         if (is_lisp_pointer(index_vector_obj) &&
2770             (TypeOf(*(lispobj *)native_pointer(index_vector_obj)) == type_SimpleArrayUnsignedByte32)) {
2771             index_vector = ((unsigned int *)native_pointer(index_vector_obj)) + 2;
2772             /*FSHOW((stderr, "/index_vector = %x\n",index_vector));*/
2773             length = fixnum_value(((unsigned int *)native_pointer(index_vector_obj))[1]);
2774             /*FSHOW((stderr, "/length = %d\n", length));*/
2775         } else {
2776             lose("invalid index_vector %x", index_vector_obj);
2777         }
2778     }
2779
2780     /* next vector */
2781     {
2782         lispobj next_vector_obj = hash_table[14];
2783
2784         if (is_lisp_pointer(next_vector_obj) &&
2785             (TypeOf(*(lispobj *)native_pointer(next_vector_obj)) == type_SimpleArrayUnsignedByte32)) {
2786             next_vector = ((unsigned int *)native_pointer(next_vector_obj)) + 2;
2787             /*FSHOW((stderr, "/next_vector = %x\n", next_vector));*/
2788             next_vector_length = fixnum_value(((unsigned int *)native_pointer(next_vector_obj))[1]);
2789             /*FSHOW((stderr, "/next_vector_length = %d\n", next_vector_length));*/
2790         } else {
2791             lose("invalid next_vector %x", next_vector_obj);
2792         }
2793     }
2794
2795     /* maybe hash vector */
2796     {
2797         /* FIXME: This bare "15" offset should become a symbolic
2798          * expression of some sort. And all the other bare offsets
2799          * too. And the bare "16" in scavenge(hash_table, 16). And
2800          * probably other stuff too. Ugh.. */
2801         lispobj hash_vector_obj = hash_table[15];
2802
2803         if (is_lisp_pointer(hash_vector_obj) &&
2804             (TypeOf(*(lispobj *)native_pointer(hash_vector_obj))
2805              == type_SimpleArrayUnsignedByte32)) {
2806             hash_vector = ((unsigned int *)native_pointer(hash_vector_obj)) + 2;
2807             /*FSHOW((stderr, "/hash_vector = %x\n", hash_vector));*/
2808             gc_assert(fixnum_value(((unsigned int *)native_pointer(hash_vector_obj))[1])
2809                       == next_vector_length);
2810         } else {
2811             hash_vector = NULL;
2812             /*FSHOW((stderr, "/no hash_vector: %x\n", hash_vector_obj));*/
2813         }
2814     }
2815
2816     /* These lengths could be different as the index_vector can be a
2817      * different length from the others, a larger index_vector could help
2818      * reduce collisions. */
2819     gc_assert(next_vector_length*2 == kv_length);
2820
2821     /* now all set up.. */
2822
2823     /* Work through the KV vector. */
2824     {
2825         int i;
2826         for (i = 1; i < next_vector_length; i++) {
2827             lispobj old_key = kv_vector[2*i];
2828             unsigned int  old_index = (old_key & 0x1fffffff)%length;
2829
2830             /* Scavenge the key and value. */
2831             scavenge(&kv_vector[2*i],2);
2832
2833             /* Check whether the key has moved and is EQ based. */
2834             {
2835                 lispobj new_key = kv_vector[2*i];
2836                 unsigned int new_index = (new_key & 0x1fffffff)%length;
2837
2838                 if ((old_index != new_index) &&
2839                     ((!hash_vector) || (hash_vector[i] == 0x80000000)) &&
2840                     ((new_key != empty_symbol) ||
2841                      (kv_vector[2*i] != empty_symbol))) {
2842
2843                     /*FSHOW((stderr,
2844                            "* EQ key %d moved from %x to %x; index %d to %d\n",
2845                            i, old_key, new_key, old_index, new_index));*/
2846
2847                     if (index_vector[old_index] != 0) {
2848                         /*FSHOW((stderr, "/P1 %d\n", index_vector[old_index]));*/
2849
2850                         /* Unlink the key from the old_index chain. */
2851                         if (index_vector[old_index] == i) {
2852                             /*FSHOW((stderr, "/P2a %d\n", next_vector[i]));*/
2853                             index_vector[old_index] = next_vector[i];
2854                             /* Link it into the needing rehash chain. */
2855                             next_vector[i] = fixnum_value(hash_table[11]);
2856                             hash_table[11] = make_fixnum(i);
2857                             /*SHOW("P2");*/
2858                         } else {
2859                             unsigned prior = index_vector[old_index];
2860                             unsigned next = next_vector[prior];
2861
2862                             /*FSHOW((stderr, "/P3a %d %d\n", prior, next));*/
2863
2864                             while (next != 0) {
2865                                 /*FSHOW((stderr, "/P3b %d %d\n", prior, next));*/
2866                                 if (next == i) {
2867                                     /* Unlink it. */
2868                                     next_vector[prior] = next_vector[next];
2869                                     /* Link it into the needing rehash
2870                                      * chain. */
2871                                     next_vector[next] =
2872                                         fixnum_value(hash_table[11]);
2873                                     hash_table[11] = make_fixnum(next);
2874                                     /*SHOW("/P3");*/
2875                                     break;
2876                                 }
2877                                 prior = next;
2878                                 next = next_vector[next];
2879                             }
2880                         }
2881                     }
2882                 }
2883             }
2884         }
2885     }
2886     return (CEILING(kv_length + 2, 2));
2887 }
2888
2889 static lispobj
2890 trans_vector(lispobj object)
2891 {
2892     struct vector *vector;
2893     int length, nwords;
2894
2895     gc_assert(is_lisp_pointer(object));
2896
2897     vector = (struct vector *) native_pointer(object);
2898
2899     length = fixnum_value(vector->length);
2900     nwords = CEILING(length + 2, 2);
2901
2902     return copy_large_object(object, nwords);
2903 }
2904
2905 static int
2906 size_vector(lispobj *where)
2907 {
2908     struct vector *vector;
2909     int length, nwords;
2910
2911     vector = (struct vector *) where;
2912     length = fixnum_value(vector->length);
2913     nwords = CEILING(length + 2, 2);
2914
2915     return nwords;
2916 }
2917
2918
2919 static int
2920 scav_vector_bit(lispobj *where, lispobj object)
2921 {
2922     struct vector *vector;
2923     int length, nwords;
2924
2925     vector = (struct vector *) where;
2926     length = fixnum_value(vector->length);
2927     nwords = CEILING(NWORDS(length, 32) + 2, 2);
2928
2929     return nwords;
2930 }
2931
2932 static lispobj
2933 trans_vector_bit(lispobj object)
2934 {
2935     struct vector *vector;
2936     int length, nwords;
2937
2938     gc_assert(is_lisp_pointer(object));
2939
2940     vector = (struct vector *) native_pointer(object);
2941     length = fixnum_value(vector->length);
2942     nwords = CEILING(NWORDS(length, 32) + 2, 2);
2943
2944     return copy_large_unboxed_object(object, nwords);
2945 }
2946
2947 static int
2948 size_vector_bit(lispobj *where)
2949 {
2950     struct vector *vector;
2951     int length, nwords;
2952
2953     vector = (struct vector *) where;
2954     length = fixnum_value(vector->length);
2955     nwords = CEILING(NWORDS(length, 32) + 2, 2);
2956
2957     return nwords;
2958 }
2959
2960
2961 static int
2962 scav_vector_unsigned_byte_2(lispobj *where, lispobj object)
2963 {
2964     struct vector *vector;
2965     int length, nwords;
2966
2967     vector = (struct vector *) where;
2968     length = fixnum_value(vector->length);
2969     nwords = CEILING(NWORDS(length, 16) + 2, 2);
2970
2971     return nwords;
2972 }
2973
2974 static lispobj
2975 trans_vector_unsigned_byte_2(lispobj object)
2976 {
2977     struct vector *vector;
2978     int length, nwords;
2979
2980     gc_assert(is_lisp_pointer(object));
2981
2982     vector = (struct vector *) native_pointer(object);
2983     length = fixnum_value(vector->length);
2984     nwords = CEILING(NWORDS(length, 16) + 2, 2);
2985
2986     return copy_large_unboxed_object(object, nwords);
2987 }
2988
2989 static int
2990 size_vector_unsigned_byte_2(lispobj *where)
2991 {
2992     struct vector *vector;
2993     int length, nwords;
2994
2995     vector = (struct vector *) where;
2996     length = fixnum_value(vector->length);
2997     nwords = CEILING(NWORDS(length, 16) + 2, 2);
2998
2999     return nwords;
3000 }
3001
3002
3003 static int
3004 scav_vector_unsigned_byte_4(lispobj *where, lispobj object)
3005 {
3006     struct vector *vector;
3007     int length, nwords;
3008
3009     vector = (struct vector *) where;
3010     length = fixnum_value(vector->length);
3011     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3012
3013     return nwords;
3014 }
3015
3016 static lispobj
3017 trans_vector_unsigned_byte_4(lispobj object)
3018 {
3019     struct vector *vector;
3020     int length, nwords;
3021
3022     gc_assert(is_lisp_pointer(object));
3023
3024     vector = (struct vector *) native_pointer(object);
3025     length = fixnum_value(vector->length);
3026     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3027
3028     return copy_large_unboxed_object(object, nwords);
3029 }
3030
3031 static int
3032 size_vector_unsigned_byte_4(lispobj *where)
3033 {
3034     struct vector *vector;
3035     int length, nwords;
3036
3037     vector = (struct vector *) where;
3038     length = fixnum_value(vector->length);
3039     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3040
3041     return nwords;
3042 }
3043
3044 static int
3045 scav_vector_unsigned_byte_8(lispobj *where, lispobj object)
3046 {
3047     struct vector *vector;
3048     int length, nwords;
3049
3050     vector = (struct vector *) where;
3051     length = fixnum_value(vector->length);
3052     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3053
3054     return nwords;
3055 }
3056
3057 static lispobj
3058 trans_vector_unsigned_byte_8(lispobj object)
3059 {
3060     struct vector *vector;
3061     int length, nwords;
3062
3063     gc_assert(is_lisp_pointer(object));
3064
3065     vector = (struct vector *) native_pointer(object);
3066     length = fixnum_value(vector->length);
3067     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3068
3069     return copy_large_unboxed_object(object, nwords);
3070 }
3071
3072 static int
3073 size_vector_unsigned_byte_8(lispobj *where)
3074 {
3075     struct vector *vector;
3076     int length, nwords;
3077
3078     vector = (struct vector *) where;
3079     length = fixnum_value(vector->length);
3080     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3081
3082     return nwords;
3083 }
3084
3085
3086 static int
3087 scav_vector_unsigned_byte_16(lispobj *where, lispobj object)
3088 {
3089     struct vector *vector;
3090     int length, nwords;
3091
3092     vector = (struct vector *) where;
3093     length = fixnum_value(vector->length);
3094     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3095
3096     return nwords;
3097 }
3098
3099 static lispobj
3100 trans_vector_unsigned_byte_16(lispobj object)
3101 {
3102     struct vector *vector;
3103     int length, nwords;
3104
3105     gc_assert(is_lisp_pointer(object));
3106
3107     vector = (struct vector *) native_pointer(object);
3108     length = fixnum_value(vector->length);
3109     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3110
3111     return copy_large_unboxed_object(object, nwords);
3112 }
3113
3114 static int
3115 size_vector_unsigned_byte_16(lispobj *where)
3116 {
3117     struct vector *vector;
3118     int length, nwords;
3119
3120     vector = (struct vector *) where;
3121     length = fixnum_value(vector->length);
3122     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3123
3124     return nwords;
3125 }
3126
3127 static int
3128 scav_vector_unsigned_byte_32(lispobj *where, lispobj object)
3129 {
3130     struct vector *vector;
3131     int length, nwords;
3132
3133     vector = (struct vector *) where;
3134     length = fixnum_value(vector->length);
3135     nwords = CEILING(length + 2, 2);
3136
3137     return nwords;
3138 }
3139
3140 static lispobj
3141 trans_vector_unsigned_byte_32(lispobj object)
3142 {
3143     struct vector *vector;
3144     int length, nwords;
3145
3146     gc_assert(is_lisp_pointer(object));
3147
3148     vector = (struct vector *) native_pointer(object);
3149     length = fixnum_value(vector->length);
3150     nwords = CEILING(length + 2, 2);
3151
3152     return copy_large_unboxed_object(object, nwords);
3153 }
3154
3155 static int
3156 size_vector_unsigned_byte_32(lispobj *where)
3157 {
3158     struct vector *vector;
3159     int length, nwords;
3160
3161     vector = (struct vector *) where;
3162     length = fixnum_value(vector->length);
3163     nwords = CEILING(length + 2, 2);
3164
3165     return nwords;
3166 }
3167
3168 static int
3169 scav_vector_single_float(lispobj *where, lispobj object)
3170 {
3171     struct vector *vector;
3172     int length, nwords;
3173
3174     vector = (struct vector *) where;
3175     length = fixnum_value(vector->length);
3176     nwords = CEILING(length + 2, 2);
3177
3178     return nwords;
3179 }
3180
3181 static lispobj
3182 trans_vector_single_float(lispobj object)
3183 {
3184     struct vector *vector;
3185     int length, nwords;
3186
3187     gc_assert(is_lisp_pointer(object));
3188
3189     vector = (struct vector *) native_pointer(object);
3190     length = fixnum_value(vector->length);
3191     nwords = CEILING(length + 2, 2);
3192
3193     return copy_large_unboxed_object(object, nwords);
3194 }
3195
3196 static int
3197 size_vector_single_float(lispobj *where)
3198 {
3199     struct vector *vector;
3200     int length, nwords;
3201
3202     vector = (struct vector *) where;
3203     length = fixnum_value(vector->length);
3204     nwords = CEILING(length + 2, 2);
3205
3206     return nwords;
3207 }
3208
3209 static int
3210 scav_vector_double_float(lispobj *where, lispobj object)
3211 {
3212     struct vector *vector;
3213     int length, nwords;
3214
3215     vector = (struct vector *) where;
3216     length = fixnum_value(vector->length);
3217     nwords = CEILING(length * 2 + 2, 2);
3218
3219     return nwords;
3220 }
3221
3222 static lispobj
3223 trans_vector_double_float(lispobj object)
3224 {
3225     struct vector *vector;
3226     int length, nwords;
3227
3228     gc_assert(is_lisp_pointer(object));
3229
3230     vector = (struct vector *) native_pointer(object);
3231     length = fixnum_value(vector->length);
3232     nwords = CEILING(length * 2 + 2, 2);
3233
3234     return copy_large_unboxed_object(object, nwords);
3235 }
3236
3237 static int
3238 size_vector_double_float(lispobj *where)
3239 {
3240     struct vector *vector;
3241     int length, nwords;
3242
3243     vector = (struct vector *) where;
3244     length = fixnum_value(vector->length);
3245     nwords = CEILING(length * 2 + 2, 2);
3246
3247     return nwords;
3248 }
3249
3250 #ifdef type_SimpleArrayLongFloat
3251 static int
3252 scav_vector_long_float(lispobj *where, lispobj object)
3253 {
3254     struct vector *vector;
3255     int length, nwords;
3256
3257     vector = (struct vector *) where;
3258     length = fixnum_value(vector->length);
3259     nwords = CEILING(length * 3 + 2, 2);
3260
3261     return nwords;
3262 }
3263
3264 static lispobj
3265 trans_vector_long_float(lispobj object)
3266 {
3267     struct vector *vector;
3268     int length, nwords;
3269
3270     gc_assert(is_lisp_pointer(object));
3271
3272     vector = (struct vector *) native_pointer(object);
3273     length = fixnum_value(vector->length);
3274     nwords = CEILING(length * 3 + 2, 2);
3275
3276     return copy_large_unboxed_object(object, nwords);
3277 }
3278
3279 static int
3280 size_vector_long_float(lispobj *where)
3281 {
3282     struct vector *vector;
3283     int length, nwords;
3284
3285     vector = (struct vector *) where;
3286     length = fixnum_value(vector->length);
3287     nwords = CEILING(length * 3 + 2, 2);
3288
3289     return nwords;
3290 }
3291 #endif
3292
3293
3294 #ifdef type_SimpleArrayComplexSingleFloat
3295 static int
3296 scav_vector_complex_single_float(lispobj *where, lispobj object)
3297 {
3298     struct vector *vector;
3299     int length, nwords;
3300
3301     vector = (struct vector *) where;
3302     length = fixnum_value(vector->length);
3303     nwords = CEILING(length * 2 + 2, 2);
3304
3305     return nwords;
3306 }
3307
3308 static lispobj
3309 trans_vector_complex_single_float(lispobj object)
3310 {
3311     struct vector *vector;
3312     int length, nwords;
3313
3314     gc_assert(is_lisp_pointer(object));
3315
3316     vector = (struct vector *) native_pointer(object);
3317     length = fixnum_value(vector->length);
3318     nwords = CEILING(length * 2 + 2, 2);
3319
3320     return copy_large_unboxed_object(object, nwords);
3321 }
3322
3323 static int
3324 size_vector_complex_single_float(lispobj *where)
3325 {
3326     struct vector *vector;
3327     int length, nwords;
3328
3329     vector = (struct vector *) where;
3330     length = fixnum_value(vector->length);
3331     nwords = CEILING(length * 2 + 2, 2);
3332
3333     return nwords;
3334 }
3335 #endif
3336
3337 #ifdef type_SimpleArrayComplexDoubleFloat
3338 static int
3339 scav_vector_complex_double_float(lispobj *where, lispobj object)
3340 {
3341     struct vector *vector;
3342     int length, nwords;
3343
3344     vector = (struct vector *) where;
3345     length = fixnum_value(vector->length);
3346     nwords = CEILING(length * 4 + 2, 2);
3347
3348     return nwords;
3349 }
3350
3351 static lispobj
3352 trans_vector_complex_double_float(lispobj object)
3353 {
3354     struct vector *vector;
3355     int length, nwords;
3356
3357     gc_assert(is_lisp_pointer(object));
3358
3359     vector = (struct vector *) native_pointer(object);
3360     length = fixnum_value(vector->length);
3361     nwords = CEILING(length * 4 + 2, 2);
3362
3363     return copy_large_unboxed_object(object, nwords);
3364 }
3365
3366 static int
3367 size_vector_complex_double_float(lispobj *where)
3368 {
3369     struct vector *vector;
3370     int length, nwords;
3371
3372     vector = (struct vector *) where;
3373     length = fixnum_value(vector->length);
3374     nwords = CEILING(length * 4 + 2, 2);
3375
3376     return nwords;
3377 }
3378 #endif
3379
3380
3381 #ifdef type_SimpleArrayComplexLongFloat
3382 static int
3383 scav_vector_complex_long_float(lispobj *where, lispobj object)
3384 {
3385     struct vector *vector;
3386     int length, nwords;
3387
3388     vector = (struct vector *) where;
3389     length = fixnum_value(vector->length);
3390     nwords = CEILING(length * 6 + 2, 2);
3391
3392     return nwords;
3393 }
3394
3395 static lispobj
3396 trans_vector_complex_long_float(lispobj object)
3397 {
3398     struct vector *vector;
3399     int length, nwords;
3400
3401     gc_assert(is_lisp_pointer(object));
3402
3403     vector = (struct vector *) native_pointer(object);
3404     length = fixnum_value(vector->length);
3405     nwords = CEILING(length * 6 + 2, 2);
3406
3407     return copy_large_unboxed_object(object, nwords);
3408 }
3409
3410 static int
3411 size_vector_complex_long_float(lispobj *where)
3412 {
3413     struct vector *vector;
3414     int length, nwords;
3415
3416     vector = (struct vector *) where;
3417     length = fixnum_value(vector->length);
3418     nwords = CEILING(length * 6 + 2, 2);
3419
3420     return nwords;
3421 }
3422 #endif
3423
3424 \f
3425 /*
3426  * weak pointers
3427  */
3428
3429 /* XX This is a hack adapted from cgc.c. These don't work too well with the
3430  * gencgc as a list of the weak pointers is maintained within the
3431  * objects which causes writes to the pages. A limited attempt is made
3432  * to avoid unnecessary writes, but this needs a re-think. */
3433
3434 #define WEAK_POINTER_NWORDS \
3435     CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
3436
3437 static int
3438 scav_weak_pointer(lispobj *where, lispobj object)
3439 {
3440     struct weak_pointer *wp = weak_pointers;
3441     /* Push the weak pointer onto the list of weak pointers.
3442      * Do I have to watch for duplicates? Originally this was
3443      * part of trans_weak_pointer but that didn't work in the
3444      * case where the WP was in a promoted region.
3445      */
3446
3447     /* Check whether it's already in the list. */
3448     while (wp != NULL) {
3449         if (wp == (struct weak_pointer*)where) {
3450             break;
3451         }
3452         wp = wp->next;
3453     }
3454     if (wp == NULL) {
3455         /* Add it to the start of the list. */
3456         wp = (struct weak_pointer*)where;
3457         if (wp->next != weak_pointers) {
3458             wp->next = weak_pointers;
3459         } else {
3460             /*SHOW("avoided write to weak pointer");*/
3461         }
3462         weak_pointers = wp;
3463     }
3464
3465     /* Do not let GC scavenge the value slot of the weak pointer.
3466      * (That is why it is a weak pointer.) */
3467
3468     return WEAK_POINTER_NWORDS;
3469 }
3470
3471 static lispobj
3472 trans_weak_pointer(lispobj object)
3473 {
3474     lispobj copy;
3475     /* struct weak_pointer *wp; */
3476
3477     gc_assert(is_lisp_pointer(object));
3478
3479 #if defined(DEBUG_WEAK)
3480     FSHOW((stderr, "Transporting weak pointer from 0x%08x\n", object));
3481 #endif
3482
3483     /* Need to remember where all the weak pointers are that have */
3484     /* been transported so they can be fixed up in a post-GC pass. */
3485
3486     copy = copy_object(object, WEAK_POINTER_NWORDS);
3487     /*  wp = (struct weak_pointer *) native_pointer(copy);*/
3488         
3489
3490     /* Push the weak pointer onto the list of weak pointers. */
3491     /*  wp->next = weak_pointers;
3492      *  weak_pointers = wp;*/
3493
3494     return copy;
3495 }
3496
3497 static int
3498 size_weak_pointer(lispobj *where)
3499 {
3500     return WEAK_POINTER_NWORDS;
3501 }
3502
3503 void scan_weak_pointers(void)
3504 {
3505     struct weak_pointer *wp;
3506     for (wp = weak_pointers; wp != NULL; wp = wp->next) {
3507         lispobj value = wp->value;
3508         lispobj *first_pointer;
3509
3510         first_pointer = (lispobj *)native_pointer(value);
3511
3512         /*
3513         FSHOW((stderr, "/weak pointer at 0x%08x\n", (unsigned long) wp));
3514         FSHOW((stderr, "/value: 0x%08x\n", (unsigned long) value));
3515         */
3516
3517         if (is_lisp_pointer(value) && from_space_p(value)) {
3518             /* Now, we need to check whether the object has been forwarded. If
3519              * it has been, the weak pointer is still good and needs to be
3520              * updated. Otherwise, the weak pointer needs to be nil'ed
3521              * out. */
3522             if (first_pointer[0] == 0x01) {
3523                 wp->value = first_pointer[1];
3524             } else {
3525                 /* Break it. */
3526                 SHOW("broken");
3527                 wp->value = NIL;
3528                 wp->broken = T;
3529             }
3530         }
3531     }
3532 }
3533 \f
3534 /*
3535  * initialization
3536  */
3537
3538 static int
3539 scav_lose(lispobj *where, lispobj object)
3540 {
3541     lose("no scavenge function for object 0x%08x", (unsigned long) object);
3542     return 0; /* bogus return value to satisfy static type checking */
3543 }
3544
3545 static lispobj
3546 trans_lose(lispobj object)
3547 {
3548     lose("no transport function for object 0x%08x", (unsigned long) object);
3549     return NIL; /* bogus return value to satisfy static type checking */
3550 }
3551
3552 static int
3553 size_lose(lispobj *where)
3554 {
3555     lose("no size function for object at 0x%08x", (unsigned long) where);
3556     return 1; /* bogus return value to satisfy static type checking */
3557 }
3558
3559 static void
3560 gc_init_tables(void)
3561 {
3562     int i;
3563
3564     /* Set default value in all slots of scavenge table. */
3565     for (i = 0; i < 256; i++) { /* FIXME: bare constant length, ick! */
3566         scavtab[i] = scav_lose;
3567     }
3568
3569     /* For each type which can be selected by the low 3 bits of the tag
3570      * alone, set multiple entries in our 8-bit scavenge table (one for each
3571      * possible value of the high 5 bits). */
3572     for (i = 0; i < 32; i++) { /* FIXME: bare constant length, ick! */
3573         scavtab[EVEN_FIXNUM_LOWTAG|(i<<3)] = scav_immediate;
3574         scavtab[FUN_POINTER_LOWTAG|(i<<3)] = scav_fun_pointer;
3575         /* skipping OTHER_IMMEDIATE_0_LOWTAG */
3576         scavtab[LIST_POINTER_LOWTAG|(i<<3)] = scav_list_pointer;
3577         scavtab[ODD_FIXNUM_LOWTAG|(i<<3)] = scav_immediate;
3578         scavtab[INSTANCE_POINTER_LOWTAG|(i<<3)] = scav_instance_pointer;
3579         /* skipping OTHER_IMMEDIATE_1_LOWTAG */
3580         scavtab[OTHER_POINTER_LOWTAG|(i<<3)] = scav_other_pointer;
3581     }
3582
3583     /* Other-pointer types (those selected by all eight bits of the tag) get
3584      * one entry each in the scavenge table. */
3585     scavtab[type_Bignum] = scav_unboxed;
3586     scavtab[type_Ratio] = scav_boxed;
3587     scavtab[type_SingleFloat] = scav_unboxed;
3588     scavtab[type_DoubleFloat] = scav_unboxed;
3589 #ifdef type_LongFloat
3590     scavtab[type_LongFloat] = scav_unboxed;
3591 #endif
3592     scavtab[type_Complex] = scav_boxed;
3593 #ifdef type_ComplexSingleFloat
3594     scavtab[type_ComplexSingleFloat] = scav_unboxed;
3595 #endif
3596 #ifdef type_ComplexDoubleFloat
3597     scavtab[type_ComplexDoubleFloat] = scav_unboxed;
3598 #endif
3599 #ifdef type_ComplexLongFloat
3600     scavtab[type_ComplexLongFloat] = scav_unboxed;
3601 #endif
3602     scavtab[type_SimpleArray] = scav_boxed;
3603     scavtab[type_SimpleString] = scav_string;
3604     scavtab[type_SimpleBitVector] = scav_vector_bit;
3605     scavtab[type_SimpleVector] = scav_vector;
3606     scavtab[type_SimpleArrayUnsignedByte2] = scav_vector_unsigned_byte_2;
3607     scavtab[type_SimpleArrayUnsignedByte4] = scav_vector_unsigned_byte_4;
3608     scavtab[type_SimpleArrayUnsignedByte8] = scav_vector_unsigned_byte_8;
3609     scavtab[type_SimpleArrayUnsignedByte16] = scav_vector_unsigned_byte_16;
3610     scavtab[type_SimpleArrayUnsignedByte32] = scav_vector_unsigned_byte_32;
3611 #ifdef type_SimpleArraySignedByte8
3612     scavtab[type_SimpleArraySignedByte8] = scav_vector_unsigned_byte_8;
3613 #endif
3614 #ifdef type_SimpleArraySignedByte16
3615     scavtab[type_SimpleArraySignedByte16] = scav_vector_unsigned_byte_16;
3616 #endif
3617 #ifdef type_SimpleArraySignedByte30
3618     scavtab[type_SimpleArraySignedByte30] = scav_vector_unsigned_byte_32;
3619 #endif
3620 #ifdef type_SimpleArraySignedByte32
3621     scavtab[type_SimpleArraySignedByte32] = scav_vector_unsigned_byte_32;
3622 #endif
3623     scavtab[type_SimpleArraySingleFloat] = scav_vector_single_float;
3624     scavtab[type_SimpleArrayDoubleFloat] = scav_vector_double_float;
3625 #ifdef type_SimpleArrayLongFloat
3626     scavtab[type_SimpleArrayLongFloat] = scav_vector_long_float;
3627 #endif
3628 #ifdef type_SimpleArrayComplexSingleFloat
3629     scavtab[type_SimpleArrayComplexSingleFloat] = scav_vector_complex_single_float;
3630 #endif
3631 #ifdef type_SimpleArrayComplexDoubleFloat
3632     scavtab[type_SimpleArrayComplexDoubleFloat] = scav_vector_complex_double_float;
3633 #endif
3634 #ifdef type_SimpleArrayComplexLongFloat
3635     scavtab[type_SimpleArrayComplexLongFloat] = scav_vector_complex_long_float;
3636 #endif
3637     scavtab[type_ComplexString] = scav_boxed;
3638     scavtab[type_ComplexBitVector] = scav_boxed;
3639     scavtab[type_ComplexVector] = scav_boxed;
3640     scavtab[type_ComplexArray] = scav_boxed;
3641     scavtab[type_CodeHeader] = scav_code_header;
3642     /*scavtab[type_SimpleFunHeader] = scav_fun_header;*/
3643     /*scavtab[type_ClosureFunHeader] = scav_fun_header;*/
3644     /*scavtab[type_ReturnPcHeader] = scav_return_pc_header;*/
3645 #ifdef __i386__
3646     scavtab[type_ClosureHeader] = scav_closure_header;
3647     scavtab[type_FuncallableInstanceHeader] = scav_closure_header;
3648 #else
3649     scavtab[type_ClosureHeader] = scav_boxed;
3650     scavtab[type_FuncallableInstanceHeader] = scav_boxed;
3651 #endif
3652     scavtab[type_ValueCellHeader] = scav_boxed;
3653     scavtab[type_SymbolHeader] = scav_boxed;
3654     scavtab[type_BaseChar] = scav_immediate;
3655     scavtab[type_Sap] = scav_unboxed;
3656     scavtab[type_UnboundMarker] = scav_immediate;
3657     scavtab[type_WeakPointer] = scav_weak_pointer;
3658     scavtab[type_InstanceHeader] = scav_boxed;
3659     scavtab[type_Fdefn] = scav_fdefn;
3660
3661     /* transport other table, initialized same way as scavtab */
3662     for (i = 0; i < 256; i++)
3663         transother[i] = trans_lose;
3664     transother[type_Bignum] = trans_unboxed;
3665     transother[type_Ratio] = trans_boxed;
3666     transother[type_SingleFloat] = trans_unboxed;
3667     transother[type_DoubleFloat] = trans_unboxed;
3668 #ifdef type_LongFloat
3669     transother[type_LongFloat] = trans_unboxed;
3670 #endif
3671     transother[type_Complex] = trans_boxed;
3672 #ifdef type_ComplexSingleFloat
3673     transother[type_ComplexSingleFloat] = trans_unboxed;
3674 #endif
3675 #ifdef type_ComplexDoubleFloat
3676     transother[type_ComplexDoubleFloat] = trans_unboxed;
3677 #endif
3678 #ifdef type_ComplexLongFloat
3679     transother[type_ComplexLongFloat] = trans_unboxed;
3680 #endif
3681     transother[type_SimpleArray] = trans_boxed_large;
3682     transother[type_SimpleString] = trans_string;
3683     transother[type_SimpleBitVector] = trans_vector_bit;
3684     transother[type_SimpleVector] = trans_vector;
3685     transother[type_SimpleArrayUnsignedByte2] = trans_vector_unsigned_byte_2;
3686     transother[type_SimpleArrayUnsignedByte4] = trans_vector_unsigned_byte_4;
3687     transother[type_SimpleArrayUnsignedByte8] = trans_vector_unsigned_byte_8;
3688     transother[type_SimpleArrayUnsignedByte16] = trans_vector_unsigned_byte_16;
3689     transother[type_SimpleArrayUnsignedByte32] = trans_vector_unsigned_byte_32;
3690 #ifdef type_SimpleArraySignedByte8
3691     transother[type_SimpleArraySignedByte8] = trans_vector_unsigned_byte_8;
3692 #endif
3693 #ifdef type_SimpleArraySignedByte16
3694     transother[type_SimpleArraySignedByte16] = trans_vector_unsigned_byte_16;
3695 #endif
3696 #ifdef type_SimpleArraySignedByte30
3697     transother[type_SimpleArraySignedByte30] = trans_vector_unsigned_byte_32;
3698 #endif
3699 #ifdef type_SimpleArraySignedByte32
3700     transother[type_SimpleArraySignedByte32] = trans_vector_unsigned_byte_32;
3701 #endif
3702     transother[type_SimpleArraySingleFloat] = trans_vector_single_float;
3703     transother[type_SimpleArrayDoubleFloat] = trans_vector_double_float;
3704 #ifdef type_SimpleArrayLongFloat
3705     transother[type_SimpleArrayLongFloat] = trans_vector_long_float;
3706 #endif
3707 #ifdef type_SimpleArrayComplexSingleFloat
3708     transother[type_SimpleArrayComplexSingleFloat] = trans_vector_complex_single_float;
3709 #endif
3710 #ifdef type_SimpleArrayComplexDoubleFloat
3711     transother[type_SimpleArrayComplexDoubleFloat] = trans_vector_complex_double_float;
3712 #endif
3713 #ifdef type_SimpleArrayComplexLongFloat
3714     transother[type_SimpleArrayComplexLongFloat] = trans_vector_complex_long_float;
3715 #endif
3716     transother[type_ComplexString] = trans_boxed;
3717     transother[type_ComplexBitVector] = trans_boxed;
3718     transother[type_ComplexVector] = trans_boxed;
3719     transother[type_ComplexArray] = trans_boxed;
3720     transother[type_CodeHeader] = trans_code_header;
3721     transother[type_SimpleFunHeader] = trans_fun_header;
3722     transother[type_ClosureFunHeader] = trans_fun_header;
3723     transother[type_ReturnPcHeader] = trans_return_pc_header;
3724     transother[type_ClosureHeader] = trans_boxed;
3725     transother[type_FuncallableInstanceHeader] = trans_boxed;
3726     transother[type_ValueCellHeader] = trans_boxed;
3727     transother[type_SymbolHeader] = trans_boxed;
3728     transother[type_BaseChar] = trans_immediate;
3729     transother[type_Sap] = trans_unboxed;
3730     transother[type_UnboundMarker] = trans_immediate;
3731     transother[type_WeakPointer] = trans_weak_pointer;
3732     transother[type_InstanceHeader] = trans_boxed;
3733     transother[type_Fdefn] = trans_boxed;
3734
3735     /* size table, initialized the same way as scavtab */
3736     for (i = 0; i < 256; i++)
3737         sizetab[i] = size_lose;
3738     for (i = 0; i < 32; i++) {
3739         sizetab[EVEN_FIXNUM_LOWTAG|(i<<3)] = size_immediate;
3740         sizetab[FUN_POINTER_LOWTAG|(i<<3)] = size_pointer;
3741         /* skipping OTHER_IMMEDIATE_0_LOWTAG */
3742         sizetab[LIST_POINTER_LOWTAG|(i<<3)] = size_pointer;
3743         sizetab[ODD_FIXNUM_LOWTAG|(i<<3)] = size_immediate;
3744         sizetab[INSTANCE_POINTER_LOWTAG|(i<<3)] = size_pointer;
3745         /* skipping OTHER_IMMEDIATE_1_LOWTAG */
3746         sizetab[OTHER_POINTER_LOWTAG|(i<<3)] = size_pointer;
3747     }
3748     sizetab[type_Bignum] = size_unboxed;
3749     sizetab[type_Ratio] = size_boxed;
3750     sizetab[type_SingleFloat] = size_unboxed;
3751     sizetab[type_DoubleFloat] = size_unboxed;
3752 #ifdef type_LongFloat
3753     sizetab[type_LongFloat] = size_unboxed;
3754 #endif
3755     sizetab[type_Complex] = size_boxed;
3756 #ifdef type_ComplexSingleFloat
3757     sizetab[type_ComplexSingleFloat] = size_unboxed;
3758 #endif
3759 #ifdef type_ComplexDoubleFloat
3760     sizetab[type_ComplexDoubleFloat] = size_unboxed;
3761 #endif
3762 #ifdef type_ComplexLongFloat
3763     sizetab[type_ComplexLongFloat] = size_unboxed;
3764 #endif
3765     sizetab[type_SimpleArray] = size_boxed;
3766     sizetab[type_SimpleString] = size_string;
3767     sizetab[type_SimpleBitVector] = size_vector_bit;
3768     sizetab[type_SimpleVector] = size_vector;
3769     sizetab[type_SimpleArrayUnsignedByte2] = size_vector_unsigned_byte_2;
3770     sizetab[type_SimpleArrayUnsignedByte4] = size_vector_unsigned_byte_4;
3771     sizetab[type_SimpleArrayUnsignedByte8] = size_vector_unsigned_byte_8;
3772     sizetab[type_SimpleArrayUnsignedByte16] = size_vector_unsigned_byte_16;
3773     sizetab[type_SimpleArrayUnsignedByte32] = size_vector_unsigned_byte_32;
3774 #ifdef type_SimpleArraySignedByte8
3775     sizetab[type_SimpleArraySignedByte8] = size_vector_unsigned_byte_8;
3776 #endif
3777 #ifdef type_SimpleArraySignedByte16
3778     sizetab[type_SimpleArraySignedByte16] = size_vector_unsigned_byte_16;
3779 #endif
3780 #ifdef type_SimpleArraySignedByte30
3781     sizetab[type_SimpleArraySignedByte30] = size_vector_unsigned_byte_32;
3782 #endif
3783 #ifdef type_SimpleArraySignedByte32
3784     sizetab[type_SimpleArraySignedByte32] = size_vector_unsigned_byte_32;
3785 #endif
3786     sizetab[type_SimpleArraySingleFloat] = size_vector_single_float;
3787     sizetab[type_SimpleArrayDoubleFloat] = size_vector_double_float;
3788 #ifdef type_SimpleArrayLongFloat
3789     sizetab[type_SimpleArrayLongFloat] = size_vector_long_float;
3790 #endif
3791 #ifdef type_SimpleArrayComplexSingleFloat
3792     sizetab[type_SimpleArrayComplexSingleFloat] = size_vector_complex_single_float;
3793 #endif
3794 #ifdef type_SimpleArrayComplexDoubleFloat
3795     sizetab[type_SimpleArrayComplexDoubleFloat] = size_vector_complex_double_float;
3796 #endif
3797 #ifdef type_SimpleArrayComplexLongFloat
3798     sizetab[type_SimpleArrayComplexLongFloat] = size_vector_complex_long_float;
3799 #endif
3800     sizetab[type_ComplexString] = size_boxed;
3801     sizetab[type_ComplexBitVector] = size_boxed;
3802     sizetab[type_ComplexVector] = size_boxed;
3803     sizetab[type_ComplexArray] = size_boxed;
3804     sizetab[type_CodeHeader] = size_code_header;
3805 #if 0
3806     /* We shouldn't see these, so just lose if it happens. */
3807     sizetab[type_SimpleFunHeader] = size_function_header;
3808     sizetab[type_ClosureFunHeader] = size_function_header;
3809     sizetab[type_ReturnPcHeader] = size_return_pc_header;
3810 #endif
3811     sizetab[type_ClosureHeader] = size_boxed;
3812     sizetab[type_FuncallableInstanceHeader] = size_boxed;
3813     sizetab[type_ValueCellHeader] = size_boxed;
3814     sizetab[type_SymbolHeader] = size_boxed;
3815     sizetab[type_BaseChar] = size_immediate;
3816     sizetab[type_Sap] = size_unboxed;
3817     sizetab[type_UnboundMarker] = size_immediate;
3818     sizetab[type_WeakPointer] = size_weak_pointer;
3819     sizetab[type_InstanceHeader] = size_boxed;
3820     sizetab[type_Fdefn] = size_boxed;
3821 }
3822 \f
3823 /* Scan an area looking for an object which encloses the given pointer.
3824  * Return the object start on success or NULL on failure. */
3825 static lispobj *
3826 search_space(lispobj *start, size_t words, lispobj *pointer)
3827 {
3828     while (words > 0) {
3829         size_t count = 1;
3830         lispobj thing = *start;
3831
3832         /* If thing is an immediate then this is a cons. */
3833         if (is_lisp_pointer(thing)
3834             || ((thing & 3) == 0) /* fixnum */
3835             || (TypeOf(thing) == type_BaseChar)
3836             || (TypeOf(thing) == type_UnboundMarker))
3837             count = 2;
3838         else
3839             count = (sizetab[TypeOf(thing)])(start);
3840
3841         /* Check whether the pointer is within this object. */
3842         if ((pointer >= start) && (pointer < (start+count))) {
3843             /* found it! */
3844             /*FSHOW((stderr,"/found %x in %x %x\n", pointer, start, thing));*/
3845             return(start);
3846         }
3847
3848         /* Round up the count. */
3849         count = CEILING(count,2);
3850
3851         start += count;
3852         words -= count;
3853     }
3854     return (NULL);
3855 }
3856
3857 static lispobj*
3858 search_read_only_space(lispobj *pointer)
3859 {
3860     lispobj* start = (lispobj*)READ_ONLY_SPACE_START;
3861     lispobj* end = (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER);
3862     if ((pointer < start) || (pointer >= end))
3863         return NULL;
3864     return (search_space(start, (pointer+2)-start, pointer));
3865 }
3866
3867 static lispobj *
3868 search_static_space(lispobj *pointer)
3869 {
3870     lispobj* start = (lispobj*)STATIC_SPACE_START;
3871     lispobj* end = (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER);
3872     if ((pointer < start) || (pointer >= end))
3873         return NULL;
3874     return (search_space(start, (pointer+2)-start, pointer));
3875 }
3876
3877 /* a faster version for searching the dynamic space. This will work even
3878  * if the object is in a current allocation region. */
3879 lispobj *
3880 search_dynamic_space(lispobj *pointer)
3881 {
3882     int  page_index = find_page_index(pointer);
3883     lispobj *start;
3884
3885     /* The address may be invalid, so do some checks. */
3886     if ((page_index == -1) || (page_table[page_index].allocated == FREE_PAGE))
3887         return NULL;
3888     start = (lispobj *)((void *)page_address(page_index)
3889                         + page_table[page_index].first_object_offset);
3890     return (search_space(start, (pointer+2)-start, pointer));
3891 }
3892
3893 /* Is there any possibility that pointer is a valid Lisp object
3894  * reference, and/or something else (e.g. subroutine call return
3895  * address) which should prevent us from moving the referred-to thing? */
3896 static int
3897 possibly_valid_dynamic_space_pointer(lispobj *pointer)
3898 {
3899     lispobj *start_addr;
3900
3901     /* Find the object start address. */
3902     if ((start_addr = search_dynamic_space(pointer)) == NULL) {
3903         return 0;
3904     }
3905
3906     /* We need to allow raw pointers into Code objects for return
3907      * addresses. This will also pick up pointers to functions in code
3908      * objects. */
3909     if (TypeOf(*start_addr) == type_CodeHeader) {
3910         /* XXX could do some further checks here */
3911         return 1;
3912     }
3913
3914     /* If it's not a return address then it needs to be a valid Lisp
3915      * pointer. */
3916     if (!is_lisp_pointer((lispobj)pointer)) {
3917         return 0;
3918     }
3919
3920     /* Check that the object pointed to is consistent with the pointer
3921      * low tag.
3922      *
3923      * FIXME: It's not safe to rely on the result from this check
3924      * before an object is initialized. Thus, if we were interrupted
3925      * just as an object had been allocated but not initialized, the
3926      * GC relying on this result could bogusly reclaim the memory.
3927      * However, we can't really afford to do without this check. So
3928      * we should make it safe somehow. 
3929      *   (1) Perhaps just review the code to make sure
3930      *       that WITHOUT-GCING or WITHOUT-INTERRUPTS or some such
3931      *       thing is wrapped around critical sections where allocated
3932      *       memory type bits haven't been set.
3933      *   (2) Perhaps find some other hack to protect against this, e.g.
3934      *       recording the result of the last call to allocate-lisp-memory,
3935      *       and returning true from this function when *pointer is
3936      *       a reference to that result. */
3937     switch (lowtagof((lispobj)pointer)) {
3938     case FUN_POINTER_LOWTAG:
3939         /* Start_addr should be the enclosing code object, or a closure
3940          * header. */
3941         switch (TypeOf(*start_addr)) {
3942         case type_CodeHeader:
3943             /* This case is probably caught above. */
3944             break;
3945         case type_ClosureHeader:
3946         case type_FuncallableInstanceHeader:
3947             if ((unsigned)pointer !=
3948                 ((unsigned)start_addr+FUN_POINTER_LOWTAG)) {
3949                 if (gencgc_verbose)
3950                     FSHOW((stderr,
3951                            "/Wf2: %x %x %x\n",
3952                            pointer, start_addr, *start_addr));
3953                 return 0;
3954             }
3955             break;
3956         default:
3957             if (gencgc_verbose)
3958                 FSHOW((stderr,
3959                        "/Wf3: %x %x %x\n",
3960                        pointer, start_addr, *start_addr));
3961             return 0;
3962         }
3963         break;
3964     case LIST_POINTER_LOWTAG:
3965         if ((unsigned)pointer !=
3966             ((unsigned)start_addr+LIST_POINTER_LOWTAG)) {
3967             if (gencgc_verbose)
3968                 FSHOW((stderr,
3969                        "/Wl1: %x %x %x\n",
3970                        pointer, start_addr, *start_addr));
3971             return 0;
3972         }
3973         /* Is it plausible cons? */
3974         if ((is_lisp_pointer(start_addr[0])
3975             || ((start_addr[0] & 3) == 0) /* fixnum */
3976             || (TypeOf(start_addr[0]) == type_BaseChar)
3977             || (TypeOf(start_addr[0]) == type_UnboundMarker))
3978            && (is_lisp_pointer(start_addr[1])
3979                || ((start_addr[1] & 3) == 0) /* fixnum */
3980                || (TypeOf(start_addr[1]) == type_BaseChar)
3981                || (TypeOf(start_addr[1]) == type_UnboundMarker)))
3982             break;
3983         else {
3984             if (gencgc_verbose)
3985                 FSHOW((stderr,
3986                        "/Wl2: %x %x %x\n",
3987                        pointer, start_addr, *start_addr));
3988             return 0;
3989         }
3990     case INSTANCE_POINTER_LOWTAG:
3991         if ((unsigned)pointer !=
3992             ((unsigned)start_addr+INSTANCE_POINTER_LOWTAG)) {
3993             if (gencgc_verbose)
3994                 FSHOW((stderr,
3995                        "/Wi1: %x %x %x\n",
3996                        pointer, start_addr, *start_addr));
3997             return 0;
3998         }
3999         if (TypeOf(start_addr[0]) != type_InstanceHeader) {
4000             if (gencgc_verbose)
4001                 FSHOW((stderr,
4002                        "/Wi2: %x %x %x\n",
4003                        pointer, start_addr, *start_addr));
4004             return 0;
4005         }
4006         break;
4007     case OTHER_POINTER_LOWTAG:
4008         if ((unsigned)pointer !=
4009             ((int)start_addr+OTHER_POINTER_LOWTAG)) {
4010             if (gencgc_verbose)
4011                 FSHOW((stderr,
4012                        "/Wo1: %x %x %x\n",
4013                        pointer, start_addr, *start_addr));
4014             return 0;
4015         }
4016         /* Is it plausible?  Not a cons. XXX should check the headers. */
4017         if (is_lisp_pointer(start_addr[0]) || ((start_addr[0] & 3) == 0)) {
4018             if (gencgc_verbose)
4019                 FSHOW((stderr,
4020                        "/Wo2: %x %x %x\n",
4021                        pointer, start_addr, *start_addr));
4022             return 0;
4023         }
4024         switch (TypeOf(start_addr[0])) {
4025         case type_UnboundMarker:
4026         case type_BaseChar:
4027             if (gencgc_verbose)
4028                 FSHOW((stderr,
4029                        "*Wo3: %x %x %x\n",
4030                        pointer, start_addr, *start_addr));
4031             return 0;
4032
4033             /* only pointed to by function pointers? */
4034         case type_ClosureHeader:
4035         case type_FuncallableInstanceHeader:
4036             if (gencgc_verbose)
4037                 FSHOW((stderr,
4038                        "*Wo4: %x %x %x\n",
4039                        pointer, start_addr, *start_addr));
4040             return 0;
4041
4042         case type_InstanceHeader:
4043             if (gencgc_verbose)
4044                 FSHOW((stderr,
4045                        "*Wo5: %x %x %x\n",
4046                        pointer, start_addr, *start_addr));
4047             return 0;
4048
4049             /* the valid other immediate pointer objects */
4050         case type_SimpleVector:
4051         case type_Ratio:
4052         case type_Complex:
4053 #ifdef type_ComplexSingleFloat
4054         case type_ComplexSingleFloat:
4055 #endif
4056 #ifdef type_ComplexDoubleFloat
4057         case type_ComplexDoubleFloat:
4058 #endif
4059 #ifdef type_ComplexLongFloat
4060         case type_ComplexLongFloat:
4061 #endif
4062         case type_SimpleArray:
4063         case type_ComplexString:
4064         case type_ComplexBitVector:
4065         case type_ComplexVector:
4066         case type_ComplexArray:
4067         case type_ValueCellHeader:
4068         case type_SymbolHeader:
4069         case type_Fdefn:
4070         case type_CodeHeader:
4071         case type_Bignum:
4072         case type_SingleFloat:
4073         case type_DoubleFloat:
4074 #ifdef type_LongFloat
4075         case type_LongFloat:
4076 #endif
4077         case type_SimpleString:
4078         case type_SimpleBitVector:
4079         case type_SimpleArrayUnsignedByte2:
4080         case type_SimpleArrayUnsignedByte4:
4081         case type_SimpleArrayUnsignedByte8:
4082         case type_SimpleArrayUnsignedByte16:
4083         case type_SimpleArrayUnsignedByte32:
4084 #ifdef type_SimpleArraySignedByte8
4085         case type_SimpleArraySignedByte8:
4086 #endif
4087 #ifdef type_SimpleArraySignedByte16
4088         case type_SimpleArraySignedByte16:
4089 #endif
4090 #ifdef type_SimpleArraySignedByte30
4091         case type_SimpleArraySignedByte30:
4092 #endif
4093 #ifdef type_SimpleArraySignedByte32
4094         case type_SimpleArraySignedByte32:
4095 #endif
4096         case type_SimpleArraySingleFloat:
4097         case type_SimpleArrayDoubleFloat:
4098 #ifdef type_SimpleArrayLongFloat
4099         case type_SimpleArrayLongFloat:
4100 #endif
4101 #ifdef type_SimpleArrayComplexSingleFloat
4102         case type_SimpleArrayComplexSingleFloat:
4103 #endif
4104 #ifdef type_SimpleArrayComplexDoubleFloat
4105         case type_SimpleArrayComplexDoubleFloat:
4106 #endif
4107 #ifdef type_SimpleArrayComplexLongFloat
4108         case type_SimpleArrayComplexLongFloat:
4109 #endif
4110         case type_Sap:
4111         case type_WeakPointer:
4112             break;
4113
4114         default:
4115             if (gencgc_verbose)
4116                 FSHOW((stderr,
4117                        "/Wo6: %x %x %x\n",
4118                        pointer, start_addr, *start_addr));
4119             return 0;
4120         }
4121         break;
4122     default:
4123         if (gencgc_verbose)
4124             FSHOW((stderr,
4125                    "*W?: %x %x %x\n",
4126                    pointer, start_addr, *start_addr));
4127         return 0;
4128     }
4129
4130     /* looks good */
4131     return 1;
4132 }
4133
4134 /* Adjust large bignum and vector objects. This will adjust the
4135  * allocated region if the size has shrunk, and move unboxed objects
4136  * into unboxed pages. The pages are not promoted here, and the
4137  * promoted region is not added to the new_regions; this is really
4138  * only designed to be called from preserve_pointer(). Shouldn't fail
4139  * if this is missed, just may delay the moving of objects to unboxed
4140  * pages, and the freeing of pages. */
4141 static void
4142 maybe_adjust_large_object(lispobj *where)
4143 {
4144     int first_page;
4145     int nwords;
4146
4147     int remaining_bytes;
4148     int next_page;
4149     int bytes_freed;
4150     int old_bytes_used;
4151
4152     int boxed;
4153
4154     /* Check whether it's a vector or bignum object. */
4155     switch (TypeOf(where[0])) {
4156     case type_SimpleVector:
4157         boxed = BOXED_PAGE;
4158         break;
4159     case type_Bignum:
4160     case type_SimpleString:
4161     case type_SimpleBitVector:
4162     case type_SimpleArrayUnsignedByte2:
4163     case type_SimpleArrayUnsignedByte4:
4164     case type_SimpleArrayUnsignedByte8:
4165     case type_SimpleArrayUnsignedByte16:
4166     case type_SimpleArrayUnsignedByte32:
4167 #ifdef type_SimpleArraySignedByte8
4168     case type_SimpleArraySignedByte8:
4169 #endif
4170 #ifdef type_SimpleArraySignedByte16
4171     case type_SimpleArraySignedByte16:
4172 #endif
4173 #ifdef type_SimpleArraySignedByte30
4174     case type_SimpleArraySignedByte30:
4175 #endif
4176 #ifdef type_SimpleArraySignedByte32
4177     case type_SimpleArraySignedByte32:
4178 #endif
4179     case type_SimpleArraySingleFloat:
4180     case type_SimpleArrayDoubleFloat:
4181 #ifdef type_SimpleArrayLongFloat
4182     case type_SimpleArrayLongFloat:
4183 #endif
4184 #ifdef type_SimpleArrayComplexSingleFloat
4185     case type_SimpleArrayComplexSingleFloat:
4186 #endif
4187 #ifdef type_SimpleArrayComplexDoubleFloat
4188     case type_SimpleArrayComplexDoubleFloat:
4189 #endif
4190 #ifdef type_SimpleArrayComplexLongFloat
4191     case type_SimpleArrayComplexLongFloat:
4192 #endif
4193         boxed = UNBOXED_PAGE;
4194         break;
4195     default:
4196         return;
4197     }
4198
4199     /* Find its current size. */
4200     nwords = (sizetab[TypeOf(where[0])])(where);
4201
4202     first_page = find_page_index((void *)where);
4203     gc_assert(first_page >= 0);
4204
4205     /* Note: Any page write-protection must be removed, else a later
4206      * scavenge_newspace may incorrectly not scavenge these pages.
4207      * This would not be necessary if they are added to the new areas,
4208      * but lets do it for them all (they'll probably be written
4209      * anyway?). */
4210
4211     gc_assert(page_table[first_page].first_object_offset == 0);
4212
4213     next_page = first_page;
4214     remaining_bytes = nwords*4;
4215     while (remaining_bytes > 4096) {
4216         gc_assert(page_table[next_page].gen == from_space);
4217         gc_assert((page_table[next_page].allocated == BOXED_PAGE)
4218                   || (page_table[next_page].allocated == UNBOXED_PAGE));
4219         gc_assert(page_table[next_page].large_object);
4220         gc_assert(page_table[next_page].first_object_offset ==
4221                   -4096*(next_page-first_page));
4222         gc_assert(page_table[next_page].bytes_used == 4096);
4223
4224         page_table[next_page].allocated = boxed;
4225
4226         /* Shouldn't be write-protected at this stage. Essential that the
4227          * pages aren't. */
4228         gc_assert(!page_table[next_page].write_protected);
4229         remaining_bytes -= 4096;
4230         next_page++;
4231     }
4232
4233     /* Now only one page remains, but the object may have shrunk so
4234      * there may be more unused pages which will be freed. */
4235
4236     /* Object may have shrunk but shouldn't have grown - check. */
4237     gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
4238
4239     page_table[next_page].allocated = boxed;
4240     gc_assert(page_table[next_page].allocated ==
4241               page_table[first_page].allocated);
4242
4243     /* Adjust the bytes_used. */
4244     old_bytes_used = page_table[next_page].bytes_used;
4245     page_table[next_page].bytes_used = remaining_bytes;
4246
4247     bytes_freed = old_bytes_used - remaining_bytes;
4248
4249     /* Free any remaining pages; needs care. */
4250     next_page++;
4251     while ((old_bytes_used == 4096) &&
4252            (page_table[next_page].gen == from_space) &&
4253            ((page_table[next_page].allocated == UNBOXED_PAGE)
4254             || (page_table[next_page].allocated == BOXED_PAGE)) &&
4255            page_table[next_page].large_object &&
4256            (page_table[next_page].first_object_offset ==
4257             -(next_page - first_page)*4096)) {
4258         /* It checks out OK, free the page. We don't need to both zeroing
4259          * pages as this should have been done before shrinking the
4260          * object. These pages shouldn't be write protected as they
4261          * should be zero filled. */
4262         gc_assert(page_table[next_page].write_protected == 0);
4263
4264         old_bytes_used = page_table[next_page].bytes_used;
4265         page_table[next_page].allocated = FREE_PAGE;
4266         page_table[next_page].bytes_used = 0;
4267         bytes_freed += old_bytes_used;
4268         next_page++;
4269     }
4270
4271     if ((bytes_freed > 0) && gencgc_verbose) {
4272         FSHOW((stderr,
4273                "/maybe_adjust_large_object() freed %d\n",
4274                bytes_freed));
4275     }
4276
4277     generations[from_space].bytes_allocated -= bytes_freed;
4278     bytes_allocated -= bytes_freed;
4279
4280     return;
4281 }
4282
4283 /* Take a possible pointer to a Lisp object and mark its page in the
4284  * page_table so that it will not be relocated during a GC.
4285  *
4286  * This involves locating the page it points to, then backing up to
4287  * the first page that has its first object start at offset 0, and
4288  * then marking all pages dont_move from the first until a page that
4289  * ends by being full, or having free gen.
4290  *
4291  * This ensures that objects spanning pages are not broken.
4292  *
4293  * It is assumed that all the page static flags have been cleared at
4294  * the start of a GC.
4295  *
4296  * It is also assumed that the current gc_alloc() region has been
4297  * flushed and the tables updated. */
4298 static void
4299 preserve_pointer(void *addr)
4300 {
4301     int addr_page_index = find_page_index(addr);
4302     int first_page;
4303     int i;
4304     unsigned region_allocation;
4305
4306     /* quick check 1: Address is quite likely to have been invalid. */
4307     if ((addr_page_index == -1)
4308         || (page_table[addr_page_index].allocated == FREE_PAGE)
4309         || (page_table[addr_page_index].bytes_used == 0)
4310         || (page_table[addr_page_index].gen != from_space)
4311         /* Skip if already marked dont_move. */
4312         || (page_table[addr_page_index].dont_move != 0))
4313         return;
4314
4315     /* (Now that we know that addr_page_index is in range, it's
4316      * safe to index into page_table[] with it.) */
4317     region_allocation = page_table[addr_page_index].allocated;
4318
4319     /* quick check 2: Check the offset within the page.
4320      *
4321      * FIXME: The mask should have a symbolic name, and ideally should
4322      * be derived from page size instead of hardwired to 0xfff.
4323      * (Also fix other uses of 0xfff, elsewhere.) */
4324     if (((unsigned)addr & 0xfff) > page_table[addr_page_index].bytes_used)
4325         return;
4326
4327     /* Filter out anything which can't be a pointer to a Lisp object
4328      * (or, as a special case which also requires dont_move, a return
4329      * address referring to something in a CodeObject). This is
4330      * expensive but important, since it vastly reduces the
4331      * probability that random garbage will be bogusly interpreter as
4332      * a pointer which prevents a page from moving. */
4333     if (!possibly_valid_dynamic_space_pointer(addr))
4334         return;
4335
4336     /* Work backwards to find a page with a first_object_offset of 0.
4337      * The pages should be contiguous with all bytes used in the same
4338      * gen. Assumes the first_object_offset is negative or zero. */
4339     first_page = addr_page_index;
4340     while (page_table[first_page].first_object_offset != 0) {
4341         --first_page;
4342         /* Do some checks. */
4343         gc_assert(page_table[first_page].bytes_used == 4096);
4344         gc_assert(page_table[first_page].gen == from_space);
4345         gc_assert(page_table[first_page].allocated == region_allocation);
4346     }
4347
4348     /* Adjust any large objects before promotion as they won't be
4349      * copied after promotion. */
4350     if (page_table[first_page].large_object) {
4351         maybe_adjust_large_object(page_address(first_page));
4352         /* If a large object has shrunk then addr may now point to a
4353          * free area in which case it's ignored here. Note it gets
4354          * through the valid pointer test above because the tail looks
4355          * like conses. */
4356         if ((page_table[addr_page_index].allocated == FREE_PAGE)
4357             || (page_table[addr_page_index].bytes_used == 0)
4358             /* Check the offset within the page. */
4359             || (((unsigned)addr & 0xfff)
4360                 > page_table[addr_page_index].bytes_used)) {
4361             FSHOW((stderr,
4362                    "weird? ignore ptr 0x%x to freed area of large object\n",
4363                    addr));
4364             return;
4365         }
4366         /* It may have moved to unboxed pages. */
4367         region_allocation = page_table[first_page].allocated;
4368     }
4369
4370     /* Now work forward until the end of this contiguous area is found,
4371      * marking all pages as dont_move. */
4372     for (i = first_page; ;i++) {
4373         gc_assert(page_table[i].allocated == region_allocation);
4374
4375         /* Mark the page static. */
4376         page_table[i].dont_move = 1;
4377
4378         /* Move the page to the new_space. XX I'd rather not do this
4379          * but the GC logic is not quite able to copy with the static
4380          * pages remaining in the from space. This also requires the
4381          * generation bytes_allocated counters be updated. */
4382         page_table[i].gen = new_space;
4383         generations[new_space].bytes_allocated += page_table[i].bytes_used;
4384         generations[from_space].bytes_allocated -= page_table[i].bytes_used;
4385
4386         /* It is essential that the pages are not write protected as
4387          * they may have pointers into the old-space which need
4388          * scavenging. They shouldn't be write protected at this
4389          * stage. */
4390         gc_assert(!page_table[i].write_protected);
4391
4392         /* Check whether this is the last page in this contiguous block.. */
4393         if ((page_table[i].bytes_used < 4096)
4394             /* ..or it is 4096 and is the last in the block */
4395             || (page_table[i+1].allocated == FREE_PAGE)
4396             || (page_table[i+1].bytes_used == 0) /* next page free */
4397             || (page_table[i+1].gen != from_space) /* diff. gen */
4398             || (page_table[i+1].first_object_offset == 0))
4399             break;
4400     }
4401
4402     /* Check that the page is now static. */
4403     gc_assert(page_table[addr_page_index].dont_move != 0);
4404 }
4405 \f
4406 /* If the given page is not write-protected, then scan it for pointers
4407  * to younger generations or the top temp. generation, if no
4408  * suspicious pointers are found then the page is write-protected.
4409  *
4410  * Care is taken to check for pointers to the current gc_alloc()
4411  * region if it is a younger generation or the temp. generation. This
4412  * frees the caller from doing a gc_alloc_update_page_tables(). Actually
4413  * the gc_alloc_generation does not need to be checked as this is only
4414  * called from scavenge_generation() when the gc_alloc generation is
4415  * younger, so it just checks if there is a pointer to the current
4416  * region.
4417  *
4418  * We return 1 if the page was write-protected, else 0. */
4419 static int
4420 update_page_write_prot(int page)
4421 {
4422     int gen = page_table[page].gen;
4423     int j;
4424     int wp_it = 1;
4425     void **page_addr = (void **)page_address(page);
4426     int num_words = page_table[page].bytes_used / 4;
4427
4428     /* Shouldn't be a free page. */
4429     gc_assert(page_table[page].allocated != FREE_PAGE);
4430     gc_assert(page_table[page].bytes_used != 0);
4431
4432     /* Skip if it's already write-protected or an unboxed page. */
4433     if (page_table[page].write_protected
4434         || (page_table[page].allocated == UNBOXED_PAGE))
4435         return (0);
4436
4437     /* Scan the page for pointers to younger generations or the
4438      * top temp. generation. */
4439
4440     for (j = 0; j < num_words; j++) {
4441         void *ptr = *(page_addr+j);
4442         int index = find_page_index(ptr);
4443
4444         /* Check that it's in the dynamic space */
4445         if (index != -1)
4446             if (/* Does it point to a younger or the temp. generation? */
4447                 ((page_table[index].allocated != FREE_PAGE)
4448                  && (page_table[index].bytes_used != 0)
4449                  && ((page_table[index].gen < gen)
4450                      || (page_table[index].gen == NUM_GENERATIONS)))
4451
4452                 /* Or does it point within a current gc_alloc() region? */
4453                 || ((boxed_region.start_addr <= ptr)
4454                     && (ptr <= boxed_region.free_pointer))
4455                 || ((unboxed_region.start_addr <= ptr)
4456                     && (ptr <= unboxed_region.free_pointer))) {
4457                 wp_it = 0;
4458                 break;
4459             }
4460     }
4461
4462     if (wp_it == 1) {
4463         /* Write-protect the page. */
4464         /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
4465
4466         os_protect((void *)page_addr,
4467                    4096,
4468                    OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
4469
4470         /* Note the page as protected in the page tables. */
4471         page_table[page].write_protected = 1;
4472     }
4473
4474     return (wp_it);
4475 }
4476
4477 /* Scavenge a generation.
4478  *
4479  * This will not resolve all pointers when generation is the new
4480  * space, as new objects may be added which are not check here - use
4481  * scavenge_newspace generation.
4482  *
4483  * Write-protected pages should not have any pointers to the
4484  * from_space so do need scavenging; thus write-protected pages are
4485  * not always scavenged. There is some code to check that these pages
4486  * are not written; but to check fully the write-protected pages need
4487  * to be scavenged by disabling the code to skip them.
4488  *
4489  * Under the current scheme when a generation is GCed the younger
4490  * generations will be empty. So, when a generation is being GCed it
4491  * is only necessary to scavenge the older generations for pointers
4492  * not the younger. So a page that does not have pointers to younger
4493  * generations does not need to be scavenged.
4494  *
4495  * The write-protection can be used to note pages that don't have
4496  * pointers to younger pages. But pages can be written without having
4497  * pointers to younger generations. After the pages are scavenged here
4498  * they can be scanned for pointers to younger generations and if
4499  * there are none the page can be write-protected.
4500  *
4501  * One complication is when the newspace is the top temp. generation.
4502  *
4503  * Enabling SC_GEN_CK scavenges the write-protected pages and checks
4504  * that none were written, which they shouldn't be as they should have
4505  * no pointers to younger generations. This breaks down for weak
4506  * pointers as the objects contain a link to the next and are written
4507  * if a weak pointer is scavenged. Still it's a useful check. */
4508 static void
4509 scavenge_generation(int generation)
4510 {
4511     int i;
4512     int num_wp = 0;
4513
4514 #define SC_GEN_CK 0
4515 #if SC_GEN_CK
4516     /* Clear the write_protected_cleared flags on all pages. */
4517     for (i = 0; i < NUM_PAGES; i++)
4518         page_table[i].write_protected_cleared = 0;
4519 #endif
4520
4521     for (i = 0; i < last_free_page; i++) {
4522         if ((page_table[i].allocated == BOXED_PAGE)
4523             && (page_table[i].bytes_used != 0)
4524             && (page_table[i].gen == generation)) {
4525             int last_page;
4526
4527             /* This should be the start of a contiguous block. */
4528             gc_assert(page_table[i].first_object_offset == 0);
4529
4530             /* We need to find the full extent of this contiguous
4531              * block in case objects span pages. */
4532
4533             /* Now work forward until the end of this contiguous area
4534              * is found. A small area is preferred as there is a
4535              * better chance of its pages being write-protected. */
4536             for (last_page = i; ; last_page++)
4537                 /* Check whether this is the last page in this contiguous
4538                  * block. */
4539                 if ((page_table[last_page].bytes_used < 4096)
4540                     /* Or it is 4096 and is the last in the block */
4541                     || (page_table[last_page+1].allocated != BOXED_PAGE)
4542                     || (page_table[last_page+1].bytes_used == 0)
4543                     || (page_table[last_page+1].gen != generation)
4544                     || (page_table[last_page+1].first_object_offset == 0))
4545                     break;
4546
4547             /* Do a limited check for write_protected pages. If all pages
4548              * are write_protected then there is no need to scavenge. */
4549             {
4550                 int j, all_wp = 1;
4551                 for (j = i; j <= last_page; j++)
4552                     if (page_table[j].write_protected == 0) {
4553                         all_wp = 0;
4554                         break;
4555                     }
4556 #if !SC_GEN_CK
4557                 if (all_wp == 0)
4558 #endif
4559                     {
4560                         scavenge(page_address(i), (page_table[last_page].bytes_used
4561                                                    + (last_page-i)*4096)/4);
4562
4563                         /* Now scan the pages and write protect those
4564                          * that don't have pointers to younger
4565                          * generations. */
4566                         if (enable_page_protection) {
4567                             for (j = i; j <= last_page; j++) {
4568                                 num_wp += update_page_write_prot(j);
4569                             }
4570                         }
4571                     }
4572             }
4573             i = last_page;
4574         }
4575     }
4576
4577     if ((gencgc_verbose > 1) && (num_wp != 0)) {
4578         FSHOW((stderr,
4579                "/write protected %d pages within generation %d\n",
4580                num_wp, generation));
4581     }
4582
4583 #if SC_GEN_CK
4584     /* Check that none of the write_protected pages in this generation
4585      * have been written to. */
4586     for (i = 0; i < NUM_PAGES; i++) {
4587         if ((page_table[i].allocation ! =FREE_PAGE)
4588             && (page_table[i].bytes_used != 0)
4589             && (page_table[i].gen == generation)
4590             && (page_table[i].write_protected_cleared != 0)) {
4591             FSHOW((stderr, "/scavenge_generation() %d\n", generation));
4592             FSHOW((stderr,
4593                    "/page bytes_used=%d first_object_offset=%d dont_move=%d\n",
4594                     page_table[i].bytes_used,
4595                     page_table[i].first_object_offset,
4596                     page_table[i].dont_move));
4597             lose("write to protected page %d in scavenge_generation()", i);
4598         }
4599     }
4600 #endif
4601 }
4602
4603 \f
4604 /* Scavenge a newspace generation. As it is scavenged new objects may
4605  * be allocated to it; these will also need to be scavenged. This
4606  * repeats until there are no more objects unscavenged in the
4607  * newspace generation.
4608  *
4609  * To help improve the efficiency, areas written are recorded by
4610  * gc_alloc() and only these scavenged. Sometimes a little more will be
4611  * scavenged, but this causes no harm. An easy check is done that the
4612  * scavenged bytes equals the number allocated in the previous
4613  * scavenge.
4614  *
4615  * Write-protected pages are not scanned except if they are marked
4616  * dont_move in which case they may have been promoted and still have
4617  * pointers to the from space.
4618  *
4619  * Write-protected pages could potentially be written by alloc however
4620  * to avoid having to handle re-scavenging of write-protected pages
4621  * gc_alloc() does not write to write-protected pages.
4622  *
4623  * New areas of objects allocated are recorded alternatively in the two
4624  * new_areas arrays below. */
4625 static struct new_area new_areas_1[NUM_NEW_AREAS];
4626 static struct new_area new_areas_2[NUM_NEW_AREAS];
4627
4628 /* Do one full scan of the new space generation. This is not enough to
4629  * complete the job as new objects may be added to the generation in
4630  * the process which are not scavenged. */
4631 static void
4632 scavenge_newspace_generation_one_scan(int generation)
4633 {
4634     int i;
4635
4636     FSHOW((stderr,
4637            "/starting one full scan of newspace generation %d\n",
4638            generation));
4639
4640     for (i = 0; i < last_free_page; i++) {
4641         if ((page_table[i].allocated == BOXED_PAGE)
4642             && (page_table[i].bytes_used != 0)
4643             && (page_table[i].gen == generation)
4644             && ((page_table[i].write_protected == 0)
4645                 /* (This may be redundant as write_protected is now
4646                  * cleared before promotion.) */
4647                 || (page_table[i].dont_move == 1))) {
4648             int last_page;
4649
4650             /* The scavenge will start at the first_object_offset of page i.
4651              *
4652              * We need to find the full extent of this contiguous
4653              * block in case objects span pages.
4654              *
4655              * Now work forward until the end of this contiguous area
4656              * is found. A small area is preferred as there is a
4657              * better chance of its pages being write-protected. */
4658             for (last_page = i; ;last_page++) {
4659                 /* Check whether this is the last page in this
4660                  * contiguous block */
4661                 if ((page_table[last_page].bytes_used < 4096)
4662                     /* Or it is 4096 and is the last in the block */
4663                     || (page_table[last_page+1].allocated != BOXED_PAGE)
4664                     || (page_table[last_page+1].bytes_used == 0)
4665                     || (page_table[last_page+1].gen != generation)
4666                     || (page_table[last_page+1].first_object_offset == 0))
4667                     break;
4668             }
4669
4670             /* Do a limited check for write-protected pages. If all
4671              * pages are write-protected then no need to scavenge,
4672              * except if the pages are marked dont_move. */
4673             {
4674                 int j, all_wp = 1;
4675                 for (j = i; j <= last_page; j++)
4676                     if ((page_table[j].write_protected == 0)
4677                         || (page_table[j].dont_move != 0)) {
4678                         all_wp = 0;
4679                         break;
4680                     }
4681
4682                 if (!all_wp) {
4683                     int size;
4684
4685                     /* Calculate the size. */
4686                     if (last_page == i)
4687                         size = (page_table[last_page].bytes_used
4688                                 - page_table[i].first_object_offset)/4;
4689                     else
4690                         size = (page_table[last_page].bytes_used
4691                                 + (last_page-i)*4096
4692                                 - page_table[i].first_object_offset)/4;
4693                     
4694                     {
4695                         new_areas_ignore_page = last_page;
4696                         
4697                         scavenge(page_address(i) +
4698                                  page_table[i].first_object_offset,
4699                                  size);
4700
4701                     }
4702                 }
4703             }
4704
4705             i = last_page;
4706         }
4707     }
4708     FSHOW((stderr,
4709            "/done with one full scan of newspace generation %d\n",
4710            generation));
4711 }
4712
4713 /* Do a complete scavenge of the newspace generation. */
4714 static void
4715 scavenge_newspace_generation(int generation)
4716 {
4717     int i;
4718
4719     /* the new_areas array currently being written to by gc_alloc() */
4720     struct new_area (*current_new_areas)[] = &new_areas_1;
4721     int current_new_areas_index;
4722
4723     /* the new_areas created but the previous scavenge cycle */
4724     struct new_area (*previous_new_areas)[] = NULL;
4725     int previous_new_areas_index;
4726
4727     /* Flush the current regions updating the tables. */
4728     gc_alloc_update_page_tables(0, &boxed_region);
4729     gc_alloc_update_page_tables(1, &unboxed_region);
4730
4731     /* Turn on the recording of new areas by gc_alloc(). */
4732     new_areas = current_new_areas;
4733     new_areas_index = 0;
4734
4735     /* Don't need to record new areas that get scavenged anyway during
4736      * scavenge_newspace_generation_one_scan. */
4737     record_new_objects = 1;
4738
4739     /* Start with a full scavenge. */
4740     scavenge_newspace_generation_one_scan(generation);
4741
4742     /* Record all new areas now. */
4743     record_new_objects = 2;
4744
4745     /* Flush the current regions updating the tables. */
4746     gc_alloc_update_page_tables(0, &boxed_region);
4747     gc_alloc_update_page_tables(1, &unboxed_region);
4748
4749     /* Grab new_areas_index. */
4750     current_new_areas_index = new_areas_index;
4751
4752     /*FSHOW((stderr,
4753              "The first scan is finished; current_new_areas_index=%d.\n",
4754              current_new_areas_index));*/
4755
4756     while (current_new_areas_index > 0) {
4757         /* Move the current to the previous new areas */
4758         previous_new_areas = current_new_areas;
4759         previous_new_areas_index = current_new_areas_index;
4760
4761         /* Scavenge all the areas in previous new areas. Any new areas
4762          * allocated are saved in current_new_areas. */
4763
4764         /* Allocate an array for current_new_areas; alternating between
4765          * new_areas_1 and 2 */
4766         if (previous_new_areas == &new_areas_1)
4767             current_new_areas = &new_areas_2;
4768         else
4769             current_new_areas = &new_areas_1;
4770
4771         /* Set up for gc_alloc(). */
4772         new_areas = current_new_areas;
4773         new_areas_index = 0;
4774
4775         /* Check whether previous_new_areas had overflowed. */
4776         if (previous_new_areas_index >= NUM_NEW_AREAS) {
4777
4778             /* New areas of objects allocated have been lost so need to do a
4779              * full scan to be sure! If this becomes a problem try
4780              * increasing NUM_NEW_AREAS. */
4781             if (gencgc_verbose)
4782                 SHOW("new_areas overflow, doing full scavenge");
4783
4784             /* Don't need to record new areas that get scavenge anyway
4785              * during scavenge_newspace_generation_one_scan. */
4786             record_new_objects = 1;
4787
4788             scavenge_newspace_generation_one_scan(generation);
4789
4790             /* Record all new areas now. */
4791             record_new_objects = 2;
4792
4793             /* Flush the current regions updating the tables. */
4794             gc_alloc_update_page_tables(0, &boxed_region);
4795             gc_alloc_update_page_tables(1, &unboxed_region);
4796
4797         } else {
4798
4799             /* Work through previous_new_areas. */
4800             for (i = 0; i < previous_new_areas_index; i++) {
4801                 /* FIXME: All these bare *4 and /4 should be something
4802                  * like BYTES_PER_WORD or WBYTES. */
4803                 int page = (*previous_new_areas)[i].page;
4804                 int offset = (*previous_new_areas)[i].offset;
4805                 int size = (*previous_new_areas)[i].size / 4;
4806                 gc_assert((*previous_new_areas)[i].size % 4 == 0);
4807
4808                 scavenge(page_address(page)+offset, size);
4809             }
4810
4811             /* Flush the current regions updating the tables. */
4812             gc_alloc_update_page_tables(0, &boxed_region);
4813             gc_alloc_update_page_tables(1, &unboxed_region);
4814         }
4815
4816         current_new_areas_index = new_areas_index;
4817
4818         /*FSHOW((stderr,
4819                  "The re-scan has finished; current_new_areas_index=%d.\n",
4820                  current_new_areas_index));*/
4821     }
4822
4823     /* Turn off recording of areas allocated by gc_alloc(). */
4824     record_new_objects = 0;
4825
4826 #if SC_NS_GEN_CK
4827     /* Check that none of the write_protected pages in this generation
4828      * have been written to. */
4829     for (i = 0; i < NUM_PAGES; i++) {
4830         if ((page_table[i].allocation != FREE_PAGE)
4831             && (page_table[i].bytes_used != 0)
4832             && (page_table[i].gen == generation)
4833             && (page_table[i].write_protected_cleared != 0)
4834             && (page_table[i].dont_move == 0)) {
4835             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d",
4836                  i, generation, page_table[i].dont_move);
4837         }
4838     }
4839 #endif
4840 }
4841 \f
4842 /* Un-write-protect all the pages in from_space. This is done at the
4843  * start of a GC else there may be many page faults while scavenging
4844  * the newspace (I've seen drive the system time to 99%). These pages
4845  * would need to be unprotected anyway before unmapping in
4846  * free_oldspace; not sure what effect this has on paging.. */
4847 static void
4848 unprotect_oldspace(void)
4849 {
4850     int i;
4851
4852     for (i = 0; i < last_free_page; i++) {
4853         if ((page_table[i].allocated != FREE_PAGE)
4854             && (page_table[i].bytes_used != 0)
4855             && (page_table[i].gen == from_space)) {
4856             void *page_start;
4857
4858             page_start = (void *)page_address(i);
4859
4860             /* Remove any write-protection. We should be able to rely
4861              * on the write-protect flag to avoid redundant calls. */
4862             if (page_table[i].write_protected) {
4863                 os_protect(page_start, 4096, OS_VM_PROT_ALL);
4864                 page_table[i].write_protected = 0;
4865             }
4866         }
4867     }
4868 }
4869
4870 /* Work through all the pages and free any in from_space. This
4871  * assumes that all objects have been copied or promoted to an older
4872  * generation. Bytes_allocated and the generation bytes_allocated
4873  * counter are updated. The number of bytes freed is returned. */
4874 extern void i586_bzero(void *addr, int nbytes);
4875 static int
4876 free_oldspace(void)
4877 {
4878     int bytes_freed = 0;
4879     int first_page, last_page;
4880
4881     first_page = 0;
4882
4883     do {
4884         /* Find a first page for the next region of pages. */
4885         while ((first_page < last_free_page)
4886                && ((page_table[first_page].allocated == FREE_PAGE)
4887                    || (page_table[first_page].bytes_used == 0)
4888                    || (page_table[first_page].gen != from_space)))
4889             first_page++;
4890
4891         if (first_page >= last_free_page)
4892             break;
4893
4894         /* Find the last page of this region. */
4895         last_page = first_page;
4896
4897         do {
4898             /* Free the page. */
4899             bytes_freed += page_table[last_page].bytes_used;
4900             generations[page_table[last_page].gen].bytes_allocated -=
4901                 page_table[last_page].bytes_used;
4902             page_table[last_page].allocated = FREE_PAGE;
4903             page_table[last_page].bytes_used = 0;
4904
4905             /* Remove any write-protection. We should be able to rely
4906              * on the write-protect flag to avoid redundant calls. */
4907             {
4908                 void  *page_start = (void *)page_address(last_page);
4909         
4910                 if (page_table[last_page].write_protected) {
4911                     os_protect(page_start, 4096, OS_VM_PROT_ALL);
4912                     page_table[last_page].write_protected = 0;
4913                 }
4914             }
4915             last_page++;
4916         }
4917         while ((last_page < last_free_page)
4918                && (page_table[last_page].allocated != FREE_PAGE)
4919                && (page_table[last_page].bytes_used != 0)
4920                && (page_table[last_page].gen == from_space));
4921
4922         /* Zero pages from first_page to (last_page-1).
4923          *
4924          * FIXME: Why not use os_zero(..) function instead of
4925          * hand-coding this again? (Check other gencgc_unmap_zero
4926          * stuff too. */
4927         if (gencgc_unmap_zero) {
4928             void *page_start, *addr;
4929
4930             page_start = (void *)page_address(first_page);
4931
4932             os_invalidate(page_start, 4096*(last_page-first_page));
4933             addr = os_validate(page_start, 4096*(last_page-first_page));
4934             if (addr == NULL || addr != page_start) {
4935                 /* Is this an error condition? I couldn't really tell from
4936                  * the old CMU CL code, which fprintf'ed a message with
4937                  * an exclamation point at the end. But I've never seen the
4938                  * message, so it must at least be unusual..
4939                  *
4940                  * (The same condition is also tested for in gc_free_heap.)
4941                  *
4942                  * -- WHN 19991129 */
4943                 lose("i586_bzero: page moved, 0x%08x ==> 0x%08x",
4944                      page_start,
4945                      addr);
4946             }
4947         } else {
4948             int *page_start;
4949
4950             page_start = (int *)page_address(first_page);
4951             i586_bzero(page_start, 4096*(last_page-first_page));
4952         }
4953
4954         first_page = last_page;
4955
4956     } while (first_page < last_free_page);
4957
4958     bytes_allocated -= bytes_freed;
4959     return bytes_freed;
4960 }
4961 \f
4962 #if 0
4963 /* Print some information about a pointer at the given address. */
4964 static void
4965 print_ptr(lispobj *addr)
4966 {
4967     /* If addr is in the dynamic space then out the page information. */
4968     int pi1 = find_page_index((void*)addr);
4969
4970     if (pi1 != -1)
4971         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %d  dont_move %d\n",
4972                 (unsigned int) addr,
4973                 pi1,
4974                 page_table[pi1].allocated,
4975                 page_table[pi1].gen,
4976                 page_table[pi1].bytes_used,
4977                 page_table[pi1].first_object_offset,
4978                 page_table[pi1].dont_move);
4979     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
4980             *(addr-4),
4981             *(addr-3),
4982             *(addr-2),
4983             *(addr-1),
4984             *(addr-0),
4985             *(addr+1),
4986             *(addr+2),
4987             *(addr+3),
4988             *(addr+4));
4989 }
4990 #endif
4991
4992 extern int undefined_tramp;
4993
4994 static void
4995 verify_space(lispobj *start, size_t words)
4996 {
4997     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
4998     int is_in_readonly_space =
4999         (READ_ONLY_SPACE_START <= (unsigned)start &&
5000          (unsigned)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER));
5001
5002     while (words > 0) {
5003         size_t count = 1;
5004         lispobj thing = *(lispobj*)start;
5005
5006         if (is_lisp_pointer(thing)) {
5007             int page_index = find_page_index((void*)thing);
5008             int to_readonly_space =
5009                 (READ_ONLY_SPACE_START <= thing &&
5010                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER));
5011             int to_static_space =
5012                 (STATIC_SPACE_START <= thing &&
5013                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER));
5014
5015             /* Does it point to the dynamic space? */
5016             if (page_index != -1) {
5017                 /* If it's within the dynamic space it should point to a used
5018                  * page. XX Could check the offset too. */
5019                 if ((page_table[page_index].allocated != FREE_PAGE)
5020                     && (page_table[page_index].bytes_used == 0))
5021                     lose ("Ptr %x @ %x sees free page.", thing, start);
5022                 /* Check that it doesn't point to a forwarding pointer! */
5023                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
5024                     lose("Ptr %x @ %x sees forwarding ptr.", thing, start);
5025                 }
5026                 /* Check that its not in the RO space as it would then be a
5027                  * pointer from the RO to the dynamic space. */
5028                 if (is_in_readonly_space) {
5029                     lose("ptr to dynamic space %x from RO space %x",
5030                          thing, start);
5031                 }
5032                 /* Does it point to a plausible object? This check slows
5033                  * it down a lot (so it's commented out).
5034                  *
5035                  * FIXME: Add a variable to enable this dynamically. */
5036                 /* if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
5037                  *     lose("ptr %x to invalid object %x", thing, start); */
5038             } else {
5039                 /* Verify that it points to another valid space. */
5040                 if (!to_readonly_space && !to_static_space
5041                     && (thing != (unsigned)&undefined_tramp)) {
5042                     lose("Ptr %x @ %x sees junk.", thing, start);
5043                 }
5044             }
5045         } else {
5046             if (thing & 0x3) { /* Skip fixnums. FIXME: There should be an
5047                                 * is_fixnum for this. */
5048
5049                 switch(TypeOf(*start)) {
5050
5051                     /* boxed objects */
5052                 case type_SimpleVector:
5053                 case type_Ratio:
5054                 case type_Complex:
5055                 case type_SimpleArray:
5056                 case type_ComplexString:
5057                 case type_ComplexBitVector:
5058                 case type_ComplexVector:
5059                 case type_ComplexArray:
5060                 case type_ClosureHeader:
5061                 case type_FuncallableInstanceHeader:
5062                 case type_ValueCellHeader:
5063                 case type_SymbolHeader:
5064                 case type_BaseChar:
5065                 case type_UnboundMarker:
5066                 case type_InstanceHeader:
5067                 case type_Fdefn:
5068                     count = 1;
5069                     break;
5070
5071                 case type_CodeHeader:
5072                     {
5073                         lispobj object = *start;
5074                         struct code *code;
5075                         int nheader_words, ncode_words, nwords;
5076                         lispobj fheaderl;
5077                         struct simple_fun *fheaderp;
5078
5079                         code = (struct code *) start;
5080
5081                         /* Check that it's not in the dynamic space.
5082                          * FIXME: Isn't is supposed to be OK for code
5083                          * objects to be in the dynamic space these days? */
5084                         if (is_in_dynamic_space
5085                             /* It's ok if it's byte compiled code. The trace
5086                              * table offset will be a fixnum if it's x86
5087                              * compiled code - check.
5088                              *
5089                              * FIXME: #^#@@! lack of abstraction here..
5090                              * This line can probably go away now that
5091                              * there's no byte compiler, but I've got
5092                              * too much to worry about right now to try
5093                              * to make sure. -- WHN 2001-10-06 */
5094                             && !(code->trace_table_offset & 0x3)
5095                             /* Only when enabled */
5096                             && verify_dynamic_code_check) {
5097                             FSHOW((stderr,
5098                                    "/code object at %x in the dynamic space\n",
5099                                    start));
5100                         }
5101
5102                         ncode_words = fixnum_value(code->code_size);
5103                         nheader_words = HeaderValue(object);
5104                         nwords = ncode_words + nheader_words;
5105                         nwords = CEILING(nwords, 2);
5106                         /* Scavenge the boxed section of the code data block */
5107                         verify_space(start + 1, nheader_words - 1);
5108
5109                         /* Scavenge the boxed section of each function object in
5110                          * the code data block. */
5111                         fheaderl = code->entry_points;
5112                         while (fheaderl != NIL) {
5113                             fheaderp =
5114                                 (struct simple_fun *) native_pointer(fheaderl);
5115                             gc_assert(TypeOf(fheaderp->header) == type_SimpleFunHeader);
5116                             verify_space(&fheaderp->name, 1);
5117                             verify_space(&fheaderp->arglist, 1);
5118                             verify_space(&fheaderp->type, 1);
5119                             fheaderl = fheaderp->next;
5120                         }
5121                         count = nwords;
5122                         break;
5123                     }
5124         
5125                     /* unboxed objects */
5126                 case type_Bignum:
5127                 case type_SingleFloat:
5128                 case type_DoubleFloat:
5129 #ifdef type_ComplexLongFloat
5130                 case type_LongFloat:
5131 #endif
5132 #ifdef type_ComplexSingleFloat
5133                 case type_ComplexSingleFloat:
5134 #endif
5135 #ifdef type_ComplexDoubleFloat
5136                 case type_ComplexDoubleFloat:
5137 #endif
5138 #ifdef type_ComplexLongFloat
5139                 case type_ComplexLongFloat:
5140 #endif
5141                 case type_SimpleString:
5142                 case type_SimpleBitVector:
5143                 case type_SimpleArrayUnsignedByte2:
5144                 case type_SimpleArrayUnsignedByte4:
5145                 case type_SimpleArrayUnsignedByte8:
5146                 case type_SimpleArrayUnsignedByte16:
5147                 case type_SimpleArrayUnsignedByte32:
5148 #ifdef type_SimpleArraySignedByte8
5149                 case type_SimpleArraySignedByte8:
5150 #endif
5151 #ifdef type_SimpleArraySignedByte16
5152                 case type_SimpleArraySignedByte16:
5153 #endif
5154 #ifdef type_SimpleArraySignedByte30
5155                 case type_SimpleArraySignedByte30:
5156 #endif
5157 #ifdef type_SimpleArraySignedByte32
5158                 case type_SimpleArraySignedByte32:
5159 #endif
5160                 case type_SimpleArraySingleFloat:
5161                 case type_SimpleArrayDoubleFloat:
5162 #ifdef type_SimpleArrayComplexLongFloat
5163                 case type_SimpleArrayLongFloat:
5164 #endif
5165 #ifdef type_SimpleArrayComplexSingleFloat
5166                 case type_SimpleArrayComplexSingleFloat:
5167 #endif
5168 #ifdef type_SimpleArrayComplexDoubleFloat
5169                 case type_SimpleArrayComplexDoubleFloat:
5170 #endif
5171 #ifdef type_SimpleArrayComplexLongFloat
5172                 case type_SimpleArrayComplexLongFloat:
5173 #endif
5174                 case type_Sap:
5175                 case type_WeakPointer:
5176                     count = (sizetab[TypeOf(*start)])(start);
5177                     break;
5178
5179                 default:
5180                     gc_abort();
5181                 }
5182             }
5183         }
5184         start += count;
5185         words -= count;
5186     }
5187 }
5188
5189 static void
5190 verify_gc(void)
5191 {
5192     /* FIXME: It would be nice to make names consistent so that
5193      * foo_size meant size *in* *bytes* instead of size in some
5194      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
5195      * Some counts of lispobjs are called foo_count; it might be good
5196      * to grep for all foo_size and rename the appropriate ones to
5197      * foo_count. */
5198     int read_only_space_size =
5199         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER)
5200         - (lispobj*)READ_ONLY_SPACE_START;
5201     int static_space_size =
5202         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER)
5203         - (lispobj*)STATIC_SPACE_START;
5204     int binding_stack_size =
5205         (lispobj*)SymbolValue(BINDING_STACK_POINTER)
5206         - (lispobj*)BINDING_STACK_START;
5207
5208     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
5209     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
5210     verify_space((lispobj*)BINDING_STACK_START  , binding_stack_size);
5211 }
5212
5213 static void
5214 verify_generation(int  generation)
5215 {
5216     int i;
5217
5218     for (i = 0; i < last_free_page; i++) {
5219         if ((page_table[i].allocated != FREE_PAGE)
5220             && (page_table[i].bytes_used != 0)
5221             && (page_table[i].gen == generation)) {
5222             int last_page;
5223             int region_allocation = page_table[i].allocated;
5224
5225             /* This should be the start of a contiguous block */
5226             gc_assert(page_table[i].first_object_offset == 0);
5227
5228             /* Need to find the full extent of this contiguous block in case
5229                objects span pages. */
5230
5231             /* Now work forward until the end of this contiguous area is
5232                found. */
5233             for (last_page = i; ;last_page++)
5234                 /* Check whether this is the last page in this contiguous
5235                  * block. */
5236                 if ((page_table[last_page].bytes_used < 4096)
5237                     /* Or it is 4096 and is the last in the block */
5238                     || (page_table[last_page+1].allocated != region_allocation)
5239                     || (page_table[last_page+1].bytes_used == 0)
5240                     || (page_table[last_page+1].gen != generation)
5241                     || (page_table[last_page+1].first_object_offset == 0))
5242                     break;
5243
5244             verify_space(page_address(i), (page_table[last_page].bytes_used
5245                                            + (last_page-i)*4096)/4);
5246             i = last_page;
5247         }
5248     }
5249 }
5250
5251 /* Check that all the free space is zero filled. */
5252 static void
5253 verify_zero_fill(void)
5254 {
5255     int page;
5256
5257     for (page = 0; page < last_free_page; page++) {
5258         if (page_table[page].allocated == FREE_PAGE) {
5259             /* The whole page should be zero filled. */
5260             int *start_addr = (int *)page_address(page);
5261             int size = 1024;
5262             int i;
5263             for (i = 0; i < size; i++) {
5264                 if (start_addr[i] != 0) {
5265                     lose("free page not zero at %x", start_addr + i);
5266                 }
5267             }
5268         } else {
5269             int free_bytes = 4096 - page_table[page].bytes_used;
5270             if (free_bytes > 0) {
5271                 int *start_addr = (int *)((unsigned)page_address(page)
5272                                           + page_table[page].bytes_used);
5273                 int size = free_bytes / 4;
5274                 int i;
5275                 for (i = 0; i < size; i++) {
5276                     if (start_addr[i] != 0) {
5277                         lose("free region not zero at %x", start_addr + i);
5278                     }
5279                 }
5280             }
5281         }
5282     }
5283 }
5284
5285 /* External entry point for verify_zero_fill */
5286 void
5287 gencgc_verify_zero_fill(void)
5288 {
5289     /* Flush the alloc regions updating the tables. */
5290     boxed_region.free_pointer = current_region_free_pointer;
5291     gc_alloc_update_page_tables(0, &boxed_region);
5292     gc_alloc_update_page_tables(1, &unboxed_region);
5293     SHOW("verifying zero fill");
5294     verify_zero_fill();
5295     current_region_free_pointer = boxed_region.free_pointer;
5296     current_region_end_addr = boxed_region.end_addr;
5297 }
5298
5299 static void
5300 verify_dynamic_space(void)
5301 {
5302     int i;
5303
5304     for (i = 0; i < NUM_GENERATIONS; i++)
5305         verify_generation(i);
5306
5307     if (gencgc_enable_verify_zero_fill)
5308         verify_zero_fill();
5309 }
5310 \f
5311 /* Write-protect all the dynamic boxed pages in the given generation. */
5312 static void
5313 write_protect_generation_pages(int generation)
5314 {
5315     int i;
5316
5317     gc_assert(generation < NUM_GENERATIONS);
5318
5319     for (i = 0; i < last_free_page; i++)
5320         if ((page_table[i].allocated == BOXED_PAGE)
5321             && (page_table[i].bytes_used != 0)
5322             && (page_table[i].gen == generation))  {
5323             void *page_start;
5324
5325             page_start = (void *)page_address(i);
5326
5327             os_protect(page_start,
5328                        4096,
5329                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
5330
5331             /* Note the page as protected in the page tables. */
5332             page_table[i].write_protected = 1;
5333         }
5334
5335     if (gencgc_verbose > 1) {
5336         FSHOW((stderr,
5337                "/write protected %d of %d pages in generation %d\n",
5338                count_write_protect_generation_pages(generation),
5339                count_generation_pages(generation),
5340                generation));
5341     }
5342 }
5343
5344 /* Garbage collect a generation. If raise is 0 then the remains of the
5345  * generation are not raised to the next generation. */
5346 static void
5347 garbage_collect_generation(int generation, int raise)
5348 {
5349     unsigned long bytes_freed;
5350     unsigned long i;
5351     unsigned long static_space_size;
5352
5353     gc_assert(generation <= (NUM_GENERATIONS-1));
5354
5355     /* The oldest generation can't be raised. */
5356     gc_assert((generation != (NUM_GENERATIONS-1)) || (raise == 0));
5357
5358     /* Initialize the weak pointer list. */
5359     weak_pointers = NULL;
5360
5361     /* When a generation is not being raised it is transported to a
5362      * temporary generation (NUM_GENERATIONS), and lowered when
5363      * done. Set up this new generation. There should be no pages
5364      * allocated to it yet. */
5365     if (!raise)
5366         gc_assert(generations[NUM_GENERATIONS].bytes_allocated == 0);
5367
5368     /* Set the global src and dest. generations */
5369     from_space = generation;
5370     if (raise)
5371         new_space = generation+1;
5372     else
5373         new_space = NUM_GENERATIONS;
5374
5375     /* Change to a new space for allocation, resetting the alloc_start_page */
5376     gc_alloc_generation = new_space;
5377     generations[new_space].alloc_start_page = 0;
5378     generations[new_space].alloc_unboxed_start_page = 0;
5379     generations[new_space].alloc_large_start_page = 0;
5380     generations[new_space].alloc_large_unboxed_start_page = 0;
5381
5382     /* Before any pointers are preserved, the dont_move flags on the
5383      * pages need to be cleared. */
5384     for (i = 0; i < last_free_page; i++)
5385         page_table[i].dont_move = 0;
5386
5387     /* Un-write-protect the old-space pages. This is essential for the
5388      * promoted pages as they may contain pointers into the old-space
5389      * which need to be scavenged. It also helps avoid unnecessary page
5390      * faults as forwarding pointers are written into them. They need to
5391      * be un-protected anyway before unmapping later. */
5392     unprotect_oldspace();
5393
5394     /* Scavenge the stack's conservative roots. */
5395     {
5396         void **ptr;
5397         for (ptr = (void **)CONTROL_STACK_END - 1;
5398              ptr > (void **)&raise;
5399              ptr--) {
5400             preserve_pointer(*ptr);
5401         }
5402     }
5403
5404 #if QSHOW
5405     if (gencgc_verbose > 1) {
5406         int num_dont_move_pages = count_dont_move_pages();
5407         fprintf(stderr,
5408                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
5409                 num_dont_move_pages,
5410                 /* FIXME: 4096 should be symbolic constant here and
5411                  * prob'ly elsewhere too. */
5412                 num_dont_move_pages * 4096);
5413     }
5414 #endif
5415
5416     /* Scavenge all the rest of the roots. */
5417
5418     /* Scavenge the Lisp functions of the interrupt handlers, taking
5419      * care to avoid SIG_DFL and SIG_IGN. */
5420     for (i = 0; i < NSIG; i++) {
5421         union interrupt_handler handler = interrupt_handlers[i];
5422         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
5423             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
5424             scavenge((lispobj *)(interrupt_handlers + i), 1);
5425         }
5426     }
5427
5428     /* Scavenge the binding stack. */
5429     scavenge((lispobj *) BINDING_STACK_START,
5430              (lispobj *)SymbolValue(BINDING_STACK_POINTER) -
5431              (lispobj *)BINDING_STACK_START);
5432
5433     /* The original CMU CL code had scavenge-read-only-space code
5434      * controlled by the Lisp-level variable
5435      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
5436      * wasn't documented under what circumstances it was useful or
5437      * safe to turn it on, so it's been turned off in SBCL. If you
5438      * want/need this functionality, and can test and document it,
5439      * please submit a patch. */
5440 #if 0
5441     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
5442         unsigned long read_only_space_size =
5443             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
5444             (lispobj*)READ_ONLY_SPACE_START;
5445         FSHOW((stderr,
5446                "/scavenge read only space: %d bytes\n",
5447                read_only_space_size * sizeof(lispobj)));
5448         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
5449     }
5450 #endif
5451
5452     /* Scavenge static space. */
5453     static_space_size =
5454         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER) -
5455         (lispobj *)STATIC_SPACE_START;
5456     if (gencgc_verbose > 1) {
5457         FSHOW((stderr,
5458                "/scavenge static space: %d bytes\n",
5459                static_space_size * sizeof(lispobj)));
5460     }
5461     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
5462
5463     /* All generations but the generation being GCed need to be
5464      * scavenged. The new_space generation needs special handling as
5465      * objects may be moved in - it is handled separately below. */
5466     for (i = 0; i < NUM_GENERATIONS; i++) {
5467         if ((i != generation) && (i != new_space)) {
5468             scavenge_generation(i);
5469         }
5470     }
5471
5472     /* Finally scavenge the new_space generation. Keep going until no
5473      * more objects are moved into the new generation */
5474     scavenge_newspace_generation(new_space);
5475
5476     /* FIXME: I tried reenabling this check when debugging unrelated
5477      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
5478      * Since the current GC code seems to work well, I'm guessing that
5479      * this debugging code is just stale, but I haven't tried to
5480      * figure it out. It should be figured out and then either made to
5481      * work or just deleted. */
5482 #define RESCAN_CHECK 0
5483 #if RESCAN_CHECK
5484     /* As a check re-scavenge the newspace once; no new objects should
5485      * be found. */
5486     {
5487         int old_bytes_allocated = bytes_allocated;
5488         int bytes_allocated;
5489
5490         /* Start with a full scavenge. */
5491         scavenge_newspace_generation_one_scan(new_space);
5492
5493         /* Flush the current regions, updating the tables. */
5494         gc_alloc_update_page_tables(0, &boxed_region);
5495         gc_alloc_update_page_tables(1, &unboxed_region);
5496
5497         bytes_allocated = bytes_allocated - old_bytes_allocated;
5498
5499         if (bytes_allocated != 0) {
5500             lose("Rescan of new_space allocated %d more bytes.",
5501                  bytes_allocated);
5502         }
5503     }
5504 #endif
5505
5506     scan_weak_pointers();
5507
5508     /* Flush the current regions, updating the tables. */
5509     gc_alloc_update_page_tables(0, &boxed_region);
5510     gc_alloc_update_page_tables(1, &unboxed_region);
5511
5512     /* Free the pages in oldspace, but not those marked dont_move. */
5513     bytes_freed = free_oldspace();
5514
5515     /* If the GC is not raising the age then lower the generation back
5516      * to its normal generation number */
5517     if (!raise) {
5518         for (i = 0; i < last_free_page; i++)
5519             if ((page_table[i].bytes_used != 0)
5520                 && (page_table[i].gen == NUM_GENERATIONS))
5521                 page_table[i].gen = generation;
5522         gc_assert(generations[generation].bytes_allocated == 0);
5523         generations[generation].bytes_allocated =
5524             generations[NUM_GENERATIONS].bytes_allocated;
5525         generations[NUM_GENERATIONS].bytes_allocated = 0;
5526     }
5527
5528     /* Reset the alloc_start_page for generation. */
5529     generations[generation].alloc_start_page = 0;
5530     generations[generation].alloc_unboxed_start_page = 0;
5531     generations[generation].alloc_large_start_page = 0;
5532     generations[generation].alloc_large_unboxed_start_page = 0;
5533
5534     if (generation >= verify_gens) {
5535         if (gencgc_verbose)
5536             SHOW("verifying");
5537         verify_gc();
5538         verify_dynamic_space();
5539     }
5540
5541     /* Set the new gc trigger for the GCed generation. */
5542     generations[generation].gc_trigger =
5543         generations[generation].bytes_allocated
5544         + generations[generation].bytes_consed_between_gc;
5545
5546     if (raise)
5547         generations[generation].num_gc = 0;
5548     else
5549         ++generations[generation].num_gc;
5550 }
5551
5552 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
5553 int
5554 update_x86_dynamic_space_free_pointer(void)
5555 {
5556     int last_page = -1;
5557     int i;
5558
5559     for (i = 0; i < NUM_PAGES; i++)
5560         if ((page_table[i].allocated != FREE_PAGE)
5561             && (page_table[i].bytes_used != 0))
5562             last_page = i;
5563
5564     last_free_page = last_page+1;
5565
5566     SetSymbolValue(ALLOCATION_POINTER,
5567                    (lispobj)(((char *)heap_base) + last_free_page*4096));
5568     return 0; /* dummy value: return something ... */
5569 }
5570
5571 /* GC all generations below last_gen, raising their objects to the
5572  * next generation until all generations below last_gen are empty.
5573  * Then if last_gen is due for a GC then GC it. In the special case
5574  * that last_gen==NUM_GENERATIONS, the last generation is always
5575  * GC'ed. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
5576  *
5577  * The oldest generation to be GCed will always be
5578  * gencgc_oldest_gen_to_gc, partly ignoring last_gen if necessary. */
5579 void
5580 collect_garbage(unsigned last_gen)
5581 {
5582     int gen = 0;
5583     int raise;
5584     int gen_to_wp;
5585     int i;
5586
5587     boxed_region.free_pointer = current_region_free_pointer;
5588
5589     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
5590
5591     if (last_gen > NUM_GENERATIONS) {
5592         FSHOW((stderr,
5593                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
5594                last_gen));
5595         last_gen = 0;
5596     }
5597
5598     /* Flush the alloc regions updating the tables. */
5599     gc_alloc_update_page_tables(0, &boxed_region);
5600     gc_alloc_update_page_tables(1, &unboxed_region);
5601
5602     /* Verify the new objects created by Lisp code. */
5603     if (pre_verify_gen_0) {
5604         SHOW((stderr, "pre-checking generation 0\n"));
5605         verify_generation(0);
5606     }
5607
5608     if (gencgc_verbose > 1)
5609         print_generation_stats(0);
5610
5611     do {
5612         /* Collect the generation. */
5613
5614         if (gen >= gencgc_oldest_gen_to_gc) {
5615             /* Never raise the oldest generation. */
5616             raise = 0;
5617         } else {
5618             raise =
5619                 (gen < last_gen)
5620                 || (generations[gen].num_gc >= generations[gen].trigger_age);
5621         }
5622
5623         if (gencgc_verbose > 1) {
5624             FSHOW((stderr,
5625                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
5626                    gen,
5627                    raise,
5628                    generations[gen].bytes_allocated,
5629                    generations[gen].gc_trigger,
5630                    generations[gen].num_gc));
5631         }
5632
5633         /* If an older generation is being filled, then update its
5634          * memory age. */
5635         if (raise == 1) {
5636             generations[gen+1].cum_sum_bytes_allocated +=
5637                 generations[gen+1].bytes_allocated;
5638         }
5639
5640         garbage_collect_generation(gen, raise);
5641
5642         /* Reset the memory age cum_sum. */
5643         generations[gen].cum_sum_bytes_allocated = 0;
5644
5645         if (gencgc_verbose > 1) {
5646             FSHOW((stderr, "GC of generation %d finished:\n", gen));
5647             print_generation_stats(0);
5648         }
5649
5650         gen++;
5651     } while ((gen <= gencgc_oldest_gen_to_gc)
5652              && ((gen < last_gen)
5653                  || ((gen <= gencgc_oldest_gen_to_gc)
5654                      && raise
5655                      && (generations[gen].bytes_allocated
5656                          > generations[gen].gc_trigger)
5657                      && (gen_av_mem_age(gen)
5658                          > generations[gen].min_av_mem_age))));
5659
5660     /* Now if gen-1 was raised all generations before gen are empty.
5661      * If it wasn't raised then all generations before gen-1 are empty.
5662      *
5663      * Now objects within this gen's pages cannot point to younger
5664      * generations unless they are written to. This can be exploited
5665      * by write-protecting the pages of gen; then when younger
5666      * generations are GCed only the pages which have been written
5667      * need scanning. */
5668     if (raise)
5669         gen_to_wp = gen;
5670     else
5671         gen_to_wp = gen - 1;
5672
5673     /* There's not much point in WPing pages in generation 0 as it is
5674      * never scavenged (except promoted pages). */
5675     if ((gen_to_wp > 0) && enable_page_protection) {
5676         /* Check that they are all empty. */
5677         for (i = 0; i < gen_to_wp; i++) {
5678             if (generations[i].bytes_allocated)
5679                 lose("trying to write-protect gen. %d when gen. %d nonempty",
5680                      gen_to_wp, i);
5681         }
5682         write_protect_generation_pages(gen_to_wp);
5683     }
5684
5685     /* Set gc_alloc() back to generation 0. The current regions should
5686      * be flushed after the above GCs. */
5687     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
5688     gc_alloc_generation = 0;
5689
5690     update_x86_dynamic_space_free_pointer();
5691
5692     /* This is now done by Lisp SCRUB-CONTROL-STACK in Lisp SUB-GC, so
5693      * we needn't do it here: */
5694     /*  zero_stack();*/
5695
5696     current_region_free_pointer = boxed_region.free_pointer;
5697     current_region_end_addr = boxed_region.end_addr;
5698
5699     SHOW("returning from collect_garbage");
5700 }
5701
5702 /* This is called by Lisp PURIFY when it is finished. All live objects
5703  * will have been moved to the RO and Static heaps. The dynamic space
5704  * will need a full re-initialization. We don't bother having Lisp
5705  * PURIFY flush the current gc_alloc() region, as the page_tables are
5706  * re-initialized, and every page is zeroed to be sure. */
5707 void
5708 gc_free_heap(void)
5709 {
5710     int page;
5711
5712     if (gencgc_verbose > 1)
5713         SHOW("entering gc_free_heap");
5714
5715     for (page = 0; page < NUM_PAGES; page++) {
5716         /* Skip free pages which should already be zero filled. */
5717         if (page_table[page].allocated != FREE_PAGE) {
5718             void *page_start, *addr;
5719
5720             /* Mark the page free. The other slots are assumed invalid
5721              * when it is a FREE_PAGE and bytes_used is 0 and it
5722              * should not be write-protected -- except that the
5723              * generation is used for the current region but it sets
5724              * that up. */
5725             page_table[page].allocated = FREE_PAGE;
5726             page_table[page].bytes_used = 0;
5727
5728             /* Zero the page. */
5729             page_start = (void *)page_address(page);
5730
5731             /* First, remove any write-protection. */
5732             os_protect(page_start, 4096, OS_VM_PROT_ALL);
5733             page_table[page].write_protected = 0;
5734
5735             os_invalidate(page_start,4096);
5736             addr = os_validate(page_start,4096);
5737             if (addr == NULL || addr != page_start) {
5738                 lose("gc_free_heap: page moved, 0x%08x ==> 0x%08x",
5739                      page_start,
5740                      addr);
5741             }
5742         } else if (gencgc_zero_check_during_free_heap) {
5743             /* Double-check that the page is zero filled. */
5744             int *page_start, i;
5745             gc_assert(page_table[page].allocated == FREE_PAGE);
5746             gc_assert(page_table[page].bytes_used == 0);
5747             page_start = (int *)page_address(page);
5748             for (i=0; i<1024; i++) {
5749                 if (page_start[i] != 0) {
5750                     lose("free region not zero at %x", page_start + i);
5751                 }
5752             }
5753         }
5754     }
5755
5756     bytes_allocated = 0;
5757
5758     /* Initialize the generations. */
5759     for (page = 0; page < NUM_GENERATIONS; page++) {
5760         generations[page].alloc_start_page = 0;
5761         generations[page].alloc_unboxed_start_page = 0;
5762         generations[page].alloc_large_start_page = 0;
5763         generations[page].alloc_large_unboxed_start_page = 0;
5764         generations[page].bytes_allocated = 0;
5765         generations[page].gc_trigger = 2000000;
5766         generations[page].num_gc = 0;
5767         generations[page].cum_sum_bytes_allocated = 0;
5768     }
5769
5770     if (gencgc_verbose > 1)
5771         print_generation_stats(0);
5772
5773     /* Initialize gc_alloc(). */
5774     gc_alloc_generation = 0;
5775     boxed_region.first_page = 0;
5776     boxed_region.last_page = -1;
5777     boxed_region.start_addr = page_address(0);
5778     boxed_region.free_pointer = page_address(0);
5779     boxed_region.end_addr = page_address(0);
5780     unboxed_region.first_page = 0;
5781     unboxed_region.last_page = -1;
5782     unboxed_region.start_addr = page_address(0);
5783     unboxed_region.free_pointer = page_address(0);
5784     unboxed_region.end_addr = page_address(0);
5785
5786 #if 0 /* Lisp PURIFY is currently running on the C stack so don't do this. */
5787     zero_stack();
5788 #endif
5789
5790     last_free_page = 0;
5791     SetSymbolValue(ALLOCATION_POINTER, (lispobj)((char *)heap_base));
5792
5793     current_region_free_pointer = boxed_region.free_pointer;
5794     current_region_end_addr = boxed_region.end_addr;
5795
5796     if (verify_after_free_heap) {
5797         /* Check whether purify has left any bad pointers. */
5798         if (gencgc_verbose)
5799             SHOW("checking after free_heap\n");
5800         verify_gc();
5801     }
5802 }
5803 \f
5804 void
5805 gc_init(void)
5806 {
5807     int i;
5808
5809     gc_init_tables();
5810
5811     heap_base = (void*)DYNAMIC_SPACE_START;
5812
5813     /* Initialize each page structure. */
5814     for (i = 0; i < NUM_PAGES; i++) {
5815         /* Initialize all pages as free. */
5816         page_table[i].allocated = FREE_PAGE;
5817         page_table[i].bytes_used = 0;
5818
5819         /* Pages are not write-protected at startup. */
5820         page_table[i].write_protected = 0;
5821     }
5822
5823     bytes_allocated = 0;
5824
5825     /* Initialize the generations.
5826      *
5827      * FIXME: very similar to code in gc_free_heap(), should be shared */
5828     for (i = 0; i < NUM_GENERATIONS; i++) {
5829         generations[i].alloc_start_page = 0;
5830         generations[i].alloc_unboxed_start_page = 0;
5831         generations[i].alloc_large_start_page = 0;
5832         generations[i].alloc_large_unboxed_start_page = 0;
5833         generations[i].bytes_allocated = 0;
5834         generations[i].gc_trigger = 2000000;
5835         generations[i].num_gc = 0;
5836         generations[i].cum_sum_bytes_allocated = 0;
5837         /* the tune-able parameters */
5838         generations[i].bytes_consed_between_gc = 2000000;
5839         generations[i].trigger_age = 1;
5840         generations[i].min_av_mem_age = 0.75;
5841     }
5842
5843     /* Initialize gc_alloc.
5844      *
5845      * FIXME: identical with code in gc_free_heap(), should be shared */
5846     gc_alloc_generation = 0;
5847     boxed_region.first_page = 0;
5848     boxed_region.last_page = -1;
5849     boxed_region.start_addr = page_address(0);
5850     boxed_region.free_pointer = page_address(0);
5851     boxed_region.end_addr = page_address(0);
5852     unboxed_region.first_page = 0;
5853     unboxed_region.last_page = -1;
5854     unboxed_region.start_addr = page_address(0);
5855     unboxed_region.free_pointer = page_address(0);
5856     unboxed_region.end_addr = page_address(0);
5857
5858     last_free_page = 0;
5859
5860     current_region_free_pointer = boxed_region.free_pointer;
5861     current_region_end_addr = boxed_region.end_addr;
5862 }
5863
5864 /*  Pick up the dynamic space from after a core load.
5865  *
5866  *  The ALLOCATION_POINTER points to the end of the dynamic space.
5867  *
5868  *  XX A scan is needed to identify the closest first objects for pages. */
5869 void
5870 gencgc_pickup_dynamic(void)
5871 {
5872     int page = 0;
5873     int addr = DYNAMIC_SPACE_START;
5874     int alloc_ptr = SymbolValue(ALLOCATION_POINTER);
5875
5876     /* Initialize the first region. */
5877     do {
5878         page_table[page].allocated = BOXED_PAGE;
5879         page_table[page].gen = 0;
5880         page_table[page].bytes_used = 4096;
5881         page_table[page].large_object = 0;
5882         page_table[page].first_object_offset =
5883             (void *)DYNAMIC_SPACE_START - page_address(page);
5884         addr += 4096;
5885         page++;
5886     } while (addr < alloc_ptr);
5887
5888     generations[0].bytes_allocated = 4096*page;
5889     bytes_allocated = 4096*page;
5890
5891     current_region_free_pointer = boxed_region.free_pointer;
5892     current_region_end_addr = boxed_region.end_addr;
5893 }
5894 \f
5895 /* a counter for how deep we are in alloc(..) calls */
5896 int alloc_entered = 0;
5897
5898 /* alloc(..) is the external interface for memory allocation. It
5899  * allocates to generation 0. It is not called from within the garbage
5900  * collector as it is only external uses that need the check for heap
5901  * size (GC trigger) and to disable the interrupts (interrupts are
5902  * always disabled during a GC).
5903  *
5904  * The vops that call alloc(..) assume that the returned space is zero-filled.
5905  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
5906  *
5907  * The check for a GC trigger is only performed when the current
5908  * region is full, so in most cases it's not needed. Further MAYBE-GC
5909  * is only called once because Lisp will remember "need to collect
5910  * garbage" and get around to it when it can. */
5911 char *
5912 alloc(int nbytes)
5913 {
5914     /* Check for alignment allocation problems. */
5915     gc_assert((((unsigned)current_region_free_pointer & 0x7) == 0)
5916               && ((nbytes & 0x7) == 0));
5917
5918     if (SymbolValue(PSEUDO_ATOMIC_ATOMIC)) {/* if already in a pseudo atomic */
5919         
5920         void *new_free_pointer;
5921
5922     retry1:
5923         if (alloc_entered) {
5924             SHOW("alloc re-entered in already-pseudo-atomic case");
5925         }
5926         ++alloc_entered;
5927
5928         /* Check whether there is room in the current region. */
5929         new_free_pointer = current_region_free_pointer + nbytes;
5930
5931         /* FIXME: Shouldn't we be doing some sort of lock here, to
5932          * keep from getting screwed if an interrupt service routine
5933          * allocates memory between the time we calculate new_free_pointer
5934          * and the time we write it back to current_region_free_pointer?
5935          * Perhaps I just don't understand pseudo-atomics..
5936          *
5937          * Perhaps I don't. It looks as though what happens is if we
5938          * were interrupted any time during the pseudo-atomic
5939          * interval (which includes now) we discard the allocated
5940          * memory and try again. So, at least we don't return
5941          * a memory area that was allocated out from underneath us
5942          * by code in an ISR.
5943          * Still, that doesn't seem to prevent
5944          * current_region_free_pointer from getting corrupted:
5945          *   We read current_region_free_pointer.
5946          *   They read current_region_free_pointer.
5947          *   They write current_region_free_pointer.
5948          *   We write current_region_free_pointer, scribbling over
5949          *     whatever they wrote. */
5950
5951         if (new_free_pointer <= boxed_region.end_addr) {
5952             /* If so then allocate from the current region. */
5953             void  *new_obj = current_region_free_pointer;
5954             current_region_free_pointer = new_free_pointer;
5955             alloc_entered--;
5956             return((void *)new_obj);
5957         }
5958
5959         if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
5960             /* Double the trigger. */
5961             auto_gc_trigger *= 2;
5962             alloc_entered--;
5963             /* Exit the pseudo-atomic. */
5964             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
5965             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
5966                 /* Handle any interrupts that occurred during
5967                  * gc_alloc(..). */
5968                 do_pending_interrupt();
5969             }
5970             funcall0(SymbolFunction(MAYBE_GC));
5971             /* Re-enter the pseudo-atomic. */
5972             SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(0));
5973             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(1));
5974             goto retry1;
5975         }
5976         /* Call gc_alloc(). */
5977         boxed_region.free_pointer = current_region_free_pointer;
5978         {
5979             void *new_obj = gc_alloc(nbytes);
5980             current_region_free_pointer = boxed_region.free_pointer;
5981             current_region_end_addr = boxed_region.end_addr;
5982             alloc_entered--;
5983             return (new_obj);
5984         }
5985     } else {
5986         void *result;
5987         void *new_free_pointer;
5988
5989     retry2:
5990         /* At least wrap this allocation in a pseudo atomic to prevent
5991          * gc_alloc() from being re-entered. */
5992         SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(0));
5993         SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(1));
5994
5995         if (alloc_entered)
5996             SHOW("alloc re-entered in not-already-pseudo-atomic case");
5997         ++alloc_entered;
5998
5999         /* Check whether there is room in the current region. */
6000         new_free_pointer = current_region_free_pointer + nbytes;
6001
6002         if (new_free_pointer <= boxed_region.end_addr) {
6003             /* If so then allocate from the current region. */
6004             void *new_obj = current_region_free_pointer;
6005             current_region_free_pointer = new_free_pointer;
6006             alloc_entered--;
6007             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6008             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED)) {
6009                 /* Handle any interrupts that occurred during
6010                  * gc_alloc(..). */
6011                 do_pending_interrupt();
6012                 goto retry2;
6013             }
6014
6015             return((void *)new_obj);
6016         }
6017
6018         /* KLUDGE: There's lots of code around here shared with the
6019          * the other branch. Is there some way to factor out the
6020          * duplicate code? -- WHN 19991129 */
6021         if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
6022             /* Double the trigger. */
6023             auto_gc_trigger *= 2;
6024             alloc_entered--;
6025             /* Exit the pseudo atomic. */
6026             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6027             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6028                 /* Handle any interrupts that occurred during
6029                  * gc_alloc(..); */
6030                 do_pending_interrupt();
6031             }
6032             funcall0(SymbolFunction(MAYBE_GC));
6033             goto retry2;
6034         }
6035
6036         /* Else call gc_alloc(). */
6037         boxed_region.free_pointer = current_region_free_pointer;
6038         result = gc_alloc(nbytes);
6039         current_region_free_pointer = boxed_region.free_pointer;
6040         current_region_end_addr = boxed_region.end_addr;
6041
6042         alloc_entered--;
6043         SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6044         if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6045             /* Handle any interrupts that occurred during gc_alloc(..). */
6046             do_pending_interrupt();
6047             goto retry2;
6048         }
6049
6050         return result;
6051     }
6052 }
6053 \f
6054 /*
6055  * noise to manipulate the gc trigger stuff
6056  */
6057
6058 void
6059 set_auto_gc_trigger(os_vm_size_t dynamic_usage)
6060 {
6061     auto_gc_trigger += dynamic_usage;
6062 }
6063
6064 void
6065 clear_auto_gc_trigger(void)
6066 {
6067     auto_gc_trigger = 0;
6068 }
6069 \f
6070 /* Find the code object for the given pc, or return NULL on failure.
6071  *
6072  * FIXME: PC shouldn't be lispobj*, should it? Maybe void*? */
6073 lispobj *
6074 component_ptr_from_pc(lispobj *pc)
6075 {
6076     lispobj *object = NULL;
6077
6078     if ( (object = search_read_only_space(pc)) )
6079         ;
6080     else if ( (object = search_static_space(pc)) )
6081         ;
6082     else
6083         object = search_dynamic_space(pc);
6084
6085     if (object) /* if we found something */
6086         if (TypeOf(*object) == type_CodeHeader) /* if it's a code object */
6087             return(object);
6088
6089     return (NULL);
6090 }
6091 \f
6092 /*
6093  * shared support for the OS-dependent signal handlers which
6094  * catch GENCGC-related write-protect violations
6095  */
6096
6097 void unhandled_sigmemoryfault(void);
6098
6099 /* Depending on which OS we're running under, different signals might
6100  * be raised for a violation of write protection in the heap. This
6101  * function factors out the common generational GC magic which needs
6102  * to invoked in this case, and should be called from whatever signal
6103  * handler is appropriate for the OS we're running under.
6104  *
6105  * Return true if this signal is a normal generational GC thing that
6106  * we were able to handle, or false if it was abnormal and control
6107  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
6108 int
6109 gencgc_handle_wp_violation(void* fault_addr)
6110 {
6111     int  page_index = find_page_index(fault_addr);
6112
6113 #if defined QSHOW_SIGNALS
6114     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
6115            fault_addr, page_index));
6116 #endif
6117
6118     /* Check whether the fault is within the dynamic space. */
6119     if (page_index == (-1)) {
6120
6121         /* It can be helpful to be able to put a breakpoint on this
6122          * case to help diagnose low-level problems. */
6123         unhandled_sigmemoryfault();
6124
6125         /* not within the dynamic space -- not our responsibility */
6126         return 0;
6127
6128     } else {
6129
6130         /* The only acceptable reason for an signal like this from the
6131          * heap is that the generational GC write-protected the page. */
6132         if (page_table[page_index].write_protected != 1) {
6133             lose("access failure in heap page not marked as write-protected");
6134         }
6135         
6136         /* Unprotect the page. */
6137         os_protect(page_address(page_index), 4096, OS_VM_PROT_ALL);
6138         page_table[page_index].write_protected = 0;
6139         page_table[page_index].write_protected_cleared = 1;
6140
6141         /* Don't worry, we can handle it. */
6142         return 1;
6143     }
6144 }
6145
6146 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
6147  * it's not just a case of the program hitting the write barrier, and
6148  * are about to let Lisp deal with it. It's basically just a
6149  * convenient place to set a gdb breakpoint. */
6150 void
6151 unhandled_sigmemoryfault()
6152 {}