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