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