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