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