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