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