43ccf96d6128382218b9b558f2f45220e7c1ff4a
[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.4f\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=%ld\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 int 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     return((void *) NIL); /* dummy value: return something ... */
1200 }
1201
1202 /* Allocate space from the boxed_region. If there is not enough free
1203  * space then call gc_alloc to do the job. A pointer to the start of
1204  * the region is returned. */
1205 static inline void
1206 *gc_quick_alloc(int nbytes)
1207 {
1208     void *new_free_pointer;
1209
1210     /* Check whether there is room in the current region. */
1211     new_free_pointer = boxed_region.free_pointer + nbytes;
1212
1213     if (new_free_pointer <= boxed_region.end_addr) {
1214         /* If so then allocate from the current region. */
1215         void  *new_obj = boxed_region.free_pointer;
1216         boxed_region.free_pointer = new_free_pointer;
1217         return((void *)new_obj);
1218     }
1219
1220     /* Else call gc_alloc */
1221     return (gc_alloc(nbytes));
1222 }
1223
1224 /* Allocate space for the boxed object. If it is a large object then
1225  * do a large alloc else allocate from the current region. If there is
1226  * not enough free space then call gc_alloc to do the job. A pointer
1227  * to the start of the region is returned. */
1228 static inline void
1229 *gc_quick_alloc_large(int nbytes)
1230 {
1231     void *new_free_pointer;
1232
1233     if (nbytes >= large_object_size)
1234         return gc_alloc_large(nbytes, 0, &boxed_region);
1235
1236     /* Check whether there is room in the current region. */
1237     new_free_pointer = boxed_region.free_pointer + nbytes;
1238
1239     if (new_free_pointer <= boxed_region.end_addr) {
1240         /* If so then allocate from the current region. */
1241         void *new_obj = boxed_region.free_pointer;
1242         boxed_region.free_pointer = new_free_pointer;
1243         return((void *)new_obj);
1244     }
1245
1246     /* Else call gc_alloc */
1247     return (gc_alloc(nbytes));
1248 }
1249
1250 static void
1251 *gc_alloc_unboxed(int nbytes)
1252 {
1253     void *new_free_pointer;
1254
1255     /*
1256     FSHOW((stderr, "/gc_alloc_unboxed %d\n", nbytes));
1257     */
1258
1259     /* Check whether there is room in the current region. */
1260     new_free_pointer = unboxed_region.free_pointer + nbytes;
1261
1262     if (new_free_pointer <= unboxed_region.end_addr) {
1263         /* If so then allocate from the current region. */
1264         void *new_obj = unboxed_region.free_pointer;
1265         unboxed_region.free_pointer = new_free_pointer;
1266
1267         /* Check whether the current region is almost empty. */
1268         if ((unboxed_region.end_addr - unboxed_region.free_pointer) <= 32) {
1269             /* If so finished with the current region. */
1270             gc_alloc_update_page_tables(1, &unboxed_region);
1271
1272             /* Set up a new region. */
1273             gc_alloc_new_region(32, 1, &unboxed_region);
1274         }
1275
1276         return((void *)new_obj);
1277     }
1278
1279     /* Else not enough free space in the current region. */
1280
1281     /* If there is a bit of room left in the current region then
1282        allocate a large object. */
1283     if ((unboxed_region.end_addr-unboxed_region.free_pointer) > 32)
1284         return gc_alloc_large(nbytes,1,&unboxed_region);
1285
1286     /* Else find a new region. */
1287
1288     /* Finished with the current region. */
1289     gc_alloc_update_page_tables(1, &unboxed_region);
1290
1291     /* Set up a new region. */
1292     gc_alloc_new_region(nbytes, 1, &unboxed_region);
1293
1294     /* Should now be enough room. */
1295
1296     /* Check whether there is room in the current region. */
1297     new_free_pointer = unboxed_region.free_pointer + nbytes;
1298
1299     if (new_free_pointer <= unboxed_region.end_addr) {
1300         /* If so then allocate from the current region. */
1301         void *new_obj = unboxed_region.free_pointer;
1302         unboxed_region.free_pointer = new_free_pointer;
1303
1304         /* Check whether the current region is almost empty. */
1305         if ((unboxed_region.end_addr - unboxed_region.free_pointer) <= 32) {
1306             /* If so find, finished with the current region. */
1307             gc_alloc_update_page_tables(1, &unboxed_region);
1308
1309             /* Set up a new region. */
1310             gc_alloc_new_region(32, 1, &unboxed_region);
1311         }
1312
1313         return((void *)new_obj);
1314     }
1315
1316     /* shouldn't happen? */
1317     gc_assert(0);
1318     return((void *) NIL); /* dummy value: return something ... */
1319 }
1320
1321 static inline void
1322 *gc_quick_alloc_unboxed(int nbytes)
1323 {
1324     void *new_free_pointer;
1325
1326     /* Check whether there is room in the current region. */
1327     new_free_pointer = unboxed_region.free_pointer + nbytes;
1328
1329     if (new_free_pointer <= unboxed_region.end_addr) {
1330         /* If so then allocate from the current region. */
1331         void *new_obj = unboxed_region.free_pointer;
1332         unboxed_region.free_pointer = new_free_pointer;
1333
1334         return((void *)new_obj);
1335     }
1336
1337     /* Else call gc_alloc */
1338     return (gc_alloc_unboxed(nbytes));
1339 }
1340
1341 /* Allocate space for the object. If it is a large object then do a
1342  * large alloc else allocate from the current region. If there is not
1343  * enough free space then call gc_alloc to do the job.
1344  *
1345  * A pointer to the start of the region is returned. */
1346 static inline void
1347 *gc_quick_alloc_large_unboxed(int nbytes)
1348 {
1349     void *new_free_pointer;
1350
1351     if (nbytes >= large_object_size)
1352         return gc_alloc_large(nbytes,1,&unboxed_region);
1353
1354     /* Check whether there is room in the current region. */
1355     new_free_pointer = unboxed_region.free_pointer + nbytes;
1356
1357     if (new_free_pointer <= unboxed_region.end_addr) {
1358         /* If so then allocate from the current region. */
1359         void *new_obj = unboxed_region.free_pointer;
1360         unboxed_region.free_pointer = new_free_pointer;
1361
1362         return((void *)new_obj);
1363     }
1364
1365     /* Else call gc_alloc. */
1366     return (gc_alloc_unboxed(nbytes));
1367 }
1368 \f
1369 /*
1370  * scavenging/transporting routines derived from gc.c in CMU CL ca. 18b
1371  */
1372
1373 static int (*scavtab[256])(lispobj *where, lispobj object);
1374 static lispobj (*transother[256])(lispobj object);
1375 static int (*sizetab[256])(lispobj *where);
1376
1377 static struct weak_pointer *weak_pointers;
1378
1379 #define CEILING(x,y) (((x) + ((y) - 1)) & (~((y) - 1)))
1380 \f
1381 /*
1382  * predicates
1383  */
1384
1385 static inline boolean
1386 from_space_p(lispobj obj)
1387 {
1388     int page_index=(void*)obj - heap_base;
1389     return ((page_index >= 0)
1390             && ((page_index = ((unsigned int)page_index)/4096) < NUM_PAGES)
1391             && (page_table[page_index].gen == from_space));
1392 }
1393
1394 static inline boolean
1395 new_space_p(lispobj obj)
1396 {
1397     int page_index = (void*)obj - heap_base;
1398     return ((page_index >= 0)
1399             && ((page_index = ((unsigned int)page_index)/4096) < NUM_PAGES)
1400             && (page_table[page_index].gen == new_space));
1401 }
1402 \f
1403 /*
1404  * copying objects
1405  */
1406
1407 /* to copy a boxed object */
1408 static inline lispobj
1409 copy_object(lispobj object, int nwords)
1410 {
1411     int tag;
1412     lispobj *new;
1413     lispobj *source, *dest;
1414
1415     gc_assert(Pointerp(object));
1416     gc_assert(from_space_p(object));
1417     gc_assert((nwords & 0x01) == 0);
1418
1419     /* Get tag of object. */
1420     tag = LowtagOf(object);
1421
1422     /* Allocate space. */
1423     new = gc_quick_alloc(nwords*4);
1424
1425     dest = new;
1426     source = (lispobj *) PTR(object);
1427
1428     /* Copy the object. */
1429     while (nwords > 0) {
1430         dest[0] = source[0];
1431         dest[1] = source[1];
1432         dest += 2;
1433         source += 2;
1434         nwords -= 2;
1435     }
1436
1437     /* Return Lisp pointer of new object. */
1438     return ((lispobj) new) | tag;
1439 }
1440
1441 /* to copy a large boxed object. If the object is in a large object
1442  * region then it is simply promoted, else it is copied. If it's large
1443  * enough then it's copied to a large object region.
1444  *
1445  * Vectors may have shrunk. If the object is not copied the space
1446  * needs to be reclaimed, and the page_tables corrected. */
1447 static lispobj
1448 copy_large_object(lispobj object, int nwords)
1449 {
1450     int tag;
1451     lispobj *new;
1452     lispobj *source, *dest;
1453     int first_page;
1454
1455     gc_assert(Pointerp(object));
1456     gc_assert(from_space_p(object));
1457     gc_assert((nwords & 0x01) == 0);
1458
1459     if ((nwords > 1024*1024) && gencgc_verbose) {
1460         FSHOW((stderr, "/copy_large_object: %d bytes\n", nwords*4));
1461     }
1462
1463     /* Check whether it's a large object. */
1464     first_page = find_page_index((void *)object);
1465     gc_assert(first_page >= 0);
1466
1467     if (page_table[first_page].large_object) {
1468
1469         /* Promote the object. */
1470
1471         int remaining_bytes;
1472         int next_page;
1473         int bytes_freed;
1474         int old_bytes_used;
1475
1476         /* Note: Any page write-protection must be removed, else a
1477          * later scavenge_newspace may incorrectly not scavenge these
1478          * pages. This would not be necessary if they are added to the
1479          * new areas, but let's do it for them all (they'll probably
1480          * be written anyway?). */
1481
1482         gc_assert(page_table[first_page].first_object_offset == 0);
1483
1484         next_page = first_page;
1485         remaining_bytes = nwords*4;
1486         while (remaining_bytes > 4096) {
1487             gc_assert(page_table[next_page].gen == from_space);
1488             gc_assert(page_table[next_page].allocated == BOXED_PAGE);
1489             gc_assert(page_table[next_page].large_object);
1490             gc_assert(page_table[next_page].first_object_offset==
1491                       -4096*(next_page-first_page));
1492             gc_assert(page_table[next_page].bytes_used == 4096);
1493
1494             page_table[next_page].gen = new_space;
1495
1496             /* Remove any write-protection. We should be able to rely
1497              * on the write-protect flag to avoid redundant calls. */
1498             if (page_table[next_page].write_protected) {
1499                 os_protect(page_address(next_page), 4096, OS_VM_PROT_ALL);
1500                 page_table[next_page].write_protected = 0;
1501             }
1502             remaining_bytes -= 4096;
1503             next_page++;
1504         }
1505
1506         /* Now only one page remains, but the object may have shrunk
1507          * so there may be more unused pages which will be freed. */
1508
1509         /* The object may have shrunk but shouldn't have grown. */
1510         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1511
1512         page_table[next_page].gen = new_space;
1513         gc_assert(page_table[next_page].allocated = BOXED_PAGE);
1514
1515         /* Adjust the bytes_used. */
1516         old_bytes_used = page_table[next_page].bytes_used;
1517         page_table[next_page].bytes_used = remaining_bytes;
1518
1519         bytes_freed = old_bytes_used - remaining_bytes;
1520
1521         /* Free any remaining pages; needs care. */
1522         next_page++;
1523         while ((old_bytes_used == 4096) &&
1524                (page_table[next_page].gen == from_space) &&
1525                (page_table[next_page].allocated == BOXED_PAGE) &&
1526                page_table[next_page].large_object &&
1527                (page_table[next_page].first_object_offset ==
1528                 -(next_page - first_page)*4096)) {
1529             /* Checks out OK, free the page. Don't need to both zeroing
1530              * pages as this should have been done before shrinking the
1531              * object. These pages shouldn't be write-protected as they
1532              * should be zero filled. */
1533             gc_assert(page_table[next_page].write_protected == 0);
1534
1535             old_bytes_used = page_table[next_page].bytes_used;
1536             page_table[next_page].allocated = FREE_PAGE;
1537             page_table[next_page].bytes_used = 0;
1538             bytes_freed += old_bytes_used;
1539             next_page++;
1540         }
1541
1542         if ((bytes_freed > 0) && gencgc_verbose)
1543             FSHOW((stderr, "/copy_large_boxed bytes_freed=%d\n", bytes_freed));
1544
1545         generations[from_space].bytes_allocated -= 4*nwords + bytes_freed;
1546         generations[new_space].bytes_allocated += 4*nwords;
1547         bytes_allocated -= bytes_freed;
1548
1549         /* Add the region to the new_areas if requested. */
1550         add_new_area(first_page,0,nwords*4);
1551
1552         return(object);
1553     } else {
1554         /* Get tag of object. */
1555         tag = LowtagOf(object);
1556
1557         /* Allocate space. */
1558         new = gc_quick_alloc_large(nwords*4);
1559
1560         dest = new;
1561         source = (lispobj *) PTR(object);
1562
1563         /* Copy the object. */
1564         while (nwords > 0) {
1565             dest[0] = source[0];
1566             dest[1] = source[1];
1567             dest += 2;
1568             source += 2;
1569             nwords -= 2;
1570         }
1571
1572         /* Return Lisp pointer of new object. */
1573         return ((lispobj) new) | tag;
1574     }
1575 }
1576
1577 /* to copy unboxed objects */
1578 static inline lispobj
1579 copy_unboxed_object(lispobj object, int nwords)
1580 {
1581     int tag;
1582     lispobj *new;
1583     lispobj *source, *dest;
1584
1585     gc_assert(Pointerp(object));
1586     gc_assert(from_space_p(object));
1587     gc_assert((nwords & 0x01) == 0);
1588
1589     /* Get tag of object. */
1590     tag = LowtagOf(object);
1591
1592     /* Allocate space. */
1593     new = gc_quick_alloc_unboxed(nwords*4);
1594
1595     dest = new;
1596     source = (lispobj *) PTR(object);
1597
1598     /* Copy the object. */
1599     while (nwords > 0) {
1600         dest[0] = source[0];
1601         dest[1] = source[1];
1602         dest += 2;
1603         source += 2;
1604         nwords -= 2;
1605     }
1606
1607     /* Return Lisp pointer of new object. */
1608     return ((lispobj) new) | tag;
1609 }
1610
1611 /* to copy large unboxed objects
1612  *
1613  * If the object is in a large object region then it is simply
1614  * promoted, else it is copied. If it's large enough then it's copied
1615  * to a large object region.
1616  *
1617  * Bignums and vectors may have shrunk. If the object is not copied
1618  * the space needs to be reclaimed, and the page_tables corrected.
1619  *
1620  * KLUDGE: There's a lot of cut-and-paste duplication between this
1621  * function and copy_large_object(..). -- WHN 20000619 */
1622 static lispobj
1623 copy_large_unboxed_object(lispobj object, int nwords)
1624 {
1625     int tag;
1626     lispobj *new;
1627     lispobj *source, *dest;
1628     int first_page;
1629
1630     gc_assert(Pointerp(object));
1631     gc_assert(from_space_p(object));
1632     gc_assert((nwords & 0x01) == 0);
1633
1634     if ((nwords > 1024*1024) && gencgc_verbose)
1635         FSHOW((stderr, "/copy_large_unboxed_object: %d bytes\n", nwords*4));
1636
1637     /* Check whether it's a large object. */
1638     first_page = find_page_index((void *)object);
1639     gc_assert(first_page >= 0);
1640
1641     if (page_table[first_page].large_object) {
1642         /* Promote the object. Note: Unboxed objects may have been
1643          * allocated to a BOXED region so it may be necessary to
1644          * change the region to UNBOXED. */
1645         int remaining_bytes;
1646         int next_page;
1647         int bytes_freed;
1648         int old_bytes_used;
1649
1650         gc_assert(page_table[first_page].first_object_offset == 0);
1651
1652         next_page = first_page;
1653         remaining_bytes = nwords*4;
1654         while (remaining_bytes > 4096) {
1655             gc_assert(page_table[next_page].gen == from_space);
1656             gc_assert((page_table[next_page].allocated == UNBOXED_PAGE)
1657                       || (page_table[next_page].allocated == BOXED_PAGE));
1658             gc_assert(page_table[next_page].large_object);
1659             gc_assert(page_table[next_page].first_object_offset==
1660                       -4096*(next_page-first_page));
1661             gc_assert(page_table[next_page].bytes_used == 4096);
1662
1663             page_table[next_page].gen = new_space;
1664             page_table[next_page].allocated = UNBOXED_PAGE;
1665             remaining_bytes -= 4096;
1666             next_page++;
1667         }
1668
1669         /* Now only one page remains, but the object may have shrunk so
1670          * there may be more unused pages which will be freed. */
1671
1672         /* Object may have shrunk but shouldn't have grown - check. */
1673         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1674
1675         page_table[next_page].gen = new_space;
1676         page_table[next_page].allocated = UNBOXED_PAGE;
1677
1678         /* Adjust the bytes_used. */
1679         old_bytes_used = page_table[next_page].bytes_used;
1680         page_table[next_page].bytes_used = remaining_bytes;
1681
1682         bytes_freed = old_bytes_used - remaining_bytes;
1683
1684         /* Free any remaining pages; needs care. */
1685         next_page++;
1686         while ((old_bytes_used == 4096) &&
1687                (page_table[next_page].gen == from_space) &&
1688                ((page_table[next_page].allocated == UNBOXED_PAGE)
1689                 || (page_table[next_page].allocated == BOXED_PAGE)) &&
1690                page_table[next_page].large_object &&
1691                (page_table[next_page].first_object_offset ==
1692                 -(next_page - first_page)*4096)) {
1693             /* Checks out OK, free the page. Don't need to both zeroing
1694              * pages as this should have been done before shrinking the
1695              * object. These pages shouldn't be write-protected, even if
1696              * boxed they should be zero filled. */
1697             gc_assert(page_table[next_page].write_protected == 0);
1698
1699             old_bytes_used = page_table[next_page].bytes_used;
1700             page_table[next_page].allocated = FREE_PAGE;
1701             page_table[next_page].bytes_used = 0;
1702             bytes_freed += old_bytes_used;
1703             next_page++;
1704         }
1705
1706         if ((bytes_freed > 0) && gencgc_verbose)
1707             FSHOW((stderr,
1708                    "/copy_large_unboxed bytes_freed=%d\n",
1709                    bytes_freed));
1710
1711         generations[from_space].bytes_allocated -= 4*nwords + bytes_freed;
1712         generations[new_space].bytes_allocated += 4*nwords;
1713         bytes_allocated -= bytes_freed;
1714
1715         return(object);
1716     }
1717     else {
1718         /* Get tag of object. */
1719         tag = LowtagOf(object);
1720
1721         /* Allocate space. */
1722         new = gc_quick_alloc_large_unboxed(nwords*4);
1723
1724         dest = new;
1725         source = (lispobj *) PTR(object);
1726
1727         /* Copy the object. */
1728         while (nwords > 0) {
1729             dest[0] = source[0];
1730             dest[1] = source[1];
1731             dest += 2;
1732             source += 2;
1733             nwords -= 2;
1734         }
1735
1736         /* Return Lisp pointer of new object. */
1737         return ((lispobj) new) | tag;
1738     }
1739 }
1740 \f
1741 /*
1742  * scavenging
1743  */
1744
1745 #define DIRECT_SCAV 0
1746
1747 /* FIXME: Most calls end up going to a little trouble to compute an
1748  * 'nwords' value. The system might be a little simpler if this
1749  * function used an 'end' parameter instead. */
1750 static void
1751 scavenge(lispobj *start, long nwords)
1752 {
1753     while (nwords > 0) {
1754         lispobj object;
1755 #if DIRECT_SCAV
1756         int type;
1757 #endif
1758         int words_scavenged;
1759
1760         object = *start;
1761         
1762 /*      FSHOW((stderr, "Scavenge: %p, %ld\n", start, nwords)); */
1763
1764         gc_assert(object != 0x01); /* not a forwarding pointer */
1765
1766 #if DIRECT_SCAV
1767         type = TypeOf(object);
1768         words_scavenged = (scavtab[type])(start, object);
1769 #else
1770         if (Pointerp(object)) {
1771             /* It's a pointer. */
1772             if (from_space_p(object)) {
1773                 /* It currently points to old space. Check for a forwarding
1774                  * pointer. */
1775                 lispobj *ptr = (lispobj *)PTR(object);
1776                 lispobj first_word = *ptr;
1777         
1778                 if (first_word == 0x01) {
1779                     /* Yes, there's a forwarding pointer. */
1780                     *start = ptr[1];
1781                     words_scavenged = 1;
1782                 }
1783                 else
1784                     /* Scavenge that pointer. */
1785                     words_scavenged = (scavtab[TypeOf(object)])(start, object);
1786             } else {
1787                 /* It points somewhere other than oldspace. Leave it alone. */
1788                 words_scavenged = 1;
1789             }
1790         } else {
1791             if ((object & 3) == 0) {
1792                 /* It's a fixnum: really easy.. */
1793                 words_scavenged = 1;
1794             } else {
1795                 /* It's some sort of header object or another. */
1796                 words_scavenged = (scavtab[TypeOf(object)])(start, object);
1797             }
1798         }
1799 #endif
1800
1801         start += words_scavenged;
1802         nwords -= words_scavenged;
1803     }
1804     gc_assert(nwords == 0);
1805 }
1806
1807 \f
1808 /*
1809  * code and code-related objects
1810  */
1811
1812 #define RAW_ADDR_OFFSET (6*sizeof(lispobj) - type_FunctionPointer)
1813
1814 static lispobj trans_function_header(lispobj object);
1815 static lispobj trans_boxed(lispobj object);
1816
1817 #if DIRECT_SCAV
1818 static int
1819 scav_function_pointer(lispobj *where, lispobj object)
1820 {
1821     gc_assert(Pointerp(object));
1822
1823     if (from_space_p(object)) {
1824         lispobj first, *first_pointer;
1825
1826         /* object is a pointer into from space. Check to see whether
1827          * it has been forwarded. */
1828         first_pointer = (lispobj *) PTR(object);
1829         first = *first_pointer;
1830
1831         if (first == 0x01) {
1832             /* Forwarded */
1833             *where = first_pointer[1];
1834             return 1;
1835         }
1836         else {
1837             int type;
1838             lispobj copy;
1839
1840             /* must transport object -- object may point to either a
1841              * function header, a closure function header, or to a
1842              * closure header. */
1843
1844             type = TypeOf(first);
1845             switch (type) {
1846             case type_FunctionHeader:
1847             case type_ClosureFunctionHeader:
1848                 copy = trans_function_header(object);
1849                 break;
1850             default:
1851                 copy = trans_boxed(object);
1852                 break;
1853             }
1854
1855             if (copy != object) {
1856                 /* Set forwarding pointer. */
1857                 first_pointer[0] = 0x01;
1858                 first_pointer[1] = copy;
1859             }
1860
1861             first = copy;
1862         }
1863
1864         gc_assert(Pointerp(first));
1865         gc_assert(!from_space_p(first));
1866
1867         *where = first;
1868     }
1869     return 1;
1870 }
1871 #else
1872 static int
1873 scav_function_pointer(lispobj *where, lispobj object)
1874 {
1875     lispobj *first_pointer;
1876     lispobj copy;
1877
1878     gc_assert(Pointerp(object));
1879
1880     /* Object is a pointer into from space - no a FP. */
1881     first_pointer = (lispobj *) PTR(object);
1882
1883     /* must transport object -- object may point to either a function
1884      * header, a closure function header, or to a closure header. */
1885
1886     switch (TypeOf(*first_pointer)) {
1887     case type_FunctionHeader:
1888     case type_ClosureFunctionHeader:
1889         copy = trans_function_header(object);
1890         break;
1891     default:
1892         copy = trans_boxed(object);
1893         break;
1894     }
1895
1896     if (copy != object) {
1897         /* Set forwarding pointer */
1898         first_pointer[0] = 0x01;
1899         first_pointer[1] = copy;
1900     }
1901
1902     gc_assert(Pointerp(copy));
1903     gc_assert(!from_space_p(copy));
1904
1905     *where = copy;
1906
1907     return 1;
1908 }
1909 #endif
1910
1911 /* Scan a x86 compiled code object, looking for possible fixups that
1912  * have been missed after a move.
1913  *
1914  * Two types of fixups are needed:
1915  * 1. Absolute fixups to within the code object.
1916  * 2. Relative fixups to outside the code object.
1917  *
1918  * Currently only absolute fixups to the constant vector, or to the
1919  * code area are checked. */
1920 void
1921 sniff_code_object(struct code *code, unsigned displacement)
1922 {
1923     int nheader_words, ncode_words, nwords;
1924     void *p;
1925     void *constants_start_addr, *constants_end_addr;
1926     void *code_start_addr, *code_end_addr;
1927     int fixup_found = 0;
1928
1929     if (!check_code_fixups)
1930         return;
1931
1932     /* It's ok if it's byte compiled code. The trace table offset will
1933      * be a fixnum if it's x86 compiled code - check. */
1934     if (code->trace_table_offset & 0x3) {
1935         FSHOW((stderr, "/Sniffing byte compiled code object at %x.\n", code));
1936         return;
1937     }
1938
1939     /* Else it's x86 machine code. */
1940
1941     ncode_words = fixnum_value(code->code_size);
1942     nheader_words = HeaderValue(*(lispobj *)code);
1943     nwords = ncode_words + nheader_words;
1944
1945     constants_start_addr = (void *)code + 5*4;
1946     constants_end_addr = (void *)code + nheader_words*4;
1947     code_start_addr = (void *)code + nheader_words*4;
1948     code_end_addr = (void *)code + nwords*4;
1949
1950     /* Work through the unboxed code. */
1951     for (p = code_start_addr; p < code_end_addr; p++) {
1952         void *data = *(void **)p;
1953         unsigned d1 = *((unsigned char *)p - 1);
1954         unsigned d2 = *((unsigned char *)p - 2);
1955         unsigned d3 = *((unsigned char *)p - 3);
1956         unsigned d4 = *((unsigned char *)p - 4);
1957         unsigned d5 = *((unsigned char *)p - 5);
1958         unsigned d6 = *((unsigned char *)p - 6);
1959
1960         /* Check for code references. */
1961         /* Check for a 32 bit word that looks like an absolute
1962            reference to within the code adea of the code object. */
1963         if ((data >= (code_start_addr-displacement))
1964             && (data < (code_end_addr-displacement))) {
1965             /* function header */
1966             if ((d4 == 0x5e)
1967                 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) == (unsigned)code)) {
1968                 /* Skip the function header */
1969                 p += 6*4 - 4 - 1;
1970                 continue;
1971             }
1972             /* the case of PUSH imm32 */
1973             if (d1 == 0x68) {
1974                 fixup_found = 1;
1975                 FSHOW((stderr,
1976                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1977                        p, d6, d5, d4, d3, d2, d1, data));
1978                 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1979             }
1980             /* the case of MOV [reg-8],imm32 */
1981             if ((d3 == 0xc7)
1982                 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1983                     || d2==0x45 || d2==0x46 || d2==0x47)
1984                 && (d1 == 0xf8)) {
1985                 fixup_found = 1;
1986                 FSHOW((stderr,
1987                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1988                        p, d6, d5, d4, d3, d2, d1, data));
1989                 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1990             }
1991             /* the case of LEA reg,[disp32] */
1992             if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1993                 fixup_found = 1;
1994                 FSHOW((stderr,
1995                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1996                        p, d6, d5, d4, d3, d2, d1, data));
1997                 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1998             }
1999         }
2000
2001         /* Check for constant references. */
2002         /* Check for a 32 bit word that looks like an absolute
2003            reference to within the constant vector. Constant references
2004            will be aligned. */
2005         if ((data >= (constants_start_addr-displacement))
2006             && (data < (constants_end_addr-displacement))
2007             && (((unsigned)data & 0x3) == 0)) {
2008             /*  Mov eax,m32 */
2009             if (d1 == 0xa1) {
2010                 fixup_found = 1;
2011                 FSHOW((stderr,
2012                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2013                        p, d6, d5, d4, d3, d2, d1, data));
2014                 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
2015             }
2016
2017             /*  the case of MOV m32,EAX */
2018             if (d1 == 0xa3) {
2019                 fixup_found = 1;
2020                 FSHOW((stderr,
2021                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2022                        p, d6, d5, d4, d3, d2, d1, data));
2023                 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
2024             }
2025
2026             /* the case of CMP m32,imm32 */             
2027             if ((d1 == 0x3d) && (d2 == 0x81)) {
2028                 fixup_found = 1;
2029                 FSHOW((stderr,
2030                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2031                        p, d6, d5, d4, d3, d2, d1, data));
2032                 /* XX Check this */
2033                 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
2034             }
2035
2036             /* Check for a mod=00, r/m=101 byte. */
2037             if ((d1 & 0xc7) == 5) {
2038                 /* Cmp m32,reg */
2039                 if (d2 == 0x39) {
2040                     fixup_found = 1;
2041                     FSHOW((stderr,
2042                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2043                            p, d6, d5, d4, d3, d2, d1, data));
2044                     FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
2045                 }
2046                 /* the case of CMP reg32,m32 */
2047                 if (d2 == 0x3b) {
2048                     fixup_found = 1;
2049                     FSHOW((stderr,
2050                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2051                            p, d6, d5, d4, d3, d2, d1, data));
2052                     FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
2053                 }
2054                 /* the case of MOV m32,reg32 */
2055                 if (d2 == 0x89) {
2056                     fixup_found = 1;
2057                     FSHOW((stderr,
2058                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2059                            p, d6, d5, d4, d3, d2, d1, data));
2060                     FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
2061                 }
2062                 /* the case of MOV reg32,m32 */
2063                 if (d2 == 0x8b) {
2064                     fixup_found = 1;
2065                     FSHOW((stderr,
2066                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2067                            p, d6, d5, d4, d3, d2, d1, data));
2068                     FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
2069                 }
2070                 /* the case of LEA reg32,m32 */
2071                 if (d2 == 0x8d) {
2072                     fixup_found = 1;
2073                     FSHOW((stderr,
2074                            "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
2075                            p, d6, d5, d4, d3, d2, d1, data));
2076                     FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
2077                 }
2078             }
2079         }
2080     }
2081
2082     /* If anything was found, print some information on the code
2083      * object. */
2084     if (fixup_found) {
2085         FSHOW((stderr,
2086                "/compiled code object at %x: header words = %d, code words = %d\n",
2087                code, nheader_words, ncode_words));
2088         FSHOW((stderr,
2089                "/const start = %x, end = %x\n",
2090                constants_start_addr, constants_end_addr));
2091         FSHOW((stderr,
2092                "/code start = %x, end = %x\n",
2093                code_start_addr, code_end_addr));
2094     }
2095 }
2096
2097 static void
2098 apply_code_fixups(struct code *old_code, struct code *new_code)
2099 {
2100     int nheader_words, ncode_words, nwords;
2101     void *constants_start_addr, *constants_end_addr;
2102     void *code_start_addr, *code_end_addr;
2103     lispobj fixups = NIL;
2104     unsigned displacement = (unsigned)new_code - (unsigned)old_code;
2105     struct vector *fixups_vector;
2106
2107     /* It's OK if it's byte compiled code. The trace table offset will
2108      * be a fixnum if it's x86 compiled code - check. */
2109     if (new_code->trace_table_offset & 0x3) {
2110 /*      FSHOW((stderr, "/byte compiled code object at %x\n", new_code)); */
2111         return;
2112     }
2113
2114     /* Else it's x86 machine code. */
2115     ncode_words = fixnum_value(new_code->code_size);
2116     nheader_words = HeaderValue(*(lispobj *)new_code);
2117     nwords = ncode_words + nheader_words;
2118     /* FSHOW((stderr,
2119              "/compiled code object at %x: header words = %d, code words = %d\n",
2120              new_code, nheader_words, ncode_words)); */
2121     constants_start_addr = (void *)new_code + 5*4;
2122     constants_end_addr = (void *)new_code + nheader_words*4;
2123     code_start_addr = (void *)new_code + nheader_words*4;
2124     code_end_addr = (void *)new_code + nwords*4;
2125     /*
2126     FSHOW((stderr,
2127            "/const start = %x, end = %x\n",
2128            constants_start_addr,constants_end_addr));
2129     FSHOW((stderr,
2130            "/code start = %x; end = %x\n",
2131            code_start_addr,code_end_addr));
2132     */
2133
2134     /* The first constant should be a pointer to the fixups for this
2135        code objects. Check. */
2136     fixups = new_code->constants[0];
2137
2138     /* It will be 0 or the unbound-marker if there are no fixups, and
2139      * will be an other pointer if it is valid. */
2140     if ((fixups == 0) || (fixups == type_UnboundMarker) || !Pointerp(fixups)) {
2141         /* Check for possible errors. */
2142         if (check_code_fixups)
2143             sniff_code_object(new_code, displacement);
2144
2145         /*fprintf(stderr,"Fixups for code object not found!?\n");
2146           fprintf(stderr,"*** Compiled code object at %x: header_words=%d code_words=%d .\n",
2147           new_code, nheader_words, ncode_words);
2148           fprintf(stderr,"*** Const. start = %x; end= %x; Code start = %x; end = %x\n",
2149           constants_start_addr,constants_end_addr,
2150           code_start_addr,code_end_addr);*/
2151         return;
2152     }
2153
2154     fixups_vector = (struct vector *)PTR(fixups);
2155
2156     /* Could be pointing to a forwarding pointer. */
2157     if (Pointerp(fixups) && (find_page_index((void*)fixups_vector) != -1)
2158         && (fixups_vector->header == 0x01)) {
2159         /* If so, then follow it. */
2160         /*SHOW("following pointer to a forwarding pointer");*/
2161         fixups_vector = (struct vector *)PTR((lispobj)fixups_vector->length);
2162     }
2163
2164     /*SHOW("got fixups");*/
2165
2166     if (TypeOf(fixups_vector->header) == type_SimpleArrayUnsignedByte32) {
2167         /* Got the fixups for the code block. Now work through the vector,
2168            and apply a fixup at each address. */
2169         int length = fixnum_value(fixups_vector->length);
2170         int i;
2171         for (i = 0; i < length; i++) {
2172             unsigned offset = fixups_vector->data[i];
2173             /* Now check the current value of offset. */
2174             unsigned old_value =
2175                 *(unsigned *)((unsigned)code_start_addr + offset);
2176
2177             /* If it's within the old_code object then it must be an
2178              * absolute fixup (relative ones are not saved) */
2179             if ((old_value >= (unsigned)old_code)
2180                 && (old_value < ((unsigned)old_code + nwords*4)))
2181                 /* So add the dispacement. */
2182                 *(unsigned *)((unsigned)code_start_addr + offset) =
2183                     old_value + displacement;
2184             else
2185                 /* It is outside the old code object so it must be a
2186                  * relative fixup (absolute fixups are not saved). So
2187                  * subtract the displacement. */
2188                 *(unsigned *)((unsigned)code_start_addr + offset) =
2189                     old_value - displacement;
2190         }
2191     }
2192
2193     /* Check for possible errors. */
2194     if (check_code_fixups) {
2195         sniff_code_object(new_code,displacement);
2196     }
2197 }
2198
2199 static struct code *
2200 trans_code(struct code *code)
2201 {
2202     struct code *new_code;
2203     lispobj l_code, l_new_code;
2204     int nheader_words, ncode_words, nwords;
2205     unsigned long displacement;
2206     lispobj fheaderl, *prev_pointer;
2207
2208     /* FSHOW((stderr,
2209              "\n/transporting code object located at 0x%08x\n",
2210              (unsigned long) code)); */
2211
2212     /* If object has already been transported, just return pointer. */
2213     if (*((lispobj *)code) == 0x01)
2214         return (struct code*)(((lispobj *)code)[1]);
2215
2216     gc_assert(TypeOf(code->header) == type_CodeHeader);
2217
2218     /* Prepare to transport the code vector. */
2219     l_code = (lispobj) code | type_OtherPointer;
2220
2221     ncode_words = fixnum_value(code->code_size);
2222     nheader_words = HeaderValue(code->header);
2223     nwords = ncode_words + nheader_words;
2224     nwords = CEILING(nwords, 2);
2225
2226     l_new_code = copy_large_object(l_code, nwords);
2227     new_code = (struct code *) PTR(l_new_code);
2228
2229     /* may not have been moved.. */
2230     if (new_code == code)
2231         return new_code;
2232
2233     displacement = l_new_code - l_code;
2234
2235     /*
2236     FSHOW((stderr,
2237            "/old code object at 0x%08x, new code object at 0x%08x\n",
2238            (unsigned long) code,
2239            (unsigned long) new_code));
2240     FSHOW((stderr, "/Code object is %d words long.\n", nwords));
2241     */
2242
2243     /* Set forwarding pointer. */
2244     ((lispobj *)code)[0] = 0x01;
2245     ((lispobj *)code)[1] = l_new_code;
2246
2247     /* Set forwarding pointers for all the function headers in the
2248      * code object. Also fix all self pointers. */
2249
2250     fheaderl = code->entry_points;
2251     prev_pointer = &new_code->entry_points;
2252
2253     while (fheaderl != NIL) {
2254         struct function *fheaderp, *nfheaderp;
2255         lispobj nfheaderl;
2256
2257         fheaderp = (struct function *) PTR(fheaderl);
2258         gc_assert(TypeOf(fheaderp->header) == type_FunctionHeader);
2259
2260         /* Calculate the new function pointer and the new */
2261         /* function header. */
2262         nfheaderl = fheaderl + displacement;
2263         nfheaderp = (struct function *) PTR(nfheaderl);
2264
2265         /* Set forwarding pointer. */
2266         ((lispobj *)fheaderp)[0] = 0x01;
2267         ((lispobj *)fheaderp)[1] = nfheaderl;
2268
2269         /* Fix self pointer. */
2270         nfheaderp->self = nfheaderl + RAW_ADDR_OFFSET;
2271
2272         *prev_pointer = nfheaderl;
2273
2274         fheaderl = fheaderp->next;
2275         prev_pointer = &nfheaderp->next;
2276     }
2277
2278     /*  sniff_code_object(new_code,displacement);*/
2279     apply_code_fixups(code,new_code);
2280
2281     return new_code;
2282 }
2283
2284 static int
2285 scav_code_header(lispobj *where, lispobj object)
2286 {
2287     struct code *code;
2288     int nheader_words, ncode_words, nwords;
2289     lispobj fheaderl;
2290     struct function *fheaderp;
2291
2292     code = (struct code *) where;
2293     ncode_words = fixnum_value(code->code_size);
2294     nheader_words = HeaderValue(object);
2295     nwords = ncode_words + nheader_words;
2296     nwords = CEILING(nwords, 2);
2297
2298     /* Scavenge the boxed section of the code data block. */
2299     scavenge(where + 1, nheader_words - 1);
2300
2301     /* Scavenge the boxed section of each function object in the */
2302     /* code data block. */
2303     fheaderl = code->entry_points;
2304     while (fheaderl != NIL) {
2305         fheaderp = (struct function *) PTR(fheaderl);
2306         gc_assert(TypeOf(fheaderp->header) == type_FunctionHeader);
2307
2308         scavenge(&fheaderp->name, 1);
2309         scavenge(&fheaderp->arglist, 1);
2310         scavenge(&fheaderp->type, 1);
2311                 
2312         fheaderl = fheaderp->next;
2313     }
2314         
2315     return nwords;
2316 }
2317
2318 static lispobj
2319 trans_code_header(lispobj object)
2320 {
2321     struct code *ncode;
2322
2323     ncode = trans_code((struct code *) PTR(object));
2324     return (lispobj) ncode | type_OtherPointer;
2325 }
2326
2327 static int
2328 size_code_header(lispobj *where)
2329 {
2330     struct code *code;
2331     int nheader_words, ncode_words, nwords;
2332
2333     code = (struct code *) where;
2334         
2335     ncode_words = fixnum_value(code->code_size);
2336     nheader_words = HeaderValue(code->header);
2337     nwords = ncode_words + nheader_words;
2338     nwords = CEILING(nwords, 2);
2339
2340     return nwords;
2341 }
2342
2343 static int
2344 scav_return_pc_header(lispobj *where, lispobj object)
2345 {
2346     lose("attempted to scavenge a return PC header where=0x%08x object=0x%08x",
2347          (unsigned long) where,
2348          (unsigned long) object);
2349     return 0; /* bogus return value to satisfy static type checking */
2350 }
2351
2352 static lispobj
2353 trans_return_pc_header(lispobj object)
2354 {
2355     struct function *return_pc;
2356     unsigned long offset;
2357     struct code *code, *ncode;
2358
2359     SHOW("/trans_return_pc_header: Will this work?");
2360
2361     return_pc = (struct function *) PTR(object);
2362     offset = HeaderValue(return_pc->header) * 4;
2363
2364     /* Transport the whole code object. */
2365     code = (struct code *) ((unsigned long) return_pc - offset);
2366     ncode = trans_code(code);
2367
2368     return ((lispobj) ncode + offset) | type_OtherPointer;
2369 }
2370
2371 /* On the 386, closures hold a pointer to the raw address instead of the
2372  * function object. */
2373 #ifdef __i386__
2374 static int
2375 scav_closure_header(lispobj *where, lispobj object)
2376 {
2377     struct closure *closure;
2378     lispobj fun;
2379
2380     closure = (struct closure *)where;
2381     fun = closure->function - RAW_ADDR_OFFSET;
2382     scavenge(&fun, 1);
2383     /* The function may have moved so update the raw address. But
2384      * don't write unnecessarily. */
2385     if (closure->function != fun + RAW_ADDR_OFFSET)
2386         closure->function = fun + RAW_ADDR_OFFSET;
2387
2388     return 2;
2389 }
2390 #endif
2391
2392 static int
2393 scav_function_header(lispobj *where, lispobj object)
2394 {
2395     lose("attempted to scavenge a function header where=0x%08x object=0x%08x",
2396          (unsigned long) where,
2397          (unsigned long) object);
2398     return 0; /* bogus return value to satisfy static type checking */
2399 }
2400
2401 static lispobj
2402 trans_function_header(lispobj object)
2403 {
2404     struct function *fheader;
2405     unsigned long offset;
2406     struct code *code, *ncode;
2407
2408     fheader = (struct function *) PTR(object);
2409     offset = HeaderValue(fheader->header) * 4;
2410
2411     /* Transport the whole code object. */
2412     code = (struct code *) ((unsigned long) fheader - offset);
2413     ncode = trans_code(code);
2414
2415     return ((lispobj) ncode + offset) | type_FunctionPointer;
2416 }
2417 \f
2418 /*
2419  * instances
2420  */
2421
2422 #if DIRECT_SCAV
2423 static int
2424 scav_instance_pointer(lispobj *where, lispobj object)
2425 {
2426     if (from_space_p(object)) {
2427         lispobj first, *first_pointer;
2428
2429         /* Object is a pointer into from space. Check to see */
2430         /* whether it has been forwarded. */
2431         first_pointer = (lispobj *) PTR(object);
2432         first = *first_pointer;
2433
2434         if (first == 0x01) {
2435             /* forwarded */
2436             first = first_pointer[1];
2437         } else {
2438             first = trans_boxed(object);
2439             gc_assert(first != object);
2440             /* Set forwarding pointer. */
2441             first_pointer[0] = 0x01;
2442             first_pointer[1] = first;
2443         }
2444         *where = first;
2445     }
2446     return 1;
2447 }
2448 #else
2449 static int
2450 scav_instance_pointer(lispobj *where, lispobj object)
2451 {
2452     lispobj copy, *first_pointer;
2453
2454     /* Object is a pointer into from space - not a FP. */
2455     copy = trans_boxed(object);
2456
2457     gc_assert(copy != object);
2458
2459     first_pointer = (lispobj *) PTR(object);
2460
2461     /* Set forwarding pointer. */
2462     first_pointer[0] = 0x01;
2463     first_pointer[1] = copy;
2464     *where = copy;
2465
2466     return 1;
2467 }
2468 #endif
2469 \f
2470 /*
2471  * lists and conses
2472  */
2473
2474 static lispobj trans_list(lispobj object);
2475
2476 #if DIRECT_SCAV
2477 static int
2478 scav_list_pointer(lispobj *where, lispobj object)
2479 {
2480     /* KLUDGE: There's lots of cut-and-paste duplication between this
2481      * and scav_instance_pointer(..), scav_other_pointer(..), and
2482      * perhaps other functions too. -- WHN 20000620 */
2483
2484     gc_assert(Pointerp(object));
2485
2486     if (from_space_p(object)) {
2487         lispobj first, *first_pointer;
2488
2489         /* Object is a pointer into from space. Check to see whether it has
2490          * been forwarded. */
2491         first_pointer = (lispobj *) PTR(object);
2492         first = *first_pointer;
2493
2494         if (first == 0x01) {
2495             /* forwarded */
2496             first = first_pointer[1];
2497         } else {
2498             first = trans_list(object);
2499
2500             /* Set forwarding pointer */
2501             first_pointer[0] = 0x01;
2502             first_pointer[1] = first;
2503         }
2504
2505         gc_assert(Pointerp(first));
2506         gc_assert(!from_space_p(first));
2507         *where = first;
2508     }
2509     return 1;
2510 }
2511 #else
2512 static int
2513 scav_list_pointer(lispobj *where, lispobj object)
2514 {
2515     lispobj first, *first_pointer;
2516
2517     gc_assert(Pointerp(object));
2518
2519     /* Object is a pointer into from space - not FP. */
2520
2521     first = trans_list(object);
2522     gc_assert(first != object);
2523
2524     first_pointer = (lispobj *) PTR(object);
2525
2526     /* Set forwarding pointer */
2527     first_pointer[0] = 0x01;
2528     first_pointer[1] = first;
2529
2530     gc_assert(Pointerp(first));
2531     gc_assert(!from_space_p(first));
2532     *where = first;
2533     return 1;
2534 }
2535 #endif
2536
2537 static lispobj
2538 trans_list(lispobj object)
2539 {
2540     lispobj new_list_pointer;
2541     struct cons *cons, *new_cons;
2542     lispobj cdr;
2543
2544     gc_assert(from_space_p(object));
2545
2546     cons = (struct cons *) PTR(object);
2547
2548     /* Copy 'object'. */
2549     new_cons = (struct cons *) gc_quick_alloc(sizeof(struct cons));
2550     new_cons->car = cons->car;
2551     new_cons->cdr = cons->cdr; /* updated later */
2552     new_list_pointer = (lispobj)new_cons | LowtagOf(object);
2553
2554     /* Grab the cdr before it is clobbered. */
2555     cdr = cons->cdr;
2556
2557     /* Set forwarding pointer (clobbers start of list). */
2558     cons->car = 0x01;
2559     cons->cdr = new_list_pointer;
2560
2561     /* Try to linearize the list in the cdr direction to help reduce
2562      * paging. */
2563     while (1) {
2564         lispobj  new_cdr;
2565         struct cons *cdr_cons, *new_cdr_cons;
2566
2567         if (LowtagOf(cdr) != type_ListPointer || !from_space_p(cdr)
2568             || (*((lispobj *)PTR(cdr)) == 0x01))
2569             break;
2570
2571         cdr_cons = (struct cons *) PTR(cdr);
2572
2573         /* Copy 'cdr'. */
2574         new_cdr_cons = (struct cons*) gc_quick_alloc(sizeof(struct cons));
2575         new_cdr_cons->car = cdr_cons->car;
2576         new_cdr_cons->cdr = cdr_cons->cdr;
2577         new_cdr = (lispobj)new_cdr_cons | LowtagOf(cdr);
2578
2579         /* Grab the cdr before it is clobbered. */
2580         cdr = cdr_cons->cdr;
2581
2582         /* Set forwarding pointer. */
2583         cdr_cons->car = 0x01;
2584         cdr_cons->cdr = new_cdr;
2585
2586         /* Update the cdr of the last cons copied into new space to
2587          * keep the newspace scavenge from having to do it. */
2588         new_cons->cdr = new_cdr;
2589
2590         new_cons = new_cdr_cons;
2591     }
2592
2593     return new_list_pointer;
2594 }
2595
2596 \f
2597 /*
2598  * scavenging and transporting other pointers
2599  */
2600
2601 #if DIRECT_SCAV
2602 static int
2603 scav_other_pointer(lispobj *where, lispobj object)
2604 {
2605     gc_assert(Pointerp(object));
2606
2607     if (from_space_p(object)) {
2608         lispobj first, *first_pointer;
2609
2610         /* Object is a pointer into from space. Check to see */
2611         /* whether it has been forwarded. */
2612         first_pointer = (lispobj *) PTR(object);
2613         first = *first_pointer;
2614
2615         if (first == 0x01) {
2616             /* Forwarded. */
2617             first = first_pointer[1];
2618             *where = first;
2619         } else {
2620             first = (transother[TypeOf(first)])(object);
2621
2622             if (first != object) {
2623                 /* Set forwarding pointer */
2624                 first_pointer[0] = 0x01;
2625                 first_pointer[1] = first;
2626                 *where = first;
2627             }
2628         }
2629
2630         gc_assert(Pointerp(first));
2631         gc_assert(!from_space_p(first));
2632     }
2633     return 1;
2634 }
2635 #else
2636 static int
2637 scav_other_pointer(lispobj *where, lispobj object)
2638 {
2639     lispobj first, *first_pointer;
2640
2641     gc_assert(Pointerp(object));
2642
2643     /* Object is a pointer into from space - not FP. */
2644     first_pointer = (lispobj *) PTR(object);
2645
2646     first = (transother[TypeOf(*first_pointer)])(object);
2647
2648     if (first != object) {
2649         /* Set forwarding pointer. */
2650         first_pointer[0] = 0x01;
2651         first_pointer[1] = first;
2652         *where = first;
2653     }
2654
2655     gc_assert(Pointerp(first));
2656     gc_assert(!from_space_p(first));
2657
2658     return 1;
2659 }
2660 #endif
2661
2662 \f
2663 /*
2664  * immediate, boxed, and unboxed objects
2665  */
2666
2667 static int
2668 size_pointer(lispobj *where)
2669 {
2670     return 1;
2671 }
2672
2673 static int
2674 scav_immediate(lispobj *where, lispobj object)
2675 {
2676     return 1;
2677 }
2678
2679 static lispobj
2680 trans_immediate(lispobj object)
2681 {
2682     lose("trying to transport an immediate");
2683     return NIL; /* bogus return value to satisfy static type checking */
2684 }
2685
2686 static int
2687 size_immediate(lispobj *where)
2688 {
2689     return 1;
2690 }
2691
2692
2693 static int
2694 scav_boxed(lispobj *where, lispobj object)
2695 {
2696     return 1;
2697 }
2698
2699 static lispobj
2700 trans_boxed(lispobj object)
2701 {
2702     lispobj header;
2703     unsigned long length;
2704
2705     gc_assert(Pointerp(object));
2706
2707     header = *((lispobj *) PTR(object));
2708     length = HeaderValue(header) + 1;
2709     length = CEILING(length, 2);
2710
2711     return copy_object(object, length);
2712 }
2713
2714 static lispobj
2715 trans_boxed_large(lispobj object)
2716 {
2717     lispobj header;
2718     unsigned long length;
2719
2720     gc_assert(Pointerp(object));
2721
2722     header = *((lispobj *) PTR(object));
2723     length = HeaderValue(header) + 1;
2724     length = CEILING(length, 2);
2725
2726     return copy_large_object(object, length);
2727 }
2728
2729 static int
2730 size_boxed(lispobj *where)
2731 {
2732     lispobj header;
2733     unsigned long length;
2734
2735     header = *where;
2736     length = HeaderValue(header) + 1;
2737     length = CEILING(length, 2);
2738
2739     return length;
2740 }
2741
2742 static int
2743 scav_fdefn(lispobj *where, lispobj object)
2744 {
2745     struct fdefn *fdefn;
2746
2747     fdefn = (struct fdefn *)where;
2748
2749     /* FSHOW((stderr, "scav_fdefn, function = %p, raw_addr = %p\n", 
2750        fdefn->function, fdefn->raw_addr)); */
2751
2752     if ((char *)(fdefn->function + RAW_ADDR_OFFSET) == fdefn->raw_addr) {
2753         scavenge(where + 1, sizeof(struct fdefn)/sizeof(lispobj) - 1);
2754
2755         /* Don't write unnecessarily. */
2756         if (fdefn->raw_addr != (char *)(fdefn->function + RAW_ADDR_OFFSET))
2757             fdefn->raw_addr = (char *)(fdefn->function + RAW_ADDR_OFFSET);
2758
2759         return sizeof(struct fdefn) / sizeof(lispobj);
2760     } else {
2761         return 1;
2762     }
2763 }
2764
2765 static int
2766 scav_unboxed(lispobj *where, lispobj object)
2767 {
2768     unsigned long length;
2769
2770     length = HeaderValue(object) + 1;
2771     length = CEILING(length, 2);
2772
2773     return length;
2774 }
2775
2776 static lispobj
2777 trans_unboxed(lispobj object)
2778 {
2779     lispobj header;
2780     unsigned long length;
2781
2782
2783     gc_assert(Pointerp(object));
2784
2785     header = *((lispobj *) PTR(object));
2786     length = HeaderValue(header) + 1;
2787     length = CEILING(length, 2);
2788
2789     return copy_unboxed_object(object, length);
2790 }
2791
2792 static lispobj
2793 trans_unboxed_large(lispobj object)
2794 {
2795     lispobj header;
2796     unsigned long length;
2797
2798
2799     gc_assert(Pointerp(object));
2800
2801     header = *((lispobj *) PTR(object));
2802     length = HeaderValue(header) + 1;
2803     length = CEILING(length, 2);
2804
2805     return copy_large_unboxed_object(object, length);
2806 }
2807
2808 static int
2809 size_unboxed(lispobj *where)
2810 {
2811     lispobj header;
2812     unsigned long length;
2813
2814     header = *where;
2815     length = HeaderValue(header) + 1;
2816     length = CEILING(length, 2);
2817
2818     return length;
2819 }
2820 \f
2821 /*
2822  * vector-like objects
2823  */
2824
2825 #define NWORDS(x,y) (CEILING((x),(y)) / (y))
2826
2827 static int
2828 scav_string(lispobj *where, lispobj object)
2829 {
2830     struct vector *vector;
2831     int length, nwords;
2832
2833     /* NOTE: Strings contain one more byte of data than the length */
2834     /* slot indicates. */
2835
2836     vector = (struct vector *) where;
2837     length = fixnum_value(vector->length) + 1;
2838     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2839
2840     return nwords;
2841 }
2842
2843 static lispobj
2844 trans_string(lispobj object)
2845 {
2846     struct vector *vector;
2847     int length, nwords;
2848
2849     gc_assert(Pointerp(object));
2850
2851     /* NOTE: A string contains one more byte of data (a terminating
2852      * '\0' to help when interfacing with C functions) than indicated
2853      * by the length slot. */
2854
2855     vector = (struct vector *) PTR(object);
2856     length = fixnum_value(vector->length) + 1;
2857     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2858
2859     return copy_large_unboxed_object(object, nwords);
2860 }
2861
2862 static int
2863 size_string(lispobj *where)
2864 {
2865     struct vector *vector;
2866     int length, nwords;
2867
2868     /* NOTE: A string contains one more byte of data (a terminating
2869      * '\0' to help when interfacing with C functions) than indicated
2870      * by the length slot. */
2871
2872     vector = (struct vector *) where;
2873     length = fixnum_value(vector->length) + 1;
2874     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2875
2876     return nwords;
2877 }
2878
2879 /* FIXME: What does this mean? */
2880 int gencgc_hash = 1;
2881
2882 static int
2883 scav_vector(lispobj *where, lispobj object)
2884 {
2885     unsigned int kv_length;
2886     lispobj *kv_vector;
2887     unsigned int length = 0; /* (0 = dummy to stop GCC warning) */
2888     lispobj *hash_table;
2889     lispobj empty_symbol;
2890     unsigned int *index_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2891     unsigned int *next_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2892     unsigned int *hash_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2893     lispobj weak_p_obj;
2894     unsigned next_vector_length = 0;
2895
2896     /* FIXME: A comment explaining this would be nice. It looks as
2897      * though SB-VM:VECTOR-VALID-HASHING-SUBTYPE is set for EQ-based
2898      * hash tables in the Lisp HASH-TABLE code, and nowhere else. */
2899     if (HeaderValue(object) != subtype_VectorValidHashing)
2900         return 1;
2901
2902     if (!gencgc_hash) {
2903         /* This is set for backward compatibility. FIXME: Do we need
2904          * this any more? */
2905         *where = (subtype_VectorMustRehash << type_Bits) | type_SimpleVector;
2906         return 1;
2907     }
2908
2909     kv_length = fixnum_value(where[1]);
2910     kv_vector = where + 2;  /* Skip the header and length. */
2911     /*FSHOW((stderr,"/kv_length = %d\n", kv_length));*/
2912
2913     /* Scavenge element 0, which may be a hash-table structure. */
2914     scavenge(where+2, 1);
2915     if (!Pointerp(where[2])) {
2916         lose("no pointer at %x in hash table", where[2]);
2917     }
2918     hash_table = (lispobj *)PTR(where[2]);
2919     /*FSHOW((stderr,"/hash_table = %x\n", hash_table));*/
2920     if (TypeOf(hash_table[0]) != type_InstanceHeader) {
2921         lose("hash table not instance (%x at %x)", hash_table[0], hash_table);
2922     }
2923
2924     /* Scavenge element 1, which should be some internal symbol that
2925      * the hash table code reserves for marking empty slots. */
2926     scavenge(where+3, 1);
2927     if (!Pointerp(where[3])) {
2928         lose("not empty-hash-table-slot symbol pointer: %x", where[3]);
2929     }
2930     empty_symbol = where[3];
2931     /* fprintf(stderr,"* empty_symbol = %x\n", empty_symbol);*/
2932     if (TypeOf(*(lispobj *)PTR(empty_symbol)) != type_SymbolHeader) {
2933         lose("not a symbol where empty-hash-table-slot symbol expected: %x",
2934              *(lispobj *)PTR(empty_symbol));
2935     }
2936
2937     /* Scavenge hash table, which will fix the positions of the other
2938      * needed objects. */
2939     scavenge(hash_table, 16);
2940
2941     /* Cross-check the kv_vector. */
2942     if (where != (lispobj *)PTR(hash_table[9])) {
2943         lose("hash_table table!=this table %x", hash_table[9]);
2944     }
2945
2946     /* WEAK-P */
2947     weak_p_obj = hash_table[10];
2948
2949     /* index vector */
2950     {
2951         lispobj index_vector_obj = hash_table[13];
2952
2953         if (Pointerp(index_vector_obj) &&
2954             (TypeOf(*(lispobj *)PTR(index_vector_obj)) == type_SimpleArrayUnsignedByte32)) {
2955             index_vector = ((unsigned int *)PTR(index_vector_obj)) + 2;
2956             /*FSHOW((stderr, "/index_vector = %x\n",index_vector));*/
2957             length = fixnum_value(((unsigned int *)PTR(index_vector_obj))[1]);
2958             /*FSHOW((stderr, "/length = %d\n", length));*/
2959         } else {
2960             lose("invalid index_vector %x", index_vector_obj);
2961         }
2962     }
2963
2964     /* next vector */
2965     {
2966         lispobj next_vector_obj = hash_table[14];
2967
2968         if (Pointerp(next_vector_obj) &&
2969             (TypeOf(*(lispobj *)PTR(next_vector_obj)) == type_SimpleArrayUnsignedByte32)) {
2970             next_vector = ((unsigned int *)PTR(next_vector_obj)) + 2;
2971             /*FSHOW((stderr, "/next_vector = %x\n", next_vector));*/
2972             next_vector_length = fixnum_value(((unsigned int *)PTR(next_vector_obj))[1]);
2973             /*FSHOW((stderr, "/next_vector_length = %d\n", next_vector_length));*/
2974         } else {
2975             lose("invalid next_vector %x", next_vector_obj);
2976         }
2977     }
2978
2979     /* maybe hash vector */
2980     {
2981         /* FIXME: This bare "15" offset should become a symbolic
2982          * expression of some sort. And all the other bare offsets
2983          * too. And the bare "16" in scavenge(hash_table, 16). And
2984          * probably other stuff too. Ugh.. */
2985         lispobj hash_vector_obj = hash_table[15];
2986
2987         if (Pointerp(hash_vector_obj) &&
2988             (TypeOf(*(lispobj *)PTR(hash_vector_obj))
2989              == type_SimpleArrayUnsignedByte32)) {
2990             hash_vector = ((unsigned int *)PTR(hash_vector_obj)) + 2;
2991             /*FSHOW((stderr, "/hash_vector = %x\n", hash_vector));*/
2992             gc_assert(fixnum_value(((unsigned int *)PTR(hash_vector_obj))[1])
2993                       == next_vector_length);
2994         } else {
2995             hash_vector = NULL;
2996             /*FSHOW((stderr, "/no hash_vector: %x\n", hash_vector_obj));*/
2997         }
2998     }
2999
3000     /* These lengths could be different as the index_vector can be a
3001      * different length from the others, a larger index_vector could help
3002      * reduce collisions. */
3003     gc_assert(next_vector_length*2 == kv_length);
3004
3005     /* now all set up.. */
3006
3007     /* Work through the KV vector. */
3008     {
3009         int i;
3010         for (i = 1; i < next_vector_length; i++) {
3011             lispobj old_key = kv_vector[2*i];
3012             unsigned int  old_index = (old_key & 0x1fffffff)%length;
3013
3014             /* Scavenge the key and value. */
3015             scavenge(&kv_vector[2*i],2);
3016
3017             /* Check whether the key has moved and is EQ based. */
3018             {
3019                 lispobj new_key = kv_vector[2*i];
3020                 unsigned int new_index = (new_key & 0x1fffffff)%length;
3021
3022                 if ((old_index != new_index) &&
3023                     ((!hash_vector) || (hash_vector[i] == 0x80000000)) &&
3024                     ((new_key != empty_symbol) ||
3025                      (kv_vector[2*i] != empty_symbol))) {
3026
3027                     /*FSHOW((stderr,
3028                            "* EQ key %d moved from %x to %x; index %d to %d\n",
3029                            i, old_key, new_key, old_index, new_index));*/
3030
3031                     if (index_vector[old_index] != 0) {
3032                         /*FSHOW((stderr, "/P1 %d\n", index_vector[old_index]));*/
3033
3034                         /* Unlink the key from the old_index chain. */
3035                         if (index_vector[old_index] == i) {
3036                             /*FSHOW((stderr, "/P2a %d\n", next_vector[i]));*/
3037                             index_vector[old_index] = next_vector[i];
3038                             /* Link it into the needing rehash chain. */
3039                             next_vector[i] = fixnum_value(hash_table[11]);
3040                             hash_table[11] = make_fixnum(i);
3041                             /*SHOW("P2");*/
3042                         } else {
3043                             unsigned prior = index_vector[old_index];
3044                             unsigned next = next_vector[prior];
3045
3046                             /*FSHOW((stderr, "/P3a %d %d\n", prior, next));*/
3047
3048                             while (next != 0) {
3049                                 /*FSHOW((stderr, "/P3b %d %d\n", prior, next));*/
3050                                 if (next == i) {
3051                                     /* Unlink it. */
3052                                     next_vector[prior] = next_vector[next];
3053                                     /* Link it into the needing rehash
3054                                      * chain. */
3055                                     next_vector[next] =
3056                                         fixnum_value(hash_table[11]);
3057                                     hash_table[11] = make_fixnum(next);
3058                                     /*SHOW("/P3");*/
3059                                     break;
3060                                 }
3061                                 prior = next;
3062                                 next = next_vector[next];
3063                             }
3064                         }
3065                     }
3066                 }
3067             }
3068         }
3069     }
3070     return (CEILING(kv_length + 2, 2));
3071 }
3072
3073 static lispobj
3074 trans_vector(lispobj object)
3075 {
3076     struct vector *vector;
3077     int length, nwords;
3078
3079     gc_assert(Pointerp(object));
3080
3081     vector = (struct vector *) PTR(object);
3082
3083     length = fixnum_value(vector->length);
3084     nwords = CEILING(length + 2, 2);
3085
3086     return copy_large_object(object, nwords);
3087 }
3088
3089 static int
3090 size_vector(lispobj *where)
3091 {
3092     struct vector *vector;
3093     int length, nwords;
3094
3095     vector = (struct vector *) where;
3096     length = fixnum_value(vector->length);
3097     nwords = CEILING(length + 2, 2);
3098
3099     return nwords;
3100 }
3101
3102
3103 static int
3104 scav_vector_bit(lispobj *where, lispobj object)
3105 {
3106     struct vector *vector;
3107     int length, nwords;
3108
3109     vector = (struct vector *) where;
3110     length = fixnum_value(vector->length);
3111     nwords = CEILING(NWORDS(length, 32) + 2, 2);
3112
3113     return nwords;
3114 }
3115
3116 static lispobj
3117 trans_vector_bit(lispobj object)
3118 {
3119     struct vector *vector;
3120     int length, nwords;
3121
3122     gc_assert(Pointerp(object));
3123
3124     vector = (struct vector *) PTR(object);
3125     length = fixnum_value(vector->length);
3126     nwords = CEILING(NWORDS(length, 32) + 2, 2);
3127
3128     return copy_large_unboxed_object(object, nwords);
3129 }
3130
3131 static int
3132 size_vector_bit(lispobj *where)
3133 {
3134     struct vector *vector;
3135     int length, nwords;
3136
3137     vector = (struct vector *) where;
3138     length = fixnum_value(vector->length);
3139     nwords = CEILING(NWORDS(length, 32) + 2, 2);
3140
3141     return nwords;
3142 }
3143
3144
3145 static int
3146 scav_vector_unsigned_byte_2(lispobj *where, lispobj object)
3147 {
3148     struct vector *vector;
3149     int length, nwords;
3150
3151     vector = (struct vector *) where;
3152     length = fixnum_value(vector->length);
3153     nwords = CEILING(NWORDS(length, 16) + 2, 2);
3154
3155     return nwords;
3156 }
3157
3158 static lispobj
3159 trans_vector_unsigned_byte_2(lispobj object)
3160 {
3161     struct vector *vector;
3162     int length, nwords;
3163
3164     gc_assert(Pointerp(object));
3165
3166     vector = (struct vector *) PTR(object);
3167     length = fixnum_value(vector->length);
3168     nwords = CEILING(NWORDS(length, 16) + 2, 2);
3169
3170     return copy_large_unboxed_object(object, nwords);
3171 }
3172
3173 static int
3174 size_vector_unsigned_byte_2(lispobj *where)
3175 {
3176     struct vector *vector;
3177     int length, nwords;
3178
3179     vector = (struct vector *) where;
3180     length = fixnum_value(vector->length);
3181     nwords = CEILING(NWORDS(length, 16) + 2, 2);
3182
3183     return nwords;
3184 }
3185
3186
3187 static int
3188 scav_vector_unsigned_byte_4(lispobj *where, lispobj object)
3189 {
3190     struct vector *vector;
3191     int length, nwords;
3192
3193     vector = (struct vector *) where;
3194     length = fixnum_value(vector->length);
3195     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3196
3197     return nwords;
3198 }
3199
3200 static lispobj
3201 trans_vector_unsigned_byte_4(lispobj object)
3202 {
3203     struct vector *vector;
3204     int length, nwords;
3205
3206     gc_assert(Pointerp(object));
3207
3208     vector = (struct vector *) PTR(object);
3209     length = fixnum_value(vector->length);
3210     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3211
3212     return copy_large_unboxed_object(object, nwords);
3213 }
3214
3215 static int
3216 size_vector_unsigned_byte_4(lispobj *where)
3217 {
3218     struct vector *vector;
3219     int length, nwords;
3220
3221     vector = (struct vector *) where;
3222     length = fixnum_value(vector->length);
3223     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3224
3225     return nwords;
3226 }
3227
3228 static int
3229 scav_vector_unsigned_byte_8(lispobj *where, lispobj object)
3230 {
3231     struct vector *vector;
3232     int length, nwords;
3233
3234     vector = (struct vector *) where;
3235     length = fixnum_value(vector->length);
3236     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3237
3238     return nwords;
3239 }
3240
3241 static lispobj
3242 trans_vector_unsigned_byte_8(lispobj object)
3243 {
3244     struct vector *vector;
3245     int length, nwords;
3246
3247     gc_assert(Pointerp(object));
3248
3249     vector = (struct vector *) PTR(object);
3250     length = fixnum_value(vector->length);
3251     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3252
3253     return copy_large_unboxed_object(object, nwords);
3254 }
3255
3256 static int
3257 size_vector_unsigned_byte_8(lispobj *where)
3258 {
3259     struct vector *vector;
3260     int length, nwords;
3261
3262     vector = (struct vector *) where;
3263     length = fixnum_value(vector->length);
3264     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3265
3266     return nwords;
3267 }
3268
3269
3270 static int
3271 scav_vector_unsigned_byte_16(lispobj *where, lispobj object)
3272 {
3273     struct vector *vector;
3274     int length, nwords;
3275
3276     vector = (struct vector *) where;
3277     length = fixnum_value(vector->length);
3278     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3279
3280     return nwords;
3281 }
3282
3283 static lispobj
3284 trans_vector_unsigned_byte_16(lispobj object)
3285 {
3286     struct vector *vector;
3287     int length, nwords;
3288
3289     gc_assert(Pointerp(object));
3290
3291     vector = (struct vector *) PTR(object);
3292     length = fixnum_value(vector->length);
3293     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3294
3295     return copy_large_unboxed_object(object, nwords);
3296 }
3297
3298 static int
3299 size_vector_unsigned_byte_16(lispobj *where)
3300 {
3301     struct vector *vector;
3302     int length, nwords;
3303
3304     vector = (struct vector *) where;
3305     length = fixnum_value(vector->length);
3306     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3307
3308     return nwords;
3309 }
3310
3311 static int
3312 scav_vector_unsigned_byte_32(lispobj *where, lispobj object)
3313 {
3314     struct vector *vector;
3315     int length, nwords;
3316
3317     vector = (struct vector *) where;
3318     length = fixnum_value(vector->length);
3319     nwords = CEILING(length + 2, 2);
3320
3321     return nwords;
3322 }
3323
3324 static lispobj
3325 trans_vector_unsigned_byte_32(lispobj object)
3326 {
3327     struct vector *vector;
3328     int length, nwords;
3329
3330     gc_assert(Pointerp(object));
3331
3332     vector = (struct vector *) PTR(object);
3333     length = fixnum_value(vector->length);
3334     nwords = CEILING(length + 2, 2);
3335
3336     return copy_large_unboxed_object(object, nwords);
3337 }
3338
3339 static int
3340 size_vector_unsigned_byte_32(lispobj *where)
3341 {
3342     struct vector *vector;
3343     int length, nwords;
3344
3345     vector = (struct vector *) where;
3346     length = fixnum_value(vector->length);
3347     nwords = CEILING(length + 2, 2);
3348
3349     return nwords;
3350 }
3351
3352 static int
3353 scav_vector_single_float(lispobj *where, lispobj object)
3354 {
3355     struct vector *vector;
3356     int length, nwords;
3357
3358     vector = (struct vector *) where;
3359     length = fixnum_value(vector->length);
3360     nwords = CEILING(length + 2, 2);
3361
3362     return nwords;
3363 }
3364
3365 static lispobj
3366 trans_vector_single_float(lispobj object)
3367 {
3368     struct vector *vector;
3369     int length, nwords;
3370
3371     gc_assert(Pointerp(object));
3372
3373     vector = (struct vector *) PTR(object);
3374     length = fixnum_value(vector->length);
3375     nwords = CEILING(length + 2, 2);
3376
3377     return copy_large_unboxed_object(object, nwords);
3378 }
3379
3380 static int
3381 size_vector_single_float(lispobj *where)
3382 {
3383     struct vector *vector;
3384     int length, nwords;
3385
3386     vector = (struct vector *) where;
3387     length = fixnum_value(vector->length);
3388     nwords = CEILING(length + 2, 2);
3389
3390     return nwords;
3391 }
3392
3393 static int
3394 scav_vector_double_float(lispobj *where, lispobj object)
3395 {
3396     struct vector *vector;
3397     int length, nwords;
3398
3399     vector = (struct vector *) where;
3400     length = fixnum_value(vector->length);
3401     nwords = CEILING(length * 2 + 2, 2);
3402
3403     return nwords;
3404 }
3405
3406 static lispobj
3407 trans_vector_double_float(lispobj object)
3408 {
3409     struct vector *vector;
3410     int length, nwords;
3411
3412     gc_assert(Pointerp(object));
3413
3414     vector = (struct vector *) PTR(object);
3415     length = fixnum_value(vector->length);
3416     nwords = CEILING(length * 2 + 2, 2);
3417
3418     return copy_large_unboxed_object(object, nwords);
3419 }
3420
3421 static int
3422 size_vector_double_float(lispobj *where)
3423 {
3424     struct vector *vector;
3425     int length, nwords;
3426
3427     vector = (struct vector *) where;
3428     length = fixnum_value(vector->length);
3429     nwords = CEILING(length * 2 + 2, 2);
3430
3431     return nwords;
3432 }
3433
3434 #ifdef type_SimpleArrayLongFloat
3435 static int
3436 scav_vector_long_float(lispobj *where, lispobj object)
3437 {
3438     struct vector *vector;
3439     int length, nwords;
3440
3441     vector = (struct vector *) where;
3442     length = fixnum_value(vector->length);
3443     nwords = CEILING(length * 3 + 2, 2);
3444
3445     return nwords;
3446 }
3447
3448 static lispobj
3449 trans_vector_long_float(lispobj object)
3450 {
3451     struct vector *vector;
3452     int length, nwords;
3453
3454     gc_assert(Pointerp(object));
3455
3456     vector = (struct vector *) PTR(object);
3457     length = fixnum_value(vector->length);
3458     nwords = CEILING(length * 3 + 2, 2);
3459
3460     return copy_large_unboxed_object(object, nwords);
3461 }
3462
3463 static int
3464 size_vector_long_float(lispobj *where)
3465 {
3466     struct vector *vector;
3467     int length, nwords;
3468
3469     vector = (struct vector *) where;
3470     length = fixnum_value(vector->length);
3471     nwords = CEILING(length * 3 + 2, 2);
3472
3473     return nwords;
3474 }
3475 #endif
3476
3477
3478 #ifdef type_SimpleArrayComplexSingleFloat
3479 static int
3480 scav_vector_complex_single_float(lispobj *where, lispobj object)
3481 {
3482     struct vector *vector;
3483     int length, nwords;
3484
3485     vector = (struct vector *) where;
3486     length = fixnum_value(vector->length);
3487     nwords = CEILING(length * 2 + 2, 2);
3488
3489     return nwords;
3490 }
3491
3492 static lispobj
3493 trans_vector_complex_single_float(lispobj object)
3494 {
3495     struct vector *vector;
3496     int length, nwords;
3497
3498     gc_assert(Pointerp(object));
3499
3500     vector = (struct vector *) PTR(object);
3501     length = fixnum_value(vector->length);
3502     nwords = CEILING(length * 2 + 2, 2);
3503
3504     return copy_large_unboxed_object(object, nwords);
3505 }
3506
3507 static int
3508 size_vector_complex_single_float(lispobj *where)
3509 {
3510     struct vector *vector;
3511     int length, nwords;
3512
3513     vector = (struct vector *) where;
3514     length = fixnum_value(vector->length);
3515     nwords = CEILING(length * 2 + 2, 2);
3516
3517     return nwords;
3518 }
3519 #endif
3520
3521 #ifdef type_SimpleArrayComplexDoubleFloat
3522 static int
3523 scav_vector_complex_double_float(lispobj *where, lispobj object)
3524 {
3525     struct vector *vector;
3526     int length, nwords;
3527
3528     vector = (struct vector *) where;
3529     length = fixnum_value(vector->length);
3530     nwords = CEILING(length * 4 + 2, 2);
3531
3532     return nwords;
3533 }
3534
3535 static lispobj
3536 trans_vector_complex_double_float(lispobj object)
3537 {
3538     struct vector *vector;
3539     int length, nwords;
3540
3541     gc_assert(Pointerp(object));
3542
3543     vector = (struct vector *) PTR(object);
3544     length = fixnum_value(vector->length);
3545     nwords = CEILING(length * 4 + 2, 2);
3546
3547     return copy_large_unboxed_object(object, nwords);
3548 }
3549
3550 static int
3551 size_vector_complex_double_float(lispobj *where)
3552 {
3553     struct vector *vector;
3554     int length, nwords;
3555
3556     vector = (struct vector *) where;
3557     length = fixnum_value(vector->length);
3558     nwords = CEILING(length * 4 + 2, 2);
3559
3560     return nwords;
3561 }
3562 #endif
3563
3564
3565 #ifdef type_SimpleArrayComplexLongFloat
3566 static int
3567 scav_vector_complex_long_float(lispobj *where, lispobj object)
3568 {
3569     struct vector *vector;
3570     int length, nwords;
3571
3572     vector = (struct vector *) where;
3573     length = fixnum_value(vector->length);
3574     nwords = CEILING(length * 6 + 2, 2);
3575
3576     return nwords;
3577 }
3578
3579 static lispobj
3580 trans_vector_complex_long_float(lispobj object)
3581 {
3582     struct vector *vector;
3583     int length, nwords;
3584
3585     gc_assert(Pointerp(object));
3586
3587     vector = (struct vector *) PTR(object);
3588     length = fixnum_value(vector->length);
3589     nwords = CEILING(length * 6 + 2, 2);
3590
3591     return copy_large_unboxed_object(object, nwords);
3592 }
3593
3594 static int
3595 size_vector_complex_long_float(lispobj *where)
3596 {
3597     struct vector *vector;
3598     int length, nwords;
3599
3600     vector = (struct vector *) where;
3601     length = fixnum_value(vector->length);
3602     nwords = CEILING(length * 6 + 2, 2);
3603
3604     return nwords;
3605 }
3606 #endif
3607
3608 \f
3609 /*
3610  * weak pointers
3611  */
3612
3613 /* XX This is a hack adapted from cgc.c. These don't work too well with the
3614  * gencgc as a list of the weak pointers is maintained within the
3615  * objects which causes writes to the pages. A limited attempt is made
3616  * to avoid unnecessary writes, but this needs a re-think. */
3617
3618 #define WEAK_POINTER_NWORDS \
3619     CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
3620
3621 static int
3622 scav_weak_pointer(lispobj *where, lispobj object)
3623 {
3624     struct weak_pointer *wp = weak_pointers;
3625     /* Push the weak pointer onto the list of weak pointers.
3626      * Do I have to watch for duplicates? Originally this was
3627      * part of trans_weak_pointer but that didn't work in the
3628      * case where the WP was in a promoted region.
3629      */
3630
3631     /* Check whether it's already in the list. */
3632     while (wp != NULL) {
3633         if (wp == (struct weak_pointer*)where) {
3634             break;
3635         }
3636         wp = wp->next;
3637     }
3638     if (wp == NULL) {
3639         /* Add it to the start of the list. */
3640         wp = (struct weak_pointer*)where;
3641         if (wp->next != weak_pointers) {
3642             wp->next = weak_pointers;
3643         } else {
3644             /*SHOW("avoided write to weak pointer");*/
3645         }
3646         weak_pointers = wp;
3647     }
3648
3649     /* Do not let GC scavenge the value slot of the weak pointer.
3650      * (That is why it is a weak pointer.) */
3651
3652     return WEAK_POINTER_NWORDS;
3653 }
3654
3655 static lispobj
3656 trans_weak_pointer(lispobj object)
3657 {
3658     lispobj copy;
3659     /* struct weak_pointer *wp; */
3660
3661     gc_assert(Pointerp(object));
3662
3663 #if defined(DEBUG_WEAK)
3664     FSHOW((stderr, "Transporting weak pointer from 0x%08x\n", object));
3665 #endif
3666
3667     /* Need to remember where all the weak pointers are that have */
3668     /* been transported so they can be fixed up in a post-GC pass. */
3669
3670     copy = copy_object(object, WEAK_POINTER_NWORDS);
3671     /*  wp = (struct weak_pointer *) PTR(copy);*/
3672         
3673
3674     /* Push the weak pointer onto the list of weak pointers. */
3675     /*  wp->next = weak_pointers;
3676      *  weak_pointers = wp;*/
3677
3678     return copy;
3679 }
3680
3681 static int
3682 size_weak_pointer(lispobj *where)
3683 {
3684     return WEAK_POINTER_NWORDS;
3685 }
3686
3687 void scan_weak_pointers(void)
3688 {
3689     struct weak_pointer *wp;
3690     for (wp = weak_pointers; wp != NULL; wp = wp->next) {
3691         lispobj value = wp->value;
3692         lispobj *first_pointer;
3693
3694         first_pointer = (lispobj *)PTR(value);
3695
3696         /*
3697         FSHOW((stderr, "/weak pointer at 0x%08x\n", (unsigned long) wp));
3698         FSHOW((stderr, "/value: 0x%08x\n", (unsigned long) value));
3699         */
3700
3701         if (Pointerp(value) && from_space_p(value)) {
3702             /* Now, we need to check whether the object has been forwarded. If
3703              * it has been, the weak pointer is still good and needs to be
3704              * updated. Otherwise, the weak pointer needs to be nil'ed
3705              * out. */
3706             if (first_pointer[0] == 0x01) {
3707                 wp->value = first_pointer[1];
3708             } else {
3709                 /* Break it. */
3710                 SHOW("broken");
3711                 wp->value = NIL;
3712                 wp->broken = T;
3713             }
3714         }
3715     }
3716 }
3717 \f
3718 /*
3719  * initialization
3720  */
3721
3722 static int
3723 scav_lose(lispobj *where, lispobj object)
3724 {
3725     lose("no scavenge function for object 0x%08x", (unsigned long) object);
3726     return 0; /* bogus return value to satisfy static type checking */
3727 }
3728
3729 static lispobj
3730 trans_lose(lispobj object)
3731 {
3732     lose("no transport function for object 0x%08x", (unsigned long) object);
3733     return NIL; /* bogus return value to satisfy static type checking */
3734 }
3735
3736 static int
3737 size_lose(lispobj *where)
3738 {
3739     lose("no size function for object at 0x%08x", (unsigned long) where);
3740     return 1; /* bogus return value to satisfy static type checking */
3741 }
3742
3743 static void
3744 gc_init_tables(void)
3745 {
3746     int i;
3747
3748     /* Set default value in all slots of scavenge table. */
3749     for (i = 0; i < 256; i++) { /* FIXME: bare constant length, ick! */
3750         scavtab[i] = scav_lose;
3751     }
3752
3753     /* For each type which can be selected by the low 3 bits of the tag
3754      * alone, set multiple entries in our 8-bit scavenge table (one for each
3755      * possible value of the high 5 bits). */
3756     for (i = 0; i < 32; i++) { /* FIXME: bare constant length, ick! */
3757         scavtab[type_EvenFixnum|(i<<3)] = scav_immediate;
3758         scavtab[type_FunctionPointer|(i<<3)] = scav_function_pointer;
3759         /* OtherImmediate0 */
3760         scavtab[type_ListPointer|(i<<3)] = scav_list_pointer;
3761         scavtab[type_OddFixnum|(i<<3)] = scav_immediate;
3762         scavtab[type_InstancePointer|(i<<3)] = scav_instance_pointer;
3763         /* OtherImmediate1 */
3764         scavtab[type_OtherPointer|(i<<3)] = scav_other_pointer;
3765     }
3766
3767     /* Other-pointer types (those selected by all eight bits of the tag) get
3768      * one entry each in the scavenge table. */
3769     scavtab[type_Bignum] = scav_unboxed;
3770     scavtab[type_Ratio] = scav_boxed;
3771     scavtab[type_SingleFloat] = scav_unboxed;
3772     scavtab[type_DoubleFloat] = scav_unboxed;
3773 #ifdef type_LongFloat
3774     scavtab[type_LongFloat] = scav_unboxed;
3775 #endif
3776     scavtab[type_Complex] = scav_boxed;
3777 #ifdef type_ComplexSingleFloat
3778     scavtab[type_ComplexSingleFloat] = scav_unboxed;
3779 #endif
3780 #ifdef type_ComplexDoubleFloat
3781     scavtab[type_ComplexDoubleFloat] = scav_unboxed;
3782 #endif
3783 #ifdef type_ComplexLongFloat
3784     scavtab[type_ComplexLongFloat] = scav_unboxed;
3785 #endif
3786     scavtab[type_SimpleArray] = scav_boxed;
3787     scavtab[type_SimpleString] = scav_string;
3788     scavtab[type_SimpleBitVector] = scav_vector_bit;
3789     scavtab[type_SimpleVector] = scav_vector;
3790     scavtab[type_SimpleArrayUnsignedByte2] = scav_vector_unsigned_byte_2;
3791     scavtab[type_SimpleArrayUnsignedByte4] = scav_vector_unsigned_byte_4;
3792     scavtab[type_SimpleArrayUnsignedByte8] = scav_vector_unsigned_byte_8;
3793     scavtab[type_SimpleArrayUnsignedByte16] = scav_vector_unsigned_byte_16;
3794     scavtab[type_SimpleArrayUnsignedByte32] = scav_vector_unsigned_byte_32;
3795 #ifdef type_SimpleArraySignedByte8
3796     scavtab[type_SimpleArraySignedByte8] = scav_vector_unsigned_byte_8;
3797 #endif
3798 #ifdef type_SimpleArraySignedByte16
3799     scavtab[type_SimpleArraySignedByte16] = scav_vector_unsigned_byte_16;
3800 #endif
3801 #ifdef type_SimpleArraySignedByte30
3802     scavtab[type_SimpleArraySignedByte30] = scav_vector_unsigned_byte_32;
3803 #endif
3804 #ifdef type_SimpleArraySignedByte32
3805     scavtab[type_SimpleArraySignedByte32] = scav_vector_unsigned_byte_32;
3806 #endif
3807     scavtab[type_SimpleArraySingleFloat] = scav_vector_single_float;
3808     scavtab[type_SimpleArrayDoubleFloat] = scav_vector_double_float;
3809 #ifdef type_SimpleArrayLongFloat
3810     scavtab[type_SimpleArrayLongFloat] = scav_vector_long_float;
3811 #endif
3812 #ifdef type_SimpleArrayComplexSingleFloat
3813     scavtab[type_SimpleArrayComplexSingleFloat] = scav_vector_complex_single_float;
3814 #endif
3815 #ifdef type_SimpleArrayComplexDoubleFloat
3816     scavtab[type_SimpleArrayComplexDoubleFloat] = scav_vector_complex_double_float;
3817 #endif
3818 #ifdef type_SimpleArrayComplexLongFloat
3819     scavtab[type_SimpleArrayComplexLongFloat] = scav_vector_complex_long_float;
3820 #endif
3821     scavtab[type_ComplexString] = scav_boxed;
3822     scavtab[type_ComplexBitVector] = scav_boxed;
3823     scavtab[type_ComplexVector] = scav_boxed;
3824     scavtab[type_ComplexArray] = scav_boxed;
3825     scavtab[type_CodeHeader] = scav_code_header;
3826     /*scavtab[type_FunctionHeader] = scav_function_header;*/
3827     /*scavtab[type_ClosureFunctionHeader] = scav_function_header;*/
3828     /*scavtab[type_ReturnPcHeader] = scav_return_pc_header;*/
3829 #ifdef __i386__
3830     scavtab[type_ClosureHeader] = scav_closure_header;
3831     scavtab[type_FuncallableInstanceHeader] = scav_closure_header;
3832     scavtab[type_ByteCodeFunction] = scav_closure_header;
3833     scavtab[type_ByteCodeClosure] = scav_closure_header;
3834 #else
3835     scavtab[type_ClosureHeader] = scav_boxed;
3836     scavtab[type_FuncallableInstanceHeader] = scav_boxed;
3837     scavtab[type_ByteCodeFunction] = scav_boxed;
3838     scavtab[type_ByteCodeClosure] = scav_boxed;
3839 #endif
3840     scavtab[type_ValueCellHeader] = scav_boxed;
3841     scavtab[type_SymbolHeader] = scav_boxed;
3842     scavtab[type_BaseChar] = scav_immediate;
3843     scavtab[type_Sap] = scav_unboxed;
3844     scavtab[type_UnboundMarker] = scav_immediate;
3845     scavtab[type_WeakPointer] = scav_weak_pointer;
3846     scavtab[type_InstanceHeader] = scav_boxed;
3847     scavtab[type_Fdefn] = scav_fdefn;
3848
3849     /* transport other table, initialized same way as scavtab */
3850     for (i = 0; i < 256; i++)
3851         transother[i] = trans_lose;
3852     transother[type_Bignum] = trans_unboxed;
3853     transother[type_Ratio] = trans_boxed;
3854     transother[type_SingleFloat] = trans_unboxed;
3855     transother[type_DoubleFloat] = trans_unboxed;
3856 #ifdef type_LongFloat
3857     transother[type_LongFloat] = trans_unboxed;
3858 #endif
3859     transother[type_Complex] = trans_boxed;
3860 #ifdef type_ComplexSingleFloat
3861     transother[type_ComplexSingleFloat] = trans_unboxed;
3862 #endif
3863 #ifdef type_ComplexDoubleFloat
3864     transother[type_ComplexDoubleFloat] = trans_unboxed;
3865 #endif
3866 #ifdef type_ComplexLongFloat
3867     transother[type_ComplexLongFloat] = trans_unboxed;
3868 #endif
3869     transother[type_SimpleArray] = trans_boxed_large;
3870     transother[type_SimpleString] = trans_string;
3871     transother[type_SimpleBitVector] = trans_vector_bit;
3872     transother[type_SimpleVector] = trans_vector;
3873     transother[type_SimpleArrayUnsignedByte2] = trans_vector_unsigned_byte_2;
3874     transother[type_SimpleArrayUnsignedByte4] = trans_vector_unsigned_byte_4;
3875     transother[type_SimpleArrayUnsignedByte8] = trans_vector_unsigned_byte_8;
3876     transother[type_SimpleArrayUnsignedByte16] = trans_vector_unsigned_byte_16;
3877     transother[type_SimpleArrayUnsignedByte32] = trans_vector_unsigned_byte_32;
3878 #ifdef type_SimpleArraySignedByte8
3879     transother[type_SimpleArraySignedByte8] = trans_vector_unsigned_byte_8;
3880 #endif
3881 #ifdef type_SimpleArraySignedByte16
3882     transother[type_SimpleArraySignedByte16] = trans_vector_unsigned_byte_16;
3883 #endif
3884 #ifdef type_SimpleArraySignedByte30
3885     transother[type_SimpleArraySignedByte30] = trans_vector_unsigned_byte_32;
3886 #endif
3887 #ifdef type_SimpleArraySignedByte32
3888     transother[type_SimpleArraySignedByte32] = trans_vector_unsigned_byte_32;
3889 #endif
3890     transother[type_SimpleArraySingleFloat] = trans_vector_single_float;
3891     transother[type_SimpleArrayDoubleFloat] = trans_vector_double_float;
3892 #ifdef type_SimpleArrayLongFloat
3893     transother[type_SimpleArrayLongFloat] = trans_vector_long_float;
3894 #endif
3895 #ifdef type_SimpleArrayComplexSingleFloat
3896     transother[type_SimpleArrayComplexSingleFloat] = trans_vector_complex_single_float;
3897 #endif
3898 #ifdef type_SimpleArrayComplexDoubleFloat
3899     transother[type_SimpleArrayComplexDoubleFloat] = trans_vector_complex_double_float;
3900 #endif
3901 #ifdef type_SimpleArrayComplexLongFloat
3902     transother[type_SimpleArrayComplexLongFloat] = trans_vector_complex_long_float;
3903 #endif
3904     transother[type_ComplexString] = trans_boxed;
3905     transother[type_ComplexBitVector] = trans_boxed;
3906     transother[type_ComplexVector] = trans_boxed;
3907     transother[type_ComplexArray] = trans_boxed;
3908     transother[type_CodeHeader] = trans_code_header;
3909     transother[type_FunctionHeader] = trans_function_header;
3910     transother[type_ClosureFunctionHeader] = trans_function_header;
3911     transother[type_ReturnPcHeader] = trans_return_pc_header;
3912     transother[type_ClosureHeader] = trans_boxed;
3913     transother[type_FuncallableInstanceHeader] = trans_boxed;
3914     transother[type_ByteCodeFunction] = trans_boxed;
3915     transother[type_ByteCodeClosure] = trans_boxed;
3916     transother[type_ValueCellHeader] = trans_boxed;
3917     transother[type_SymbolHeader] = trans_boxed;
3918     transother[type_BaseChar] = trans_immediate;
3919     transother[type_Sap] = trans_unboxed;
3920     transother[type_UnboundMarker] = trans_immediate;
3921     transother[type_WeakPointer] = trans_weak_pointer;
3922     transother[type_InstanceHeader] = trans_boxed;
3923     transother[type_Fdefn] = trans_boxed;
3924
3925     /* size table, initialized the same way as scavtab */
3926     for (i = 0; i < 256; i++)
3927         sizetab[i] = size_lose;
3928     for (i = 0; i < 32; i++) {
3929         sizetab[type_EvenFixnum|(i<<3)] = size_immediate;
3930         sizetab[type_FunctionPointer|(i<<3)] = size_pointer;
3931         /* OtherImmediate0 */
3932         sizetab[type_ListPointer|(i<<3)] = size_pointer;
3933         sizetab[type_OddFixnum|(i<<3)] = size_immediate;
3934         sizetab[type_InstancePointer|(i<<3)] = size_pointer;
3935         /* OtherImmediate1 */
3936         sizetab[type_OtherPointer|(i<<3)] = size_pointer;
3937     }
3938     sizetab[type_Bignum] = size_unboxed;
3939     sizetab[type_Ratio] = size_boxed;
3940     sizetab[type_SingleFloat] = size_unboxed;
3941     sizetab[type_DoubleFloat] = size_unboxed;
3942 #ifdef type_LongFloat
3943     sizetab[type_LongFloat] = size_unboxed;
3944 #endif
3945     sizetab[type_Complex] = size_boxed;
3946 #ifdef type_ComplexSingleFloat
3947     sizetab[type_ComplexSingleFloat] = size_unboxed;
3948 #endif
3949 #ifdef type_ComplexDoubleFloat
3950     sizetab[type_ComplexDoubleFloat] = size_unboxed;
3951 #endif
3952 #ifdef type_ComplexLongFloat
3953     sizetab[type_ComplexLongFloat] = size_unboxed;
3954 #endif
3955     sizetab[type_SimpleArray] = size_boxed;
3956     sizetab[type_SimpleString] = size_string;
3957     sizetab[type_SimpleBitVector] = size_vector_bit;
3958     sizetab[type_SimpleVector] = size_vector;
3959     sizetab[type_SimpleArrayUnsignedByte2] = size_vector_unsigned_byte_2;
3960     sizetab[type_SimpleArrayUnsignedByte4] = size_vector_unsigned_byte_4;
3961     sizetab[type_SimpleArrayUnsignedByte8] = size_vector_unsigned_byte_8;
3962     sizetab[type_SimpleArrayUnsignedByte16] = size_vector_unsigned_byte_16;
3963     sizetab[type_SimpleArrayUnsignedByte32] = size_vector_unsigned_byte_32;
3964 #ifdef type_SimpleArraySignedByte8
3965     sizetab[type_SimpleArraySignedByte8] = size_vector_unsigned_byte_8;
3966 #endif
3967 #ifdef type_SimpleArraySignedByte16
3968     sizetab[type_SimpleArraySignedByte16] = size_vector_unsigned_byte_16;
3969 #endif
3970 #ifdef type_SimpleArraySignedByte30
3971     sizetab[type_SimpleArraySignedByte30] = size_vector_unsigned_byte_32;
3972 #endif
3973 #ifdef type_SimpleArraySignedByte32
3974     sizetab[type_SimpleArraySignedByte32] = size_vector_unsigned_byte_32;
3975 #endif
3976     sizetab[type_SimpleArraySingleFloat] = size_vector_single_float;
3977     sizetab[type_SimpleArrayDoubleFloat] = size_vector_double_float;
3978 #ifdef type_SimpleArrayLongFloat
3979     sizetab[type_SimpleArrayLongFloat] = size_vector_long_float;
3980 #endif
3981 #ifdef type_SimpleArrayComplexSingleFloat
3982     sizetab[type_SimpleArrayComplexSingleFloat] = size_vector_complex_single_float;
3983 #endif
3984 #ifdef type_SimpleArrayComplexDoubleFloat
3985     sizetab[type_SimpleArrayComplexDoubleFloat] = size_vector_complex_double_float;
3986 #endif
3987 #ifdef type_SimpleArrayComplexLongFloat
3988     sizetab[type_SimpleArrayComplexLongFloat] = size_vector_complex_long_float;
3989 #endif
3990     sizetab[type_ComplexString] = size_boxed;
3991     sizetab[type_ComplexBitVector] = size_boxed;
3992     sizetab[type_ComplexVector] = size_boxed;
3993     sizetab[type_ComplexArray] = size_boxed;
3994     sizetab[type_CodeHeader] = size_code_header;
3995 #if 0
3996     /* We shouldn't see these, so just lose if it happens. */
3997     sizetab[type_FunctionHeader] = size_function_header;
3998     sizetab[type_ClosureFunctionHeader] = size_function_header;
3999     sizetab[type_ReturnPcHeader] = size_return_pc_header;
4000 #endif
4001     sizetab[type_ClosureHeader] = size_boxed;
4002     sizetab[type_FuncallableInstanceHeader] = size_boxed;
4003     sizetab[type_ValueCellHeader] = size_boxed;
4004     sizetab[type_SymbolHeader] = size_boxed;
4005     sizetab[type_BaseChar] = size_immediate;
4006     sizetab[type_Sap] = size_unboxed;
4007     sizetab[type_UnboundMarker] = size_immediate;
4008     sizetab[type_WeakPointer] = size_weak_pointer;
4009     sizetab[type_InstanceHeader] = size_boxed;
4010     sizetab[type_Fdefn] = size_boxed;
4011 }
4012 \f
4013 /* Scan an area looking for an object which encloses the given pointer.
4014  * Return the object start on success or NULL on failure. */
4015 static lispobj *
4016 search_space(lispobj *start, size_t words, lispobj *pointer)
4017 {
4018     while (words > 0) {
4019         size_t count = 1;
4020         lispobj thing = *start;
4021
4022         /* If thing is an immediate then this is a cons */
4023         if (Pointerp(thing)
4024             || ((thing & 3) == 0) /* fixnum */
4025             || (TypeOf(thing) == type_BaseChar)
4026             || (TypeOf(thing) == type_UnboundMarker))
4027             count = 2;
4028         else
4029             count = (sizetab[TypeOf(thing)])(start);
4030
4031         /* Check whether the pointer is within this object? */
4032         if ((pointer >= start) && (pointer < (start+count))) {
4033             /* found it! */
4034             /*FSHOW((stderr,"/found %x in %x %x\n", pointer, start, thing));*/
4035             return(start);
4036         }
4037
4038         /* Round up the count */
4039         count = CEILING(count,2);
4040
4041         start += count;
4042         words -= count;
4043     }
4044     return (NULL);
4045 }
4046
4047 static lispobj*
4048 search_read_only_space(lispobj *pointer)
4049 {
4050     lispobj* start = (lispobj*)READ_ONLY_SPACE_START;
4051     lispobj* end = (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER);
4052     if ((pointer < start) || (pointer >= end))
4053         return NULL;
4054     return (search_space(start, (pointer+2)-start, pointer));
4055 }
4056
4057 static lispobj *
4058 search_static_space(lispobj *pointer)
4059 {
4060     lispobj* start = (lispobj*)STATIC_SPACE_START;
4061     lispobj* end = (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER);
4062     if ((pointer < start) || (pointer >= end))
4063         return NULL;
4064     return (search_space(start, (pointer+2)-start, pointer));
4065 }
4066
4067 /* a faster version for searching the dynamic space. This will work even
4068  * if the object is in a current allocation region. */
4069 lispobj *
4070 search_dynamic_space(lispobj *pointer)
4071 {
4072     int  page_index = find_page_index(pointer);
4073     lispobj *start;
4074
4075     /* Address may be invalid - do some checks. */
4076     if ((page_index == -1) || (page_table[page_index].allocated == FREE_PAGE))
4077         return NULL;
4078     start = (lispobj *)((void *)page_address(page_index)
4079                         + page_table[page_index].first_object_offset);
4080     return (search_space(start, (pointer+2)-start, pointer));
4081 }
4082
4083 /* FIXME: There is a strong family resemblance between this function
4084  * and the function of the same name in purify.c. Would it be possible
4085  * to implement them as exactly the same function? */
4086 static int
4087 valid_dynamic_space_pointer(lispobj *pointer)
4088 {
4089     lispobj *start_addr;
4090
4091     /* Find the object start address */
4092     if ((start_addr = search_dynamic_space(pointer)) == NULL) {
4093         return 0;
4094     }
4095
4096     /* We need to allow raw pointers into Code objects for return
4097      * addresses. This will also pickup pointers to functions in code
4098      * objects. */
4099     if (TypeOf(*start_addr) == type_CodeHeader) {
4100         /* X Could do some further checks here. */
4101         return 1;
4102     }
4103
4104     /* If it's not a return address then it needs to be a valid Lisp
4105      * pointer. */
4106     if (!Pointerp((lispobj)pointer)) {
4107         return 0;
4108     }
4109
4110     /* Check that the object pointed to is consistent with the pointer
4111      * low tag. */
4112     switch (LowtagOf((lispobj)pointer)) {
4113     case type_FunctionPointer:
4114         /* Start_addr should be the enclosing code object, or a closure
4115            header. */
4116         switch (TypeOf(*start_addr)) {
4117         case type_CodeHeader:
4118             /* This case is probably caught above. */
4119             break;
4120         case type_ClosureHeader:
4121         case type_FuncallableInstanceHeader:
4122         case type_ByteCodeFunction:
4123         case type_ByteCodeClosure:
4124             if ((unsigned)pointer !=
4125                 ((unsigned)start_addr+type_FunctionPointer)) {
4126                 if (gencgc_verbose)
4127                     FSHOW((stderr,
4128                            "/Wf2: %x %x %x\n",
4129                            pointer, start_addr, *start_addr));
4130                 return 0;
4131             }
4132             break;
4133         default:
4134             if (gencgc_verbose)
4135                 FSHOW((stderr,
4136                        "/Wf3: %x %x %x\n",
4137                        pointer, start_addr, *start_addr));
4138             return 0;
4139         }
4140         break;
4141     case type_ListPointer:
4142         if ((unsigned)pointer !=
4143             ((unsigned)start_addr+type_ListPointer)) {
4144             if (gencgc_verbose)
4145                 FSHOW((stderr,
4146                        "/Wl1: %x %x %x\n",
4147                        pointer, start_addr, *start_addr));
4148             return 0;
4149         }
4150         /* Is it plausible cons? */
4151         if ((Pointerp(start_addr[0])
4152             || ((start_addr[0] & 3) == 0) /* fixnum */
4153             || (TypeOf(start_addr[0]) == type_BaseChar)
4154             || (TypeOf(start_addr[0]) == type_UnboundMarker))
4155            && (Pointerp(start_addr[1])
4156                || ((start_addr[1] & 3) == 0) /* fixnum */
4157                || (TypeOf(start_addr[1]) == type_BaseChar)
4158                || (TypeOf(start_addr[1]) == type_UnboundMarker)))
4159             break;
4160         else {
4161             if (gencgc_verbose)
4162                 FSHOW((stderr,
4163                        "/Wl2: %x %x %x\n",
4164                        pointer, start_addr, *start_addr));
4165             return 0;
4166         }
4167     case type_InstancePointer:
4168         if ((unsigned)pointer !=
4169             ((unsigned)start_addr+type_InstancePointer)) {
4170             if (gencgc_verbose)
4171                 FSHOW((stderr,
4172                        "/Wi1: %x %x %x\n",
4173                        pointer, start_addr, *start_addr));
4174             return 0;
4175         }
4176         if (TypeOf(start_addr[0]) != type_InstanceHeader) {
4177             if (gencgc_verbose)
4178                 FSHOW((stderr,
4179                        "/Wi2: %x %x %x\n",
4180                        pointer, start_addr, *start_addr));
4181             return 0;
4182         }
4183         break;
4184     case type_OtherPointer:
4185         if ((unsigned)pointer !=
4186             ((int)start_addr+type_OtherPointer)) {
4187             if (gencgc_verbose)
4188                 FSHOW((stderr,
4189                        "/Wo1: %x %x %x\n",
4190                        pointer, start_addr, *start_addr));
4191             return 0;
4192         }
4193         /* Is it plausible?  Not a cons. X should check the headers. */
4194         if (Pointerp(start_addr[0]) || ((start_addr[0] & 3) == 0)) {
4195             if (gencgc_verbose)
4196                 FSHOW((stderr,
4197                        "/Wo2: %x %x %x\n",
4198                        pointer, start_addr, *start_addr));
4199             return 0;
4200         }
4201         switch (TypeOf(start_addr[0])) {
4202         case type_UnboundMarker:
4203         case type_BaseChar:
4204             if (gencgc_verbose)
4205                 FSHOW((stderr,
4206                        "*Wo3: %x %x %x\n",
4207                        pointer, start_addr, *start_addr));
4208             return 0;
4209
4210             /* only pointed to by function pointers? */
4211         case type_ClosureHeader:
4212         case type_FuncallableInstanceHeader:
4213         case type_ByteCodeFunction:
4214         case type_ByteCodeClosure:
4215             if (gencgc_verbose)
4216                 FSHOW((stderr,
4217                        "*Wo4: %x %x %x\n",
4218                        pointer, start_addr, *start_addr));
4219             return 0;
4220
4221         case type_InstanceHeader:
4222             if (gencgc_verbose)
4223                 FSHOW((stderr,
4224                        "*Wo5: %x %x %x\n",
4225                        pointer, start_addr, *start_addr));
4226             return 0;
4227
4228             /* the valid other immediate pointer objects */
4229         case type_SimpleVector:
4230         case type_Ratio:
4231         case type_Complex:
4232 #ifdef type_ComplexSingleFloat
4233         case type_ComplexSingleFloat:
4234 #endif
4235 #ifdef type_ComplexDoubleFloat
4236         case type_ComplexDoubleFloat:
4237 #endif
4238 #ifdef type_ComplexLongFloat
4239         case type_ComplexLongFloat:
4240 #endif
4241         case type_SimpleArray:
4242         case type_ComplexString:
4243         case type_ComplexBitVector:
4244         case type_ComplexVector:
4245         case type_ComplexArray:
4246         case type_ValueCellHeader:
4247         case type_SymbolHeader:
4248         case type_Fdefn:
4249         case type_CodeHeader:
4250         case type_Bignum:
4251         case type_SingleFloat:
4252         case type_DoubleFloat:
4253 #ifdef type_LongFloat
4254         case type_LongFloat:
4255 #endif
4256         case type_SimpleString:
4257         case type_SimpleBitVector:
4258         case type_SimpleArrayUnsignedByte2:
4259         case type_SimpleArrayUnsignedByte4:
4260         case type_SimpleArrayUnsignedByte8:
4261         case type_SimpleArrayUnsignedByte16:
4262         case type_SimpleArrayUnsignedByte32:
4263 #ifdef type_SimpleArraySignedByte8
4264         case type_SimpleArraySignedByte8:
4265 #endif
4266 #ifdef type_SimpleArraySignedByte16
4267         case type_SimpleArraySignedByte16:
4268 #endif
4269 #ifdef type_SimpleArraySignedByte30
4270         case type_SimpleArraySignedByte30:
4271 #endif
4272 #ifdef type_SimpleArraySignedByte32
4273         case type_SimpleArraySignedByte32:
4274 #endif
4275         case type_SimpleArraySingleFloat:
4276         case type_SimpleArrayDoubleFloat:
4277 #ifdef type_SimpleArrayLongFloat
4278         case type_SimpleArrayLongFloat:
4279 #endif
4280 #ifdef type_SimpleArrayComplexSingleFloat
4281         case type_SimpleArrayComplexSingleFloat:
4282 #endif
4283 #ifdef type_SimpleArrayComplexDoubleFloat
4284         case type_SimpleArrayComplexDoubleFloat:
4285 #endif
4286 #ifdef type_SimpleArrayComplexLongFloat
4287         case type_SimpleArrayComplexLongFloat:
4288 #endif
4289         case type_Sap:
4290         case type_WeakPointer:
4291             break;
4292
4293         default:
4294             if (gencgc_verbose)
4295                 FSHOW((stderr,
4296                        "/Wo6: %x %x %x\n",
4297                        pointer, start_addr, *start_addr));
4298             return 0;
4299         }
4300         break;
4301     default:
4302         if (gencgc_verbose)
4303             FSHOW((stderr,
4304                    "*W?: %x %x %x\n",
4305                    pointer, start_addr, *start_addr));
4306         return 0;
4307     }
4308
4309     /* looks good */
4310     return 1;
4311 }
4312
4313 /* Adjust large bignum and vector objects. This will adjust the allocated
4314  * region if the size has shrunk, and move unboxed objects into unboxed
4315  * pages. The pages are not promoted here, and the promoted region is not
4316  * added to the new_regions; this is really only designed to be called from
4317  * preserve_pointer. Shouldn't fail if this is missed, just may delay the
4318  * moving of objects to unboxed pages, and the freeing of pages. */
4319 static void
4320 maybe_adjust_large_object(lispobj *where)
4321 {
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
4983     /* the new_areas created but the previous scavenge cycle */
4984     struct new_area  (*previous_new_areas)[] = NULL;
4985     int previous_new_areas_index;
4986
4987 #define SC_NS_GEN_CK 0
4988 #if SC_NS_GEN_CK
4989     /* Clear the write_protected_cleared flags on all pages. */
4990     for (i = 0; i < NUM_PAGES; i++)
4991         page_table[i].write_protected_cleared = 0;
4992 #endif
4993
4994     /* Flush the current regions updating the tables. */
4995     gc_alloc_update_page_tables(0, &boxed_region);
4996     gc_alloc_update_page_tables(1, &unboxed_region);
4997
4998     /* Turn on the recording of new areas by gc_alloc. */
4999     new_areas = current_new_areas;
5000     new_areas_index = 0;
5001
5002     /* Don't need to record new areas that get scavenged anyway during
5003      * scavenge_newspace_generation_one_scan. */
5004     record_new_objects = 1;
5005
5006     /* Start with a full scavenge. */
5007     scavenge_newspace_generation_one_scan(generation);
5008
5009     /* Record all new areas now. */
5010     record_new_objects = 2;
5011
5012     /* Flush the current regions updating the tables. */
5013     gc_alloc_update_page_tables(0, &boxed_region);
5014     gc_alloc_update_page_tables(1, &unboxed_region);
5015
5016     /* Grab new_areas_index. */
5017     current_new_areas_index = new_areas_index;
5018
5019     /*FSHOW((stderr,
5020              "The first scan is finished; current_new_areas_index=%d.\n",
5021              current_new_areas_index));*/
5022
5023     while (current_new_areas_index > 0) {
5024         /* Move the current to the previous new areas */
5025         previous_new_areas = current_new_areas;
5026         previous_new_areas_index = current_new_areas_index;
5027
5028         /* Scavenge all the areas in previous new areas. Any new areas
5029          * allocated are saved in current_new_areas. */
5030
5031         /* Allocate an array for current_new_areas; alternating between
5032          * new_areas_1 and 2 */
5033         if (previous_new_areas == &new_areas_1)
5034             current_new_areas = &new_areas_2;
5035         else
5036             current_new_areas = &new_areas_1;
5037
5038         /* Set up for gc_alloc. */
5039         new_areas = current_new_areas;
5040         new_areas_index = 0;
5041
5042         /* Check whether previous_new_areas had overflowed. */
5043         if (previous_new_areas_index >= NUM_NEW_AREAS) {
5044             /* New areas of objects allocated have been lost so need to do a
5045              * full scan to be sure! If this becomes a problem try
5046              * increasing NUM_NEW_AREAS. */
5047             if (gencgc_verbose)
5048                 SHOW("new_areas overflow, doing full scavenge");
5049
5050             /* Don't need to record new areas that get scavenge anyway
5051              * during scavenge_newspace_generation_one_scan. */
5052             record_new_objects = 1;
5053
5054             scavenge_newspace_generation_one_scan(generation);
5055
5056             /* Record all new areas now. */
5057             record_new_objects = 2;
5058
5059             /* Flush the current regions updating the tables. */
5060             gc_alloc_update_page_tables(0, &boxed_region);
5061             gc_alloc_update_page_tables(1, &unboxed_region);
5062         } else {
5063             /* Work through previous_new_areas. */
5064             for (i = 0; i < previous_new_areas_index; i++) {
5065                 int page = (*previous_new_areas)[i].page;
5066                 int offset = (*previous_new_areas)[i].offset;
5067                 int size = (*previous_new_areas)[i].size / 4;
5068                 gc_assert((*previous_new_areas)[i].size % 4 == 0);
5069         
5070                 /* FIXME: All these bare *4 and /4 should be something
5071                  * like BYTES_PER_WORD or WBYTES. */
5072
5073                 /*FSHOW((stderr,
5074                          "/S page %d offset %d size %d\n",
5075                          page, offset, size*4));*/
5076                 scavenge(page_address(page)+offset, size);
5077             }
5078
5079             /* Flush the current regions updating the tables. */
5080             gc_alloc_update_page_tables(0, &boxed_region);
5081             gc_alloc_update_page_tables(1, &unboxed_region);
5082         }
5083
5084         current_new_areas_index = new_areas_index;
5085
5086         /*FSHOW((stderr,
5087                  "The re-scan has finished; current_new_areas_index=%d.\n",
5088                  current_new_areas_index));*/
5089     }
5090
5091     /* Turn off recording of areas allocated by gc_alloc. */
5092     record_new_objects = 0;
5093
5094 #if SC_NS_GEN_CK
5095     /* Check that none of the write_protected pages in this generation
5096      * have been written to. */
5097     for (i = 0; i < NUM_PAGES; i++) {
5098         if ((page_table[i].allocation != FREE_PAGE)
5099             && (page_table[i].bytes_used != 0)
5100             && (page_table[i].gen == generation)
5101             && (page_table[i].write_protected_cleared != 0)
5102             && (page_table[i].dont_move == 0)) {
5103             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d",
5104                  i, generation, page_table[i].dont_move);
5105         }
5106     }
5107 #endif
5108 }
5109 \f
5110 /* Un-write-protect all the pages in from_space. This is done at the
5111  * start of a GC else there may be many page faults while scavenging
5112  * the newspace (I've seen drive the system time to 99%). These pages
5113  * would need to be unprotected anyway before unmapping in
5114  * free_oldspace; not sure what effect this has on paging.. */
5115 static void
5116 unprotect_oldspace(void)
5117 {
5118     int i;
5119
5120     for (i = 0; i < last_free_page; i++) {
5121         if ((page_table[i].allocated != FREE_PAGE)
5122             && (page_table[i].bytes_used != 0)
5123             && (page_table[i].gen == from_space)) {
5124             void *page_start;
5125
5126             page_start = (void *)page_address(i);
5127
5128             /* Remove any write-protection. We should be able to rely
5129              * on the write-protect flag to avoid redundant calls. */
5130             if (page_table[i].write_protected) {
5131                 os_protect(page_start, 4096, OS_VM_PROT_ALL);
5132                 page_table[i].write_protected = 0;
5133             }
5134         }
5135     }
5136 }
5137
5138 /* Work through all the pages and free any in from_space. This
5139  * assumes that all objects have been copied or promoted to an older
5140  * generation. Bytes_allocated and the generation bytes_allocated
5141  * counter are updated. The number of bytes freed is returned. */
5142 extern void i586_bzero(void *addr, int nbytes);
5143 static int
5144 free_oldspace(void)
5145 {
5146     int bytes_freed = 0;
5147     int first_page, last_page;
5148
5149     first_page = 0;
5150
5151     do {
5152         /* Find a first page for the next region of pages. */
5153         while ((first_page < last_free_page)
5154                && ((page_table[first_page].allocated == FREE_PAGE)
5155                    || (page_table[first_page].bytes_used == 0)
5156                    || (page_table[first_page].gen != from_space)))
5157             first_page++;
5158
5159         if (first_page >= last_free_page)
5160             break;
5161
5162         /* Find the last page of this region. */
5163         last_page = first_page;
5164
5165         do {
5166             /* Free the page. */
5167             bytes_freed += page_table[last_page].bytes_used;
5168             generations[page_table[last_page].gen].bytes_allocated -=
5169                 page_table[last_page].bytes_used;
5170             page_table[last_page].allocated = FREE_PAGE;
5171             page_table[last_page].bytes_used = 0;
5172
5173             /* Remove any write-protection. We should be able to rely
5174              * on the write-protect flag to avoid redundant calls. */
5175             {
5176                 void  *page_start = (void *)page_address(last_page);
5177         
5178                 if (page_table[last_page].write_protected) {
5179                     os_protect(page_start, 4096, OS_VM_PROT_ALL);
5180                     page_table[last_page].write_protected = 0;
5181                 }
5182             }
5183             last_page++;
5184         }
5185         while ((last_page < last_free_page)
5186                && (page_table[last_page].allocated != FREE_PAGE)
5187                && (page_table[last_page].bytes_used != 0)
5188                && (page_table[last_page].gen == from_space));
5189
5190         /* Zero pages from first_page to (last_page-1).
5191          *
5192          * FIXME: Why not use os_zero(..) function instead of
5193          * hand-coding this again? (Check other gencgc_unmap_zero
5194          * stuff too. */
5195         if (gencgc_unmap_zero) {
5196             void *page_start, *addr;
5197
5198             page_start = (void *)page_address(first_page);
5199
5200             os_invalidate(page_start, 4096*(last_page-first_page));
5201             addr = os_validate(page_start, 4096*(last_page-first_page));
5202             if (addr == NULL || addr != page_start) {
5203                 /* Is this an error condition? I couldn't really tell from
5204                  * the old CMU CL code, which fprintf'ed a message with
5205                  * an exclamation point at the end. But I've never seen the
5206                  * message, so it must at least be unusual..
5207                  *
5208                  * (The same condition is also tested for in gc_free_heap.)
5209                  *
5210                  * -- WHN 19991129 */
5211                 lose("i586_bzero: page moved, 0x%08x ==> 0x%08x",
5212                      page_start,
5213                      addr);
5214             }
5215         } else {
5216             int *page_start;
5217
5218             page_start = (int *)page_address(first_page);
5219             i586_bzero(page_start, 4096*(last_page-first_page));
5220         }
5221
5222         first_page = last_page;
5223
5224     } while (first_page < last_free_page);
5225
5226     bytes_allocated -= bytes_freed;
5227     return bytes_freed;
5228 }
5229 \f
5230 /* Print some information about a pointer at the given address. */
5231 static void
5232 print_ptr(lispobj *addr)
5233 {
5234     /* If addr is in the dynamic space then out the page information. */
5235     int pi1 = find_page_index((void*)addr);
5236
5237     if (pi1 != -1)
5238         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %d  dont_move %d\n",
5239                 (unsigned int) addr,
5240                 pi1,
5241                 page_table[pi1].allocated,
5242                 page_table[pi1].gen,
5243                 page_table[pi1].bytes_used,
5244                 page_table[pi1].first_object_offset,
5245                 page_table[pi1].dont_move);
5246     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
5247             *(addr-4),
5248             *(addr-3),
5249             *(addr-2),
5250             *(addr-1),
5251             *(addr-0),
5252             *(addr+1),
5253             *(addr+2),
5254             *(addr+3),
5255             *(addr+4));
5256 }
5257
5258 extern int undefined_tramp;
5259
5260 static void
5261 verify_space(lispobj *start, size_t words)
5262 {
5263     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
5264     int is_in_readonly_space =
5265         (READ_ONLY_SPACE_START <= (unsigned)start &&
5266          (unsigned)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER));
5267
5268     while (words > 0) {
5269         size_t count = 1;
5270         lispobj thing = *(lispobj*)start;
5271
5272         if (Pointerp(thing)) {
5273             int page_index = find_page_index((void*)thing);
5274             int to_readonly_space =
5275                 (READ_ONLY_SPACE_START <= thing &&
5276                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER));
5277             int to_static_space =
5278                 (STATIC_SPACE_START <= thing &&
5279                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER));
5280
5281             /* Does it point to the dynamic space? */
5282             if (page_index != -1) {
5283                 /* If it's within the dynamic space it should point to a used
5284                  * page. XX Could check the offset too. */
5285                 if ((page_table[page_index].allocated != FREE_PAGE)
5286                     && (page_table[page_index].bytes_used == 0))
5287                     lose ("Ptr %x @ %x sees free page.", thing, start);
5288                 /* Check that it doesn't point to a forwarding pointer! */
5289                 if (*((lispobj *)PTR(thing)) == 0x01) {
5290                     lose("Ptr %x @ %x sees forwarding ptr.", thing, start);
5291                 }
5292                 /* Check that its not in the RO space as it would then be a
5293                  * pointer from the RO to the dynamic space. */
5294                 if (is_in_readonly_space) {
5295                     lose("ptr to dynamic space %x from RO space %x",
5296                          thing, start);
5297                 }
5298                 /* Does it point to a plausible object? This check slows
5299                  * it down a lot (so it's commented out).
5300                  *
5301                  * FIXME: Add a variable to enable this dynamically. */
5302                 /* if (!valid_dynamic_space_pointer((lispobj *)thing)) {
5303                  *     lose("ptr %x to invalid object %x", thing, start); */
5304             } else {
5305                 /* Verify that it points to another valid space. */
5306                 if (!to_readonly_space && !to_static_space
5307                     && (thing != (unsigned)&undefined_tramp)) {
5308                     lose("Ptr %x @ %x sees junk.", thing, start);
5309                 }
5310             }
5311         } else {
5312             if (thing & 0x3) { /* Skip fixnums. FIXME: There should be an
5313                                 * is_fixnum for this. */
5314
5315                 switch(TypeOf(*start)) {
5316
5317                     /* boxed objects */
5318                 case type_SimpleVector:
5319                 case type_Ratio:
5320                 case type_Complex:
5321                 case type_SimpleArray:
5322                 case type_ComplexString:
5323                 case type_ComplexBitVector:
5324                 case type_ComplexVector:
5325                 case type_ComplexArray:
5326                 case type_ClosureHeader:
5327                 case type_FuncallableInstanceHeader:
5328                 case type_ByteCodeFunction:
5329                 case type_ByteCodeClosure:
5330                 case type_ValueCellHeader:
5331                 case type_SymbolHeader:
5332                 case type_BaseChar:
5333                 case type_UnboundMarker:
5334                 case type_InstanceHeader:
5335                 case type_Fdefn:
5336                     count = 1;
5337                     break;
5338
5339                 case type_CodeHeader:
5340                     {
5341                         lispobj object = *start;
5342                         struct code *code;
5343                         int nheader_words, ncode_words, nwords;
5344                         lispobj fheaderl;
5345                         struct function *fheaderp;
5346
5347                         code = (struct code *) start;
5348
5349                         /* Check that it's not in the dynamic space.
5350                          * FIXME: Isn't is supposed to be OK for code
5351                          * objects to be in the dynamic space these days? */
5352                         if (is_in_dynamic_space
5353                             /* It's ok if it's byte compiled code. The trace
5354                              * table offset will be a fixnum if it's x86
5355                              * compiled code - check. */
5356                             && !(code->trace_table_offset & 0x3)
5357                             /* Only when enabled */
5358                             && verify_dynamic_code_check) {
5359                             FSHOW((stderr,
5360                                    "/code object at %x in the dynamic space\n",
5361                                    start));
5362                         }
5363
5364                         ncode_words = fixnum_value(code->code_size);
5365                         nheader_words = HeaderValue(object);
5366                         nwords = ncode_words + nheader_words;
5367                         nwords = CEILING(nwords, 2);
5368                         /* Scavenge the boxed section of the code data block */
5369                         verify_space(start + 1, nheader_words - 1);
5370
5371                         /* Scavenge the boxed section of each function object in
5372                          * the code data block. */
5373                         fheaderl = code->entry_points;
5374                         while (fheaderl != NIL) {
5375                             fheaderp = (struct function *) PTR(fheaderl);
5376                             gc_assert(TypeOf(fheaderp->header) == type_FunctionHeader);
5377                             verify_space(&fheaderp->name, 1);
5378                             verify_space(&fheaderp->arglist, 1);
5379                             verify_space(&fheaderp->type, 1);
5380                             fheaderl = fheaderp->next;
5381                         }
5382                         count = nwords;
5383                         break;
5384                     }
5385         
5386                     /* unboxed objects */
5387                 case type_Bignum:
5388                 case type_SingleFloat:
5389                 case type_DoubleFloat:
5390 #ifdef type_ComplexLongFloat
5391                 case type_LongFloat:
5392 #endif
5393 #ifdef type_ComplexSingleFloat
5394                 case type_ComplexSingleFloat:
5395 #endif
5396 #ifdef type_ComplexDoubleFloat
5397                 case type_ComplexDoubleFloat:
5398 #endif
5399 #ifdef type_ComplexLongFloat
5400                 case type_ComplexLongFloat:
5401 #endif
5402                 case type_SimpleString:
5403                 case type_SimpleBitVector:
5404                 case type_SimpleArrayUnsignedByte2:
5405                 case type_SimpleArrayUnsignedByte4:
5406                 case type_SimpleArrayUnsignedByte8:
5407                 case type_SimpleArrayUnsignedByte16:
5408                 case type_SimpleArrayUnsignedByte32:
5409 #ifdef type_SimpleArraySignedByte8
5410                 case type_SimpleArraySignedByte8:
5411 #endif
5412 #ifdef type_SimpleArraySignedByte16
5413                 case type_SimpleArraySignedByte16:
5414 #endif
5415 #ifdef type_SimpleArraySignedByte30
5416                 case type_SimpleArraySignedByte30:
5417 #endif
5418 #ifdef type_SimpleArraySignedByte32
5419                 case type_SimpleArraySignedByte32:
5420 #endif
5421                 case type_SimpleArraySingleFloat:
5422                 case type_SimpleArrayDoubleFloat:
5423 #ifdef type_SimpleArrayComplexLongFloat
5424                 case type_SimpleArrayLongFloat:
5425 #endif
5426 #ifdef type_SimpleArrayComplexSingleFloat
5427                 case type_SimpleArrayComplexSingleFloat:
5428 #endif
5429 #ifdef type_SimpleArrayComplexDoubleFloat
5430                 case type_SimpleArrayComplexDoubleFloat:
5431 #endif
5432 #ifdef type_SimpleArrayComplexLongFloat
5433                 case type_SimpleArrayComplexLongFloat:
5434 #endif
5435                 case type_Sap:
5436                 case type_WeakPointer:
5437                     count = (sizetab[TypeOf(*start)])(start);
5438                     break;
5439
5440                 default:
5441                     gc_abort();
5442                 }
5443             }
5444         }
5445         start += count;
5446         words -= count;
5447     }
5448 }
5449
5450 static void
5451 verify_gc(void)
5452 {
5453     /* FIXME: It would be nice to make names consistent so that
5454      * foo_size meant size *in* *bytes* instead of size in some
5455      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
5456      * Some counts of lispobjs are called foo_count; it might be good
5457      * to grep for all foo_size and rename the appropriate ones to
5458      * foo_count. */
5459     int read_only_space_size =
5460         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER)
5461         - (lispobj*)READ_ONLY_SPACE_START;
5462     int static_space_size =
5463         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER)
5464         - (lispobj*)STATIC_SPACE_START;
5465     int binding_stack_size =
5466         (lispobj*)SymbolValue(BINDING_STACK_POINTER)
5467         - (lispobj*)BINDING_STACK_START;
5468
5469     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
5470     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
5471     verify_space((lispobj*)BINDING_STACK_START  , binding_stack_size);
5472 }
5473
5474 static void
5475 verify_generation(int  generation)
5476 {
5477     int i;
5478
5479     for (i = 0; i < last_free_page; i++) {
5480         if ((page_table[i].allocated != FREE_PAGE)
5481             && (page_table[i].bytes_used != 0)
5482             && (page_table[i].gen == generation)) {
5483             int last_page;
5484             int region_allocation = page_table[i].allocated;
5485
5486             /* This should be the start of a contiguous block */
5487             gc_assert(page_table[i].first_object_offset == 0);
5488
5489             /* Need to find the full extent of this contiguous block in case
5490                objects span pages. */
5491
5492             /* Now work forward until the end of this contiguous area is
5493                found. */
5494             for (last_page = i; ;last_page++)
5495                 /* Check whether this is the last page in this contiguous
5496                  * block. */
5497                 if ((page_table[last_page].bytes_used < 4096)
5498                     /* Or it is 4096 and is the last in the block */
5499                     || (page_table[last_page+1].allocated != region_allocation)
5500                     || (page_table[last_page+1].bytes_used == 0)
5501                     || (page_table[last_page+1].gen != generation)
5502                     || (page_table[last_page+1].first_object_offset == 0))
5503                     break;
5504
5505             verify_space(page_address(i), (page_table[last_page].bytes_used
5506                                            + (last_page-i)*4096)/4);
5507             i = last_page;
5508         }
5509     }
5510 }
5511
5512 /* Check the all the free space is zero filled. */
5513 static void
5514 verify_zero_fill(void)
5515 {
5516     int page;
5517
5518     for (page = 0; page < last_free_page; page++) {
5519         if (page_table[page].allocated == FREE_PAGE) {
5520             /* The whole page should be zero filled. */
5521             int *start_addr = (int *)page_address(page);
5522             int size = 1024;
5523             int i;
5524             for (i = 0; i < size; i++) {
5525                 if (start_addr[i] != 0) {
5526                     lose("free page not zero at %x", start_addr + i);
5527                 }
5528             }
5529         } else {
5530             int free_bytes = 4096 - page_table[page].bytes_used;
5531             if (free_bytes > 0) {
5532                 int *start_addr = (int *)((unsigned)page_address(page)
5533                                           + page_table[page].bytes_used);
5534                 int size = free_bytes / 4;
5535                 int i;
5536                 for (i = 0; i < size; i++) {
5537                     if (start_addr[i] != 0) {
5538                         lose("free region not zero at %x", start_addr + i);
5539                     }
5540                 }
5541             }
5542         }
5543     }
5544 }
5545
5546 /* External entry point for verify_zero_fill */
5547 void
5548 gencgc_verify_zero_fill(void)
5549 {
5550     /* Flush the alloc regions updating the tables. */
5551     boxed_region.free_pointer = current_region_free_pointer;
5552     gc_alloc_update_page_tables(0, &boxed_region);
5553     gc_alloc_update_page_tables(1, &unboxed_region);
5554     SHOW("verifying zero fill");
5555     verify_zero_fill();
5556     current_region_free_pointer = boxed_region.free_pointer;
5557     current_region_end_addr = boxed_region.end_addr;
5558 }
5559
5560 static void
5561 verify_dynamic_space(void)
5562 {
5563     int i;
5564
5565     for (i = 0; i < NUM_GENERATIONS; i++)
5566         verify_generation(i);
5567
5568     if (gencgc_enable_verify_zero_fill)
5569         verify_zero_fill();
5570 }
5571 \f
5572 /* Write-protect all the dynamic boxed pages in the given generation. */
5573 static void
5574 write_protect_generation_pages(int generation)
5575 {
5576     int i;
5577
5578     gc_assert(generation < NUM_GENERATIONS);
5579
5580     for (i = 0; i < last_free_page; i++)
5581         if ((page_table[i].allocated == BOXED_PAGE)
5582             && (page_table[i].bytes_used != 0)
5583             && (page_table[i].gen == generation))  {
5584             void *page_start;
5585
5586             page_start = (void *)page_address(i);
5587
5588             os_protect(page_start,
5589                        4096,
5590                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
5591
5592             /* Note the page as protected in the page tables. */
5593             page_table[i].write_protected = 1;
5594         }
5595
5596     if (gencgc_verbose > 1) {
5597         FSHOW((stderr,
5598                "/write protected %d of %d pages in generation %d\n",
5599                count_write_protect_generation_pages(generation),
5600                count_generation_pages(generation),
5601                generation));
5602     }
5603 }
5604
5605 /* Garbage collect a generation. If raise is 0 the remains of the
5606  * generation are not raised to the next generation. */
5607 static void
5608 garbage_collect_generation(int generation, int raise)
5609 {
5610     unsigned long bytes_freed;
5611     unsigned long i;
5612     unsigned long read_only_space_size, static_space_size;
5613
5614     gc_assert(generation <= (NUM_GENERATIONS-1));
5615
5616     /* The oldest generation can't be raised. */
5617     gc_assert((generation != (NUM_GENERATIONS-1)) || (raise == 0));
5618
5619     /* Initialize the weak pointer list. */
5620     weak_pointers = NULL;
5621
5622     /* When a generation is not being raised it is transported to a
5623      * temporary generation (NUM_GENERATIONS), and lowered when
5624      * done. Set up this new generation. There should be no pages
5625      * allocated to it yet. */
5626     if (!raise)
5627         gc_assert(generations[NUM_GENERATIONS].bytes_allocated == 0);
5628
5629     /* Set the global src and dest. generations */
5630     from_space = generation;
5631     if (raise)
5632         new_space = generation+1;
5633     else
5634         new_space = NUM_GENERATIONS;
5635
5636     /* Change to a new space for allocation, resetting the alloc_start_page */
5637     gc_alloc_generation = new_space;
5638     generations[new_space].alloc_start_page = 0;
5639     generations[new_space].alloc_unboxed_start_page = 0;
5640     generations[new_space].alloc_large_start_page = 0;
5641     generations[new_space].alloc_large_unboxed_start_page = 0;
5642
5643     /* Before any pointers are preserved, the dont_move flags on the
5644      * pages need to be cleared. */
5645     for (i = 0; i < last_free_page; i++)
5646         page_table[i].dont_move = 0;
5647
5648     /* Un-write-protect the old-space pages. This is essential for the
5649      * promoted pages as they may contain pointers into the old-space
5650      * which need to be scavenged. It also helps avoid unnecessary page
5651      * faults as forwarding pointer are written into them. They need to
5652      * be un-protected anyway before unmapping later. */
5653     unprotect_oldspace();
5654
5655     /* Scavenge the stack's conservative roots. */
5656     {
5657         lispobj **ptr;
5658         for (ptr = (lispobj **)CONTROL_STACK_END - 1;
5659              ptr > (lispobj **)&raise;
5660              ptr--) {
5661             preserve_pointer(*ptr);
5662         }
5663     }
5664 #ifdef CONTROL_STACKS
5665     scavenge_thread_stacks();
5666 #endif
5667
5668     if (gencgc_verbose > 1) {
5669         int num_dont_move_pages = count_dont_move_pages();
5670         FSHOW((stderr,
5671                "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
5672                num_dont_move_pages,
5673                /* FIXME: 4096 should be symbolic constant here and
5674                 * prob'ly elsewhere too. */
5675                num_dont_move_pages * 4096));
5676     }
5677
5678     /* Scavenge all the rest of the roots. */
5679
5680     /* Scavenge the Lisp functions of the interrupt handlers, taking
5681      * care to avoid SIG_DFL, SIG_IGN. */
5682     for (i = 0; i < NSIG; i++) {
5683         union interrupt_handler handler = interrupt_handlers[i];
5684         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
5685             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
5686             scavenge((lispobj *)(interrupt_handlers + i), 1);
5687         }
5688     }
5689
5690     /* Scavenge the binding stack. */
5691     scavenge( (lispobj *) BINDING_STACK_START,
5692              (lispobj *)SymbolValue(BINDING_STACK_POINTER) -
5693              (lispobj *)BINDING_STACK_START);
5694
5695     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
5696         read_only_space_size =
5697             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
5698             (lispobj*)READ_ONLY_SPACE_START;
5699         FSHOW((stderr,
5700                "/scavenge read only space: %d bytes\n",
5701                read_only_space_size * sizeof(lispobj)));
5702         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
5703     }
5704
5705     static_space_size =
5706         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER) -
5707         (lispobj *)STATIC_SPACE_START;
5708     if (gencgc_verbose > 1)
5709         FSHOW((stderr,
5710                "/scavenge static space: %d bytes\n",
5711                static_space_size * sizeof(lispobj)));
5712     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
5713
5714     /* All generations but the generation being GCed need to be
5715      * scavenged. The new_space generation needs special handling as
5716      * objects may be moved in - it is handled separately below. */
5717     for (i = 0; i < NUM_GENERATIONS; i++)
5718         if ((i != generation) && (i != new_space))
5719             scavenge_generation(i);
5720
5721     /* Finally scavenge the new_space generation. Keep going until no
5722      * more objects are moved into the new generation */
5723     scavenge_newspace_generation(new_space);
5724
5725 #define RESCAN_CHECK 0
5726 #if RESCAN_CHECK
5727     /* As a check re-scavenge the newspace once; no new objects should
5728      * be found. */
5729     {
5730         int old_bytes_allocated = bytes_allocated;
5731         int bytes_allocated;
5732
5733         /* Start with a full scavenge. */
5734         scavenge_newspace_generation_one_scan(new_space);
5735
5736         /* Flush the current regions, updating the tables. */
5737         gc_alloc_update_page_tables(0, &boxed_region);
5738         gc_alloc_update_page_tables(1, &unboxed_region);
5739
5740         bytes_allocated = bytes_allocated - old_bytes_allocated;
5741
5742         if (bytes_allocated != 0) {
5743             lose("Rescan of new_space allocated %d more bytes.",
5744                  bytes_allocated);
5745         }
5746     }
5747 #endif
5748
5749     scan_weak_pointers();
5750
5751     /* Flush the current regions, updating the tables. */
5752     gc_alloc_update_page_tables(0, &boxed_region);
5753     gc_alloc_update_page_tables(1, &unboxed_region);
5754
5755     /* Free the pages in oldspace, but not those marked dont_move. */
5756     bytes_freed = free_oldspace();
5757
5758     /* If the GC is not raising the age then lower the generation back
5759      * to its normal generation number */
5760     if (!raise) {
5761         for (i = 0; i < last_free_page; i++)
5762             if ((page_table[i].bytes_used != 0)
5763                 && (page_table[i].gen == NUM_GENERATIONS))
5764                 page_table[i].gen = generation;
5765         gc_assert(generations[generation].bytes_allocated == 0);
5766         generations[generation].bytes_allocated =
5767             generations[NUM_GENERATIONS].bytes_allocated;
5768         generations[NUM_GENERATIONS].bytes_allocated = 0;
5769     }
5770
5771     /* Reset the alloc_start_page for generation. */
5772     generations[generation].alloc_start_page = 0;
5773     generations[generation].alloc_unboxed_start_page = 0;
5774     generations[generation].alloc_large_start_page = 0;
5775     generations[generation].alloc_large_unboxed_start_page = 0;
5776
5777     if (generation >= verify_gens) {
5778         if (gencgc_verbose)
5779             SHOW("verifying");
5780         verify_gc();
5781         verify_dynamic_space();
5782     }
5783
5784     /* Set the new gc trigger for the GCed generation. */
5785     generations[generation].gc_trigger =
5786         generations[generation].bytes_allocated
5787         + generations[generation].bytes_consed_between_gc;
5788
5789     if (raise)
5790         generations[generation].num_gc = 0;
5791     else
5792         ++generations[generation].num_gc;
5793 }
5794
5795 /* Update last_free_page then ALLOCATION_POINTER */
5796 int
5797 update_x86_dynamic_space_free_pointer(void)
5798 {
5799     int last_page = -1;
5800     int i;
5801
5802     for (i = 0; i < NUM_PAGES; i++)
5803         if ((page_table[i].allocated != FREE_PAGE)
5804             && (page_table[i].bytes_used != 0))
5805             last_page = i;
5806
5807     last_free_page = last_page+1;
5808
5809     SetSymbolValue(ALLOCATION_POINTER,
5810                    (lispobj)(((char *)heap_base) + last_free_page*4096));
5811     return 0; /* dummy value: return something ... */
5812 }
5813
5814 /* GC all generations below last_gen, raising their objects to the
5815  * next generation until all generations below last_gen are empty.
5816  * Then if last_gen is due for a GC then GC it. In the special case
5817  * that last_gen==NUM_GENERATIONS, the last generation is always
5818  * GC'ed. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
5819  *
5820  * The oldest generation to be GCed will always be
5821  * gencgc_oldest_gen_to_gc, partly ignoring last_gen if necessary. */
5822 void
5823 collect_garbage(unsigned last_gen)
5824 {
5825     int gen = 0;
5826     int raise;
5827     int gen_to_wp;
5828     int i;
5829
5830     boxed_region.free_pointer = current_region_free_pointer;
5831
5832     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
5833
5834     if (last_gen > NUM_GENERATIONS) {
5835         FSHOW((stderr,
5836                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
5837                last_gen));
5838         last_gen = 0;
5839     }
5840
5841     /* Flush the alloc regions updating the tables. */
5842     gc_alloc_update_page_tables(0, &boxed_region);
5843     gc_alloc_update_page_tables(1, &unboxed_region);
5844
5845     /* Verify the new objects created by Lisp code. */
5846     if (pre_verify_gen_0) {
5847         SHOW((stderr, "pre-checking generation 0\n"));
5848         verify_generation(0);
5849     }
5850
5851     if (gencgc_verbose > 1)
5852         print_generation_stats(0);
5853
5854     do {
5855         /* Collect the generation. */
5856
5857         if (gen >= gencgc_oldest_gen_to_gc) {
5858             /* Never raise the oldest generation. */
5859             raise = 0;
5860         } else {
5861             raise =
5862                 (gen < last_gen)
5863                 || (generations[gen].num_gc >= generations[gen].trigger_age);
5864         }
5865
5866         if (gencgc_verbose > 1) {
5867             FSHOW((stderr,
5868                    "Starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
5869                    gen,
5870                    raise,
5871                    generations[gen].bytes_allocated,
5872                    generations[gen].gc_trigger,
5873                    generations[gen].num_gc));
5874         }
5875
5876         /* If an older generation is being filled then update its memory
5877          * age. */
5878         if (raise == 1) {
5879             generations[gen+1].cum_sum_bytes_allocated +=
5880                 generations[gen+1].bytes_allocated;
5881         }
5882
5883         garbage_collect_generation(gen, raise);
5884
5885         /* Reset the memory age cum_sum. */
5886         generations[gen].cum_sum_bytes_allocated = 0;
5887
5888         if (gencgc_verbose > 1) {
5889             FSHOW((stderr, "GC of generation %d finished:\n", gen));
5890             print_generation_stats(0);
5891         }
5892
5893         gen++;
5894     } while ((gen <= gencgc_oldest_gen_to_gc)
5895              && ((gen < last_gen)
5896                  || ((gen <= gencgc_oldest_gen_to_gc)
5897                      && raise
5898                      && (generations[gen].bytes_allocated
5899                          > generations[gen].gc_trigger)
5900                      && (gen_av_mem_age(gen)
5901                          > generations[gen].min_av_mem_age))));
5902
5903     /* Now if gen-1 was raised all generations before gen are empty.
5904      * If it wasn't raised then all generations before gen-1 are empty.
5905      *
5906      * Now objects within this gen's pages cannot point to younger
5907      * generations unless they are written to. This can be exploited
5908      * by write-protecting the pages of gen; then when younger
5909      * generations are GCed only the pages which have been written
5910      * need scanning. */
5911     if (raise)
5912         gen_to_wp = gen;
5913     else
5914         gen_to_wp = gen - 1;
5915
5916     /* There's not much point in WPing pages in generation 0 as it is
5917      * never scavenged (except promoted pages). */
5918     if ((gen_to_wp > 0) && enable_page_protection) {
5919         /* Check that they are all empty. */
5920         for (i = 0; i < gen_to_wp; i++) {
5921             if (generations[i].bytes_allocated)
5922                 lose("trying to write-protect gen. %d when gen. %d nonempty",
5923                      gen_to_wp, i);
5924         }
5925         write_protect_generation_pages(gen_to_wp);
5926     }
5927
5928     /* Set gc_alloc back to generation 0. The current regions should
5929      * be flushed after the above GCs */
5930     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
5931     gc_alloc_generation = 0;
5932
5933     update_x86_dynamic_space_free_pointer();
5934
5935     /* This is now done by Lisp SCRUB-CONTROL-STACK in Lisp SUB-GC, so we
5936      * needn't do it here: */
5937     /*  zero_stack();*/
5938
5939     current_region_free_pointer = boxed_region.free_pointer;
5940     current_region_end_addr = boxed_region.end_addr;
5941
5942     SHOW("returning from collect_garbage");
5943 }
5944
5945 /* This is called by Lisp PURIFY when it is finished. All live objects
5946  * will have been moved to the RO and Static heaps. The dynamic space
5947  * will need a full re-initialization. We don't bother having Lisp
5948  * PURIFY flush the current gc_alloc region, as the page_tables are
5949  * re-initialized, and every page is zeroed to be sure. */
5950 void
5951 gc_free_heap(void)
5952 {
5953     int page;
5954
5955     if (gencgc_verbose > 1)
5956         SHOW("entering gc_free_heap");
5957
5958     for (page = 0; page < NUM_PAGES; page++) {
5959         /* Skip free pages which should already be zero filled. */
5960         if (page_table[page].allocated != FREE_PAGE) {
5961             void *page_start, *addr;
5962
5963             /* Mark the page free. The other slots are assumed invalid
5964              * when it is a FREE_PAGE and bytes_used is 0 and it
5965              * should not be write-protected -- except that the
5966              * generation is used for the current region but it sets
5967              * that up. */
5968             page_table[page].allocated = FREE_PAGE;
5969             page_table[page].bytes_used = 0;
5970
5971             /* Zero the page. */
5972             page_start = (void *)page_address(page);
5973
5974             /* First, remove any write-protection. */
5975             os_protect(page_start, 4096, OS_VM_PROT_ALL);
5976             page_table[page].write_protected = 0;
5977
5978             os_invalidate(page_start,4096);
5979             addr = os_validate(page_start,4096);
5980             if (addr == NULL || addr != page_start) {
5981                 lose("gc_free_heap: page moved, 0x%08x ==> 0x%08x",
5982                      page_start,
5983                      addr);
5984             }
5985         } else if (gencgc_zero_check_during_free_heap) {
5986             /* Double-check that the page is zero filled. */
5987             int *page_start, i;
5988             gc_assert(page_table[page].allocated == FREE_PAGE);
5989             gc_assert(page_table[page].bytes_used == 0);
5990             page_start = (int *)page_address(page);
5991             for (i=0; i<1024; i++) {
5992                 if (page_start[i] != 0) {
5993                     lose("free region not zero at %x", page_start + i);
5994                 }
5995             }
5996         }
5997     }
5998
5999     bytes_allocated = 0;
6000
6001     /* Initialize the generations. */
6002     for (page = 0; page < NUM_GENERATIONS; page++) {
6003         generations[page].alloc_start_page = 0;
6004         generations[page].alloc_unboxed_start_page = 0;
6005         generations[page].alloc_large_start_page = 0;
6006         generations[page].alloc_large_unboxed_start_page = 0;
6007         generations[page].bytes_allocated = 0;
6008         generations[page].gc_trigger = 2000000;
6009         generations[page].num_gc = 0;
6010         generations[page].cum_sum_bytes_allocated = 0;
6011     }
6012
6013     if (gencgc_verbose > 1)
6014         print_generation_stats(0);
6015
6016     /* Initialize gc_alloc */
6017     gc_alloc_generation = 0;
6018     boxed_region.first_page = 0;
6019     boxed_region.last_page = -1;
6020     boxed_region.start_addr = page_address(0);
6021     boxed_region.free_pointer = page_address(0);
6022     boxed_region.end_addr = page_address(0);
6023
6024     unboxed_region.first_page = 0;
6025     unboxed_region.last_page = -1;
6026     unboxed_region.start_addr = page_address(0);
6027     unboxed_region.free_pointer = page_address(0);
6028     unboxed_region.end_addr = page_address(0);
6029
6030 #if 0 /* Lisp PURIFY is currently running on the C stack so don't do this. */
6031     zero_stack();
6032 #endif
6033
6034     last_free_page = 0;
6035     SetSymbolValue(ALLOCATION_POINTER, (lispobj)((char *)heap_base));
6036
6037     current_region_free_pointer = boxed_region.free_pointer;
6038     current_region_end_addr = boxed_region.end_addr;
6039
6040     if (verify_after_free_heap) {
6041         /* Check whether purify has left any bad pointers. */
6042         if (gencgc_verbose)
6043             SHOW("checking after free_heap\n");
6044         verify_gc();
6045     }
6046 }
6047 \f
6048 void
6049 gc_init(void)
6050 {
6051     int i;
6052
6053     gc_init_tables();
6054
6055     heap_base = (void*)DYNAMIC_SPACE_START;
6056
6057     /* Initialize each page structure. */
6058     for (i = 0; i < NUM_PAGES; i++) {
6059         /* Initialize all pages as free. */
6060         page_table[i].allocated = FREE_PAGE;
6061         page_table[i].bytes_used = 0;
6062
6063         /* Pages are not write-protected at startup. */
6064         page_table[i].write_protected = 0;
6065     }
6066
6067     bytes_allocated = 0;
6068
6069     /* Initialize the generations. */
6070     for (i = 0; i < NUM_GENERATIONS; i++) {
6071         generations[i].alloc_start_page = 0;
6072         generations[i].alloc_unboxed_start_page = 0;
6073         generations[i].alloc_large_start_page = 0;
6074         generations[i].alloc_large_unboxed_start_page = 0;
6075         generations[i].bytes_allocated = 0;
6076         generations[i].gc_trigger = 2000000;
6077         generations[i].num_gc = 0;
6078         generations[i].cum_sum_bytes_allocated = 0;
6079         /* the tune-able parameters */
6080         generations[i].bytes_consed_between_gc = 2000000;
6081         generations[i].trigger_age = 1;
6082         generations[i].min_av_mem_age = 0.75;
6083     }
6084
6085     /* Initialize gc_alloc. */
6086     gc_alloc_generation = 0;
6087     boxed_region.first_page = 0;
6088     boxed_region.last_page = -1;
6089     boxed_region.start_addr = page_address(0);
6090     boxed_region.free_pointer = page_address(0);
6091     boxed_region.end_addr = page_address(0);
6092
6093     unboxed_region.first_page = 0;
6094     unboxed_region.last_page = -1;
6095     unboxed_region.start_addr = page_address(0);
6096     unboxed_region.free_pointer = page_address(0);
6097     unboxed_region.end_addr = page_address(0);
6098
6099     last_free_page = 0;
6100
6101     current_region_free_pointer = boxed_region.free_pointer;
6102     current_region_end_addr = boxed_region.end_addr;
6103 }
6104
6105 /*  Pick up the dynamic space from after a core load.
6106  *
6107  *  The ALLOCATION_POINTER points to the end of the dynamic space.
6108  *
6109  *  XX A scan is needed to identify the closest first objects for pages. */
6110 void
6111 gencgc_pickup_dynamic(void)
6112 {
6113     int page = 0;
6114     int addr = DYNAMIC_SPACE_START;
6115     int alloc_ptr = SymbolValue(ALLOCATION_POINTER);
6116
6117     /* Initialize the first region. */
6118     do {
6119         page_table[page].allocated = BOXED_PAGE;
6120         page_table[page].gen = 0;
6121         page_table[page].bytes_used = 4096;
6122         page_table[page].large_object = 0;
6123         page_table[page].first_object_offset =
6124             (void *)DYNAMIC_SPACE_START - page_address(page);
6125         addr += 4096;
6126         page++;
6127     } while (addr < alloc_ptr);
6128
6129     generations[0].bytes_allocated = 4096*page;
6130     bytes_allocated = 4096*page;
6131
6132     current_region_free_pointer = boxed_region.free_pointer;
6133     current_region_end_addr = boxed_region.end_addr;
6134 }
6135 \f
6136 /* a counter for how deep we are in alloc(..) calls */
6137 int alloc_entered = 0;
6138
6139 /* alloc(..) is the external interface for memory allocation. It
6140  * allocates to generation 0. It is not called from within the garbage
6141  * collector as it is only external uses that need the check for heap
6142  * size (GC trigger) and to disable the interrupts (interrupts are
6143  * always disabled during a GC).
6144  *
6145  * The vops that call alloc(..) assume that the returned space is zero-filled.
6146  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
6147  *
6148  * The check for a GC trigger is only performed when the current
6149  * region is full, so in most cases it's not needed. Further MAYBE-GC
6150  * is only called once because Lisp will remember "need to collect
6151  * garbage" and get around to it when it can. */
6152 char *
6153 alloc(int nbytes)
6154 {
6155     /* Check for alignment allocation problems. */
6156     gc_assert((((unsigned)current_region_free_pointer & 0x7) == 0)
6157               && ((nbytes & 0x7) == 0));
6158
6159     if (SymbolValue(PSEUDO_ATOMIC_ATOMIC)) {/* if already in a pseudo atomic */
6160         
6161         void *new_free_pointer;
6162
6163     retry1:
6164         if (alloc_entered) {
6165             SHOW("alloc re-entered in already-pseudo-atomic case");
6166         }
6167         ++alloc_entered;
6168
6169         /* Check whether there is room in the current region. */
6170         new_free_pointer = current_region_free_pointer + nbytes;
6171
6172         /* FIXME: Shouldn't we be doing some sort of lock here, to
6173          * keep from getting screwed if an interrupt service routine
6174          * allocates memory between the time we calculate new_free_pointer
6175          * and the time we write it back to current_region_free_pointer?
6176          * Perhaps I just don't understand pseudo-atomics..
6177          *
6178          * Perhaps I don't. It looks as though what happens is if we
6179          * were interrupted any time during the pseudo-atomic
6180          * interval (which includes now) we discard the allocated
6181          * memory and try again. So, at least we don't return
6182          * a memory area that was allocated out from underneath us
6183          * by code in an ISR.
6184          * Still, that doesn't seem to prevent
6185          * current_region_free_pointer from getting corrupted:
6186          *   We read current_region_free_pointer.
6187          *   They read current_region_free_pointer.
6188          *   They write current_region_free_pointer.
6189          *   We write current_region_free_pointer, scribbling over
6190          *     whatever they wrote. */
6191
6192         if (new_free_pointer <= boxed_region.end_addr) {
6193             /* If so then allocate from the current region. */
6194             void  *new_obj = current_region_free_pointer;
6195             current_region_free_pointer = new_free_pointer;
6196             alloc_entered--;
6197             return((void *)new_obj);
6198         }
6199
6200         if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
6201             /* Double the trigger. */
6202             auto_gc_trigger *= 2;
6203             alloc_entered--;
6204             /* Exit the pseudo-atomic. */
6205             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6206             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6207                 /* Handle any interrupts that occurred during
6208                  * gc_alloc(..). */
6209                 do_pending_interrupt();
6210             }
6211             funcall0(SymbolFunction(MAYBE_GC));
6212             /* Re-enter the pseudo-atomic. */
6213             SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(0));
6214             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(1));
6215             goto retry1;
6216         }
6217         /* Call gc_alloc. */
6218         boxed_region.free_pointer = current_region_free_pointer;
6219         {
6220             void *new_obj = gc_alloc(nbytes);
6221             current_region_free_pointer = boxed_region.free_pointer;
6222             current_region_end_addr = boxed_region.end_addr;
6223             alloc_entered--;
6224             return (new_obj);
6225         }
6226     } else {
6227         void *result;
6228         void *new_free_pointer;
6229
6230     retry2:
6231         /* At least wrap this allocation in a pseudo atomic to prevent
6232          * gc_alloc from being re-entered. */
6233         SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(0));
6234         SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(1));
6235
6236         if (alloc_entered)
6237             SHOW("alloc re-entered in not-already-pseudo-atomic case");
6238         ++alloc_entered;
6239
6240         /* Check whether there is room in the current region. */
6241         new_free_pointer = current_region_free_pointer + nbytes;
6242
6243         if (new_free_pointer <= boxed_region.end_addr) {
6244             /* If so then allocate from the current region. */
6245             void *new_obj = current_region_free_pointer;
6246             current_region_free_pointer = new_free_pointer;
6247             alloc_entered--;
6248             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6249             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED)) {
6250                 /* Handle any interrupts that occurred during
6251                  * gc_alloc(..). */
6252                 do_pending_interrupt();
6253                 goto retry2;
6254             }
6255
6256             return((void *)new_obj);
6257         }
6258
6259         /* KLUDGE: There's lots of code around here shared with the
6260          * the other branch. Is there some way to factor out the
6261          * duplicate code? -- WHN 19991129 */
6262         if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
6263             /* Double the trigger. */
6264             auto_gc_trigger *= 2;
6265             alloc_entered--;
6266             /* Exit the pseudo atomic. */
6267             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6268             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6269                 /* Handle any interrupts that occurred during
6270                  * gc_alloc(..); */
6271                 do_pending_interrupt();
6272             }
6273             funcall0(SymbolFunction(MAYBE_GC));
6274             goto retry2;
6275         }
6276
6277         /* Else call gc_alloc. */
6278         boxed_region.free_pointer = current_region_free_pointer;
6279         result = gc_alloc(nbytes);
6280         current_region_free_pointer = boxed_region.free_pointer;
6281         current_region_end_addr = boxed_region.end_addr;
6282
6283         alloc_entered--;
6284         SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6285         if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6286             /* Handle any interrupts that occurred during
6287              * gc_alloc(..). */
6288             do_pending_interrupt();
6289             goto retry2;
6290         }
6291
6292         return result;
6293     }
6294 }
6295 \f
6296 /*
6297  * noise to manipulate the gc trigger stuff
6298  */
6299
6300 void
6301 set_auto_gc_trigger(os_vm_size_t dynamic_usage)
6302 {
6303     auto_gc_trigger += dynamic_usage;
6304 }
6305
6306 void
6307 clear_auto_gc_trigger(void)
6308 {
6309     auto_gc_trigger = 0;
6310 }
6311 \f
6312 /* Find the code object for the given pc, or return NULL on failure.
6313  *
6314  * FIXME: PC shouldn't be lispobj*, should it? Maybe void*? */
6315 lispobj *
6316 component_ptr_from_pc(lispobj *pc)
6317 {
6318     lispobj *object = NULL;
6319
6320     if ( (object = search_read_only_space(pc)) )
6321         ;
6322     else if ( (object = search_static_space(pc)) )
6323         ;
6324     else
6325         object = search_dynamic_space(pc);
6326
6327     if (object) /* if we found something */
6328         if (TypeOf(*object) == type_CodeHeader) /* if it's a code object */
6329             return(object);
6330
6331     return (NULL);
6332 }
6333 \f
6334 /*
6335  * shared support for the OS-dependent signal handlers which
6336  * catch GENCGC-related write-protect violations
6337  */
6338
6339 /* Depending on which OS we're running under, different signals might
6340  * be raised for a violation of write protection in the heap. This
6341  * function factors out the common generational GC magic which needs
6342  * to invoked in this case, and should be called from whatever signal
6343  * handler is appropriate for the OS we're running under.
6344  *
6345  * Return true if this signal is a normal generational GC thing that
6346  * we were able to handle, or false if it was abnormal and control
6347  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
6348 int
6349 gencgc_handle_wp_violation(void* fault_addr)
6350 {
6351     int  page_index = find_page_index(fault_addr);
6352
6353 #if defined QSHOW_SIGNALS
6354     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
6355            fault_addr, page_index));
6356 #endif
6357
6358     /* Check whether the fault is within the dynamic space. */
6359     if (page_index == (-1)) {
6360
6361         /* not within the dynamic space -- not our responsibility */
6362         return 0;
6363
6364     } else {
6365
6366         /* The only acceptable reason for an signal like this from the
6367          * heap is that the generational GC write-protected the page. */
6368         if (page_table[page_index].write_protected != 1) {
6369             lose("access failure in heap page not marked as write-protected");
6370         }
6371         
6372         /* Unprotect the page. */
6373         os_protect(page_address(page_index), 4096, OS_VM_PROT_ALL);
6374         page_table[page_index].write_protected = 0;
6375         page_table[page_index].write_protected_cleared = 1;
6376
6377         /* Don't worry, we can handle it. */
6378         return 1;
6379     }
6380 }