af6b4ae08a1e9ee43aa34e67950eeef6a9c29277
[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 <errno.h>
30 #include "runtime.h"
31 #include "sbcl.h"
32 #include "os.h"
33 #include "interr.h"
34 #include "globals.h"
35 #include "interrupt.h"
36 #include "validate.h"
37 #include "lispregs.h"
38 #include "arch.h"
39 #include "gc.h"
40 #include "gc-internal.h"
41 #include "thread.h"
42 #include "genesis/vector.h"
43 #include "genesis/weak-pointer.h"
44 #include "genesis/simple-fun.h"
45
46 #ifdef LISP_FEATURE_SB_THREAD
47 #include <sys/ptrace.h>
48 #include <linux/user.h>         /* threading is presently linux-only */
49 #endif
50
51 /* assembly language stub that executes trap_PendingInterrupt */
52 void do_pending_interrupt(void);
53
54 \f
55 /*
56  * GC parameters
57  */
58
59 /* the number of actual generations. (The number of 'struct
60  * generation' objects is one more than this, because one object
61  * serves as scratch when GC'ing.) */
62 #define NUM_GENERATIONS 6
63
64 /* Should we use page protection to help avoid the scavenging of pages
65  * that don't have pointers to younger generations? */
66 boolean enable_page_protection = 1;
67
68 /* Should we unmap a page and re-mmap it to have it zero filled? */
69 #if defined(__FreeBSD__) || defined(__OpenBSD__)
70 /* comment from cmucl-2.4.8: This can waste a lot of swap on FreeBSD
71  * so don't unmap there.
72  *
73  * The CMU CL comment didn't specify a version, but was probably an
74  * old version of FreeBSD (pre-4.0), so this might no longer be true.
75  * OTOH, if it is true, this behavior might exist on OpenBSD too, so
76  * for now we don't unmap there either. -- WHN 2001-04-07 */
77 boolean gencgc_unmap_zero = 0;
78 #else
79 boolean gencgc_unmap_zero = 1;
80 #endif
81
82 /* the minimum size (in bytes) for a large object*/
83 unsigned large_object_size = 4 * 4096;
84 \f
85 /*
86  * debugging
87  */
88
89
90
91 /* the verbosity level. All non-error messages are disabled at level 0;
92  * and only a few rare messages are printed at level 1. */
93 unsigned gencgc_verbose = (QSHOW ? 1 : 0);
94
95 /* FIXME: At some point enable the various error-checking things below
96  * and see what they say. */
97
98 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
99  * Set verify_gens to NUM_GENERATIONS to disable this kind of check. */
100 int verify_gens = NUM_GENERATIONS;
101
102 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
103 boolean pre_verify_gen_0 = 0;
104
105 /* Should we check for bad pointers after gc_free_heap is called
106  * from Lisp PURIFY? */
107 boolean verify_after_free_heap = 0;
108
109 /* Should we print a note when code objects are found in the dynamic space
110  * during a heap verify? */
111 boolean verify_dynamic_code_check = 0;
112
113 /* Should we check code objects for fixup errors after they are transported? */
114 boolean check_code_fixups = 0;
115
116 /* Should we check that newly allocated regions are zero filled? */
117 boolean gencgc_zero_check = 0;
118
119 /* Should we check that the free space is zero filled? */
120 boolean gencgc_enable_verify_zero_fill = 0;
121
122 /* Should we check that free pages are zero filled during gc_free_heap
123  * called after Lisp PURIFY? */
124 boolean gencgc_zero_check_during_free_heap = 0;
125 \f
126 /*
127  * GC structures and variables
128  */
129
130 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
131 unsigned long bytes_allocated = 0;
132 static unsigned long auto_gc_trigger = 0;
133
134 /* the source and destination generations. These are set before a GC starts
135  * scavenging. */
136 int from_space;
137 int new_space;
138
139
140 /* FIXME: It would be nice to use this symbolic constant instead of
141  * bare 4096 almost everywhere. We could also use an assertion that
142  * it's equal to getpagesize(). */
143
144 #define PAGE_BYTES 4096
145
146 /* An array of page structures is statically allocated.
147  * This helps quickly map between an address its page structure.
148  * NUM_PAGES is set from the size of the dynamic space. */
149 struct page page_table[NUM_PAGES];
150
151 /* To map addresses to page structures the address of the first page
152  * is needed. */
153 static void *heap_base = NULL;
154
155
156 /* Calculate the start address for the given page number. */
157 inline void *
158 page_address(int page_num)
159 {
160     return (heap_base + (page_num * 4096));
161 }
162
163 /* Find the page index within the page_table for the given
164  * address. Return -1 on failure. */
165 inline int
166 find_page_index(void *addr)
167 {
168     int index = addr-heap_base;
169
170     if (index >= 0) {
171         index = ((unsigned int)index)/4096;
172         if (index < NUM_PAGES)
173             return (index);
174     }
175
176     return (-1);
177 }
178
179 /* a structure to hold the state of a generation */
180 struct generation {
181
182     /* the first page that gc_alloc() checks on its next call */
183     int alloc_start_page;
184
185     /* the first page that gc_alloc_unboxed() checks on its next call */
186     int alloc_unboxed_start_page;
187
188     /* the first page that gc_alloc_large (boxed) considers on its next
189      * call. (Although it always allocates after the boxed_region.) */
190     int alloc_large_start_page;
191
192     /* the first page that gc_alloc_large (unboxed) considers on its
193      * next call. (Although it always allocates after the
194      * current_unboxed_region.) */
195     int alloc_large_unboxed_start_page;
196
197     /* the bytes allocated to this generation */
198     int bytes_allocated;
199
200     /* the number of bytes at which to trigger a GC */
201     int gc_trigger;
202
203     /* to calculate a new level for gc_trigger */
204     int bytes_consed_between_gc;
205
206     /* the number of GCs since the last raise */
207     int num_gc;
208
209     /* the average age after which a GC will raise objects to the
210      * next generation */
211     int trigger_age;
212
213     /* the cumulative sum of the bytes allocated to this generation. It is
214      * cleared after a GC on this generations, and update before new
215      * objects are added from a GC of a younger generation. Dividing by
216      * the bytes_allocated will give the average age of the memory in
217      * this generation since its last GC. */
218     int cum_sum_bytes_allocated;
219
220     /* a minimum average memory age before a GC will occur helps
221      * prevent a GC when a large number of new live objects have been
222      * added, in which case a GC could be a waste of time */
223     double min_av_mem_age;
224 };
225 /* the number of actual generations. (The number of 'struct
226  * generation' objects is one more than this, because one object
227  * serves as scratch when GC'ing.) */
228 #define NUM_GENERATIONS 6
229
230 /* an array of generation structures. There needs to be one more
231  * generation structure than actual generations as the oldest
232  * generation is temporarily raised then lowered. */
233 struct generation generations[NUM_GENERATIONS+1];
234
235 /* the oldest generation that is will currently be GCed by default.
236  * Valid values are: 0, 1, ... (NUM_GENERATIONS-1)
237  *
238  * The default of (NUM_GENERATIONS-1) enables GC on all generations.
239  *
240  * Setting this to 0 effectively disables the generational nature of
241  * the GC. In some applications generational GC may not be useful
242  * because there are no long-lived objects.
243  *
244  * An intermediate value could be handy after moving long-lived data
245  * into an older generation so an unnecessary GC of this long-lived
246  * data can be avoided. */
247 unsigned int  gencgc_oldest_gen_to_gc = NUM_GENERATIONS-1;
248
249 /* The maximum free page in the heap is maintained and used to update
250  * ALLOCATION_POINTER which is used by the room function to limit its
251  * search of the heap. XX Gencgc obviously needs to be better
252  * integrated with the Lisp code. */
253 static int  last_free_page;
254 \f
255 /* This lock is to prevent multiple threads from simultaneously
256  * allocating new regions which overlap each other.  Note that the
257  * majority of GC is single-threaded, but alloc() may be called
258  * from >1 thread at a time and must be thread-safe */
259 static lispobj free_pages_lock=0;
260
261 \f
262 /*
263  * miscellaneous heap functions
264  */
265
266 /* Count the number of pages which are write-protected within the
267  * given generation. */
268 static int
269 count_write_protect_generation_pages(int generation)
270 {
271     int i;
272     int count = 0;
273
274     for (i = 0; i < last_free_page; i++)
275         if ((page_table[i].allocated != FREE_PAGE)
276             && (page_table[i].gen == generation)
277             && (page_table[i].write_protected == 1))
278             count++;
279     return count;
280 }
281
282 /* Count the number of pages within the given generation. */
283 static int
284 count_generation_pages(int generation)
285 {
286     int i;
287     int count = 0;
288
289     for (i = 0; i < last_free_page; i++)
290         if ((page_table[i].allocated != 0)
291             && (page_table[i].gen == generation))
292             count++;
293     return count;
294 }
295
296 /* Count the number of dont_move pages. */
297 static int
298 count_dont_move_pages(void)
299 {
300     int i;
301     int count = 0;
302     for (i = 0; i < last_free_page; i++) {
303         if ((page_table[i].allocated != 0) && (page_table[i].dont_move != 0)) {
304             ++count;
305         }
306     }
307     return count;
308 }
309
310 /* Work through the pages and add up the number of bytes used for the
311  * given generation. */
312 static int
313 count_generation_bytes_allocated (int gen)
314 {
315     int i;
316     int result = 0;
317     for (i = 0; i < last_free_page; i++) {
318         if ((page_table[i].allocated != 0) && (page_table[i].gen == gen))
319             result += page_table[i].bytes_used;
320     }
321     return result;
322 }
323
324 /* Return the average age of the memory in a generation. */
325 static double
326 gen_av_mem_age(int gen)
327 {
328     if (generations[gen].bytes_allocated == 0)
329         return 0.0;
330
331     return
332         ((double)generations[gen].cum_sum_bytes_allocated)
333         / ((double)generations[gen].bytes_allocated);
334 }
335
336 /* The verbose argument controls how much to print: 0 for normal
337  * level of detail; 1 for debugging. */
338 static void
339 print_generation_stats(int verbose) /* FIXME: should take FILE argument */
340 {
341     int i, gens;
342     int fpu_state[27];
343
344     /* This code uses the FP instructions which may be set up for Lisp
345      * so they need to be saved and reset for C. */
346     fpu_save(fpu_state);
347
348     /* number of generations to print */
349     if (verbose)
350         gens = NUM_GENERATIONS+1;
351     else
352         gens = NUM_GENERATIONS;
353
354     /* Print the heap stats. */
355     fprintf(stderr,
356             "   Generation Boxed Unboxed LB   LUB    Alloc  Waste   Trig    WP  GCs Mem-age\n");
357
358     for (i = 0; i < gens; i++) {
359         int j;
360         int boxed_cnt = 0;
361         int unboxed_cnt = 0;
362         int large_boxed_cnt = 0;
363         int large_unboxed_cnt = 0;
364
365         for (j = 0; j < last_free_page; j++)
366             if (page_table[j].gen == i) {
367
368                 /* Count the number of boxed pages within the given
369                  * generation. */
370                 if (page_table[j].allocated & BOXED_PAGE) {
371                     if (page_table[j].large_object)
372                         large_boxed_cnt++;
373                     else
374                         boxed_cnt++;
375                 }
376
377                 /* Count the number of unboxed pages within the given
378                  * generation. */
379                 if (page_table[j].allocated & UNBOXED_PAGE) {
380                     if (page_table[j].large_object)
381                         large_unboxed_cnt++;
382                     else
383                         unboxed_cnt++;
384                 }
385             }
386
387         gc_assert(generations[i].bytes_allocated
388                   == count_generation_bytes_allocated(i));
389         fprintf(stderr,
390                 "   %8d: %5d %5d %5d %5d %8d %5d %8d %4d %3d %7.4f\n",
391                 i,
392                 boxed_cnt, unboxed_cnt, large_boxed_cnt, large_unboxed_cnt,
393                 generations[i].bytes_allocated,
394                 (count_generation_pages(i)*4096
395                  - generations[i].bytes_allocated),
396                 generations[i].gc_trigger,
397                 count_write_protect_generation_pages(i),
398                 generations[i].num_gc,
399                 gen_av_mem_age(i));
400     }
401     fprintf(stderr,"   Total bytes allocated=%ld\n", bytes_allocated);
402
403     fpu_restore(fpu_state);
404 }
405 \f
406 /*
407  * allocation routines
408  */
409
410 /*
411  * To support quick and inline allocation, regions of memory can be
412  * allocated and then allocated from with just a free pointer and a
413  * check against an end address.
414  *
415  * Since objects can be allocated to spaces with different properties
416  * e.g. boxed/unboxed, generation, ages; there may need to be many
417  * allocation regions.
418  *
419  * Each allocation region may be start within a partly used page. Many
420  * features of memory use are noted on a page wise basis, e.g. the
421  * generation; so if a region starts within an existing allocated page
422  * it must be consistent with this page.
423  *
424  * During the scavenging of the newspace, objects will be transported
425  * into an allocation region, and pointers updated to point to this
426  * allocation region. It is possible that these pointers will be
427  * scavenged again before the allocation region is closed, e.g. due to
428  * trans_list which jumps all over the place to cleanup the list. It
429  * is important to be able to determine properties of all objects
430  * pointed to when scavenging, e.g to detect pointers to the oldspace.
431  * Thus it's important that the allocation regions have the correct
432  * properties set when allocated, and not just set when closed. The
433  * region allocation routines return regions with the specified
434  * properties, and grab all the pages, setting their properties
435  * appropriately, except that the amount used is not known.
436  *
437  * These regions are used to support quicker allocation using just a
438  * free pointer. The actual space used by the region is not reflected
439  * in the pages tables until it is closed. It can't be scavenged until
440  * closed.
441  *
442  * When finished with the region it should be closed, which will
443  * update the page tables for the actual space used returning unused
444  * space. Further it may be noted in the new regions which is
445  * necessary when scavenging the newspace.
446  *
447  * Large objects may be allocated directly without an allocation
448  * region, the page tables are updated immediately.
449  *
450  * Unboxed objects don't contain pointers to other objects and so
451  * don't need scavenging. Further they can't contain pointers to
452  * younger generations so WP is not needed. By allocating pages to
453  * unboxed objects the whole page never needs scavenging or
454  * write-protecting. */
455
456 /* We are only using two regions at present. Both are for the current
457  * newspace generation. */
458 struct alloc_region boxed_region;
459 struct alloc_region unboxed_region;
460
461 /* The generation currently being allocated to. */
462 static int gc_alloc_generation;
463
464 /* Find a new region with room for at least the given number of bytes.
465  *
466  * It starts looking at the current generation's alloc_start_page. So
467  * may pick up from the previous region if there is enough space. This
468  * keeps the allocation contiguous when scavenging the newspace.
469  *
470  * The alloc_region should have been closed by a call to
471  * gc_alloc_update_page_tables(), and will thus be in an empty state.
472  *
473  * To assist the scavenging functions write-protected pages are not
474  * used. Free pages should not be write-protected.
475  *
476  * It is critical to the conservative GC that the start of regions be
477  * known. To help achieve this only small regions are allocated at a
478  * time.
479  *
480  * During scavenging, pointers may be found to within the current
481  * region and the page generation must be set so that pointers to the
482  * from space can be recognized. Therefore the generation of pages in
483  * the region are set to gc_alloc_generation. To prevent another
484  * allocation call using the same pages, all the pages in the region
485  * are allocated, although they will initially be empty.
486  */
487 static void
488 gc_alloc_new_region(int nbytes, int unboxed, struct alloc_region *alloc_region)
489 {
490     int first_page;
491     int last_page;
492     int bytes_found;
493     int i;
494
495     /*
496     FSHOW((stderr,
497            "/alloc_new_region for %d bytes from gen %d\n",
498            nbytes, gc_alloc_generation));
499     */
500
501     /* Check that the region is in a reset state. */
502     gc_assert((alloc_region->first_page == 0)
503               && (alloc_region->last_page == -1)
504               && (alloc_region->free_pointer == alloc_region->end_addr));
505     get_spinlock(&free_pages_lock,alloc_region);
506     if (unboxed) {
507         first_page =
508             generations[gc_alloc_generation].alloc_unboxed_start_page;
509     } else {
510         first_page =
511             generations[gc_alloc_generation].alloc_start_page;
512     }
513     last_page=gc_find_freeish_pages(&first_page,nbytes,unboxed,alloc_region);
514     bytes_found=(4096 - page_table[first_page].bytes_used)
515             + 4096*(last_page-first_page);
516
517     /* Set up the alloc_region. */
518     alloc_region->first_page = first_page;
519     alloc_region->last_page = last_page;
520     alloc_region->start_addr = page_table[first_page].bytes_used
521         + page_address(first_page);
522     alloc_region->free_pointer = alloc_region->start_addr;
523     alloc_region->end_addr = alloc_region->start_addr + bytes_found;
524
525     /* Set up the pages. */
526
527     /* The first page may have already been in use. */
528     if (page_table[first_page].bytes_used == 0) {
529         if (unboxed)
530             page_table[first_page].allocated = UNBOXED_PAGE;
531         else
532             page_table[first_page].allocated = BOXED_PAGE;
533         page_table[first_page].gen = gc_alloc_generation;
534         page_table[first_page].large_object = 0;
535         page_table[first_page].first_object_offset = 0;
536     }
537
538     if (unboxed)
539         gc_assert(page_table[first_page].allocated == UNBOXED_PAGE);
540     else
541         gc_assert(page_table[first_page].allocated == BOXED_PAGE);
542     page_table[first_page].allocated |= OPEN_REGION_PAGE; 
543
544     gc_assert(page_table[first_page].gen == gc_alloc_generation);
545     gc_assert(page_table[first_page].large_object == 0);
546
547     for (i = first_page+1; i <= last_page; i++) {
548         if (unboxed)
549             page_table[i].allocated = UNBOXED_PAGE;
550         else
551             page_table[i].allocated = BOXED_PAGE;
552         page_table[i].gen = gc_alloc_generation;
553         page_table[i].large_object = 0;
554         /* This may not be necessary for unboxed regions (think it was
555          * broken before!) */
556         page_table[i].first_object_offset =
557             alloc_region->start_addr - page_address(i);
558         page_table[i].allocated |= OPEN_REGION_PAGE ;
559     }
560     /* Bump up last_free_page. */
561     if (last_page+1 > last_free_page) {
562         last_free_page = last_page+1;
563         SetSymbolValue(ALLOCATION_POINTER,
564                        (lispobj)(((char *)heap_base) + last_free_page*4096),
565                        0);
566     }
567     free_pages_lock=0;
568     
569     /* we can do this after releasing free_pages_lock */
570     if (gencgc_zero_check) {
571         int *p;
572         for (p = (int *)alloc_region->start_addr;
573              p < (int *)alloc_region->end_addr; p++) {
574             if (*p != 0) {
575                 /* KLUDGE: It would be nice to use %lx and explicit casts
576                  * (long) in code like this, so that it is less likely to
577                  * break randomly when running on a machine with different
578                  * word sizes. -- WHN 19991129 */
579                 lose("The new region at %x is not zero.", p);
580             }
581     }
582 }
583
584 }
585
586 /* If the record_new_objects flag is 2 then all new regions created
587  * are recorded.
588  *
589  * If it's 1 then then it is only recorded if the first page of the
590  * current region is <= new_areas_ignore_page. This helps avoid
591  * unnecessary recording when doing full scavenge pass.
592  *
593  * The new_object structure holds the page, byte offset, and size of
594  * new regions of objects. Each new area is placed in the array of
595  * these structures pointer to by new_areas. new_areas_index holds the
596  * offset into new_areas.
597  *
598  * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
599  * later code must detect this and handle it, probably by doing a full
600  * scavenge of a generation. */
601 #define NUM_NEW_AREAS 512
602 static int record_new_objects = 0;
603 static int new_areas_ignore_page;
604 struct new_area {
605     int  page;
606     int  offset;
607     int  size;
608 };
609 static struct new_area (*new_areas)[];
610 static int new_areas_index;
611 int max_new_areas;
612
613 /* Add a new area to new_areas. */
614 static void
615 add_new_area(int first_page, int offset, int size)
616 {
617     unsigned new_area_start,c;
618     int i;
619
620     /* Ignore if full. */
621     if (new_areas_index >= NUM_NEW_AREAS)
622         return;
623
624     switch (record_new_objects) {
625     case 0:
626         return;
627     case 1:
628         if (first_page > new_areas_ignore_page)
629             return;
630         break;
631     case 2:
632         break;
633     default:
634         gc_abort();
635     }
636
637     new_area_start = 4096*first_page + offset;
638
639     /* Search backwards for a prior area that this follows from. If
640        found this will save adding a new area. */
641     for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
642         unsigned area_end =
643             4096*((*new_areas)[i].page)
644             + (*new_areas)[i].offset
645             + (*new_areas)[i].size;
646         /*FSHOW((stderr,
647                "/add_new_area S1 %d %d %d %d\n",
648                i, c, new_area_start, area_end));*/
649         if (new_area_start == area_end) {
650             /*FSHOW((stderr,
651                    "/adding to [%d] %d %d %d with %d %d %d:\n",
652                    i,
653                    (*new_areas)[i].page,
654                    (*new_areas)[i].offset,
655                    (*new_areas)[i].size,
656                    first_page,
657                    offset,
658                     size);*/
659             (*new_areas)[i].size += size;
660             return;
661         }
662     }
663
664     (*new_areas)[new_areas_index].page = first_page;
665     (*new_areas)[new_areas_index].offset = offset;
666     (*new_areas)[new_areas_index].size = size;
667     /*FSHOW((stderr,
668            "/new_area %d page %d offset %d size %d\n",
669            new_areas_index, first_page, offset, size));*/
670     new_areas_index++;
671
672     /* Note the max new_areas used. */
673     if (new_areas_index > max_new_areas)
674         max_new_areas = new_areas_index;
675 }
676
677 /* Update the tables for the alloc_region. The region maybe added to
678  * the new_areas.
679  *
680  * When done the alloc_region is set up so that the next quick alloc
681  * will fail safely and thus a new region will be allocated. Further
682  * it is safe to try to re-update the page table of this reset
683  * alloc_region. */
684 void
685 gc_alloc_update_page_tables(int unboxed, struct alloc_region *alloc_region)
686 {
687     int more;
688     int first_page;
689     int next_page;
690     int bytes_used;
691     int orig_first_page_bytes_used;
692     int region_size;
693     int byte_cnt;
694
695     /*
696     FSHOW((stderr,
697            "/gc_alloc_update_page_tables() to gen %d:\n",
698            gc_alloc_generation));
699     */
700
701     first_page = alloc_region->first_page;
702
703     /* Catch an unused alloc_region. */
704     if ((first_page == 0) && (alloc_region->last_page == -1))
705         return;
706
707     next_page = first_page+1;
708
709     /* Skip if no bytes were allocated. */
710     if (alloc_region->free_pointer != alloc_region->start_addr) {
711         orig_first_page_bytes_used = page_table[first_page].bytes_used;
712
713         gc_assert(alloc_region->start_addr == (page_address(first_page) + page_table[first_page].bytes_used));
714
715         /* All the pages used need to be updated */
716
717         /* Update the first page. */
718
719         /* If the page was free then set up the gen, and
720          * first_object_offset. */
721         if (page_table[first_page].bytes_used == 0)
722             gc_assert(page_table[first_page].first_object_offset == 0);
723         page_table[first_page].allocated &= ~(OPEN_REGION_PAGE);
724
725         if (unboxed)
726             gc_assert(page_table[first_page].allocated == UNBOXED_PAGE);
727         else
728             gc_assert(page_table[first_page].allocated == BOXED_PAGE);
729         gc_assert(page_table[first_page].gen == gc_alloc_generation);
730         gc_assert(page_table[first_page].large_object == 0);
731
732         byte_cnt = 0;
733
734         /* Calculate the number of bytes used in this page. This is not
735          * always the number of new bytes, unless it was free. */
736         more = 0;
737         if ((bytes_used = (alloc_region->free_pointer - page_address(first_page)))>4096) {
738             bytes_used = 4096;
739             more = 1;
740         }
741         page_table[first_page].bytes_used = bytes_used;
742         byte_cnt += bytes_used;
743
744
745         /* All the rest of the pages should be free. We need to set their
746          * first_object_offset pointer to the start of the region, and set
747          * the bytes_used. */
748         while (more) {
749             page_table[next_page].allocated &= ~(OPEN_REGION_PAGE);
750             if (unboxed)
751                 gc_assert(page_table[next_page].allocated == UNBOXED_PAGE);
752             else
753                 gc_assert(page_table[next_page].allocated == BOXED_PAGE);
754             gc_assert(page_table[next_page].bytes_used == 0);
755             gc_assert(page_table[next_page].gen == gc_alloc_generation);
756             gc_assert(page_table[next_page].large_object == 0);
757
758             gc_assert(page_table[next_page].first_object_offset ==
759                       alloc_region->start_addr - page_address(next_page));
760
761             /* Calculate the number of bytes used in this page. */
762             more = 0;
763             if ((bytes_used = (alloc_region->free_pointer
764                                - page_address(next_page)))>4096) {
765                 bytes_used = 4096;
766                 more = 1;
767             }
768             page_table[next_page].bytes_used = bytes_used;
769             byte_cnt += bytes_used;
770
771             next_page++;
772         }
773
774         region_size = alloc_region->free_pointer - alloc_region->start_addr;
775         bytes_allocated += region_size;
776         generations[gc_alloc_generation].bytes_allocated += region_size;
777
778         gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
779
780         /* Set the generations alloc restart page to the last page of
781          * the region. */
782         if (unboxed)
783             generations[gc_alloc_generation].alloc_unboxed_start_page =
784                 next_page-1;
785         else
786             generations[gc_alloc_generation].alloc_start_page = next_page-1;
787
788         /* Add the region to the new_areas if requested. */
789         if (!unboxed)
790             add_new_area(first_page,orig_first_page_bytes_used, region_size);
791
792         /*
793         FSHOW((stderr,
794                "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
795                region_size,
796                gc_alloc_generation));
797         */
798     } else {
799         /* There are no bytes allocated. Unallocate the first_page if
800          * there are 0 bytes_used. */
801         page_table[first_page].allocated &= ~(OPEN_REGION_PAGE);
802         if (page_table[first_page].bytes_used == 0)
803             page_table[first_page].allocated = FREE_PAGE;
804     }
805
806     /* Unallocate any unused pages. */
807     while (next_page <= alloc_region->last_page) {
808         gc_assert(page_table[next_page].bytes_used == 0);
809         page_table[next_page].allocated = FREE_PAGE;
810         next_page++;
811     }
812
813     gc_set_region_empty(alloc_region);
814 }
815
816 static inline void *gc_quick_alloc(int nbytes);
817
818 /* Allocate a possibly large object. */
819 void *
820 gc_alloc_large(int nbytes, int unboxed, struct alloc_region *alloc_region)
821 {
822     int first_page;
823     int last_page;
824     int orig_first_page_bytes_used;
825     int byte_cnt;
826     int more;
827     int bytes_used;
828     int next_page;
829     int large = (nbytes >= large_object_size);
830
831     /*
832     if (nbytes > 200000)
833         FSHOW((stderr, "/alloc_large %d\n", nbytes));
834     */
835
836     /*
837     FSHOW((stderr,
838            "/gc_alloc_large() for %d bytes from gen %d\n",
839            nbytes, gc_alloc_generation));
840     */
841
842     /* If the object is small, and there is room in the current region
843        then allocate it in the current region. */
844     if (!large
845         && ((alloc_region->end_addr-alloc_region->free_pointer) >= nbytes))
846         return gc_quick_alloc(nbytes);
847
848     /* To allow the allocation of small objects without the danger of
849        using a page in the current boxed region, the search starts after
850        the current boxed free region. XX could probably keep a page
851        index ahead of the current region and bumped up here to save a
852        lot of re-scanning. */
853
854     get_spinlock(&free_pages_lock,alloc_region);
855
856     if (unboxed) {
857         first_page =
858             generations[gc_alloc_generation].alloc_large_unboxed_start_page;
859     } else {
860         first_page = generations[gc_alloc_generation].alloc_large_start_page;
861     }
862     if (first_page <= alloc_region->last_page) {
863         first_page = alloc_region->last_page+1;
864     }
865
866     last_page=gc_find_freeish_pages(&first_page,nbytes,unboxed,0);
867
868     gc_assert(first_page > alloc_region->last_page);
869     if (unboxed)
870         generations[gc_alloc_generation].alloc_large_unboxed_start_page =
871             last_page;
872     else
873         generations[gc_alloc_generation].alloc_large_start_page = last_page;
874
875     /* Set up the pages. */
876     orig_first_page_bytes_used = page_table[first_page].bytes_used;
877
878     /* If the first page was free then set up the gen, and
879      * first_object_offset. */
880     if (page_table[first_page].bytes_used == 0) {
881         if (unboxed)
882             page_table[first_page].allocated = UNBOXED_PAGE;
883         else
884             page_table[first_page].allocated = BOXED_PAGE;
885         page_table[first_page].gen = gc_alloc_generation;
886         page_table[first_page].first_object_offset = 0;
887         page_table[first_page].large_object = large;
888     }
889
890     if (unboxed)
891         gc_assert(page_table[first_page].allocated == UNBOXED_PAGE);
892     else
893         gc_assert(page_table[first_page].allocated == BOXED_PAGE);
894     gc_assert(page_table[first_page].gen == gc_alloc_generation);
895     gc_assert(page_table[first_page].large_object == large);
896
897     byte_cnt = 0;
898
899     /* Calc. the number of bytes used in this page. This is not
900      * always the number of new bytes, unless it was free. */
901     more = 0;
902     if ((bytes_used = nbytes+orig_first_page_bytes_used) > 4096) {
903         bytes_used = 4096;
904         more = 1;
905     }
906     page_table[first_page].bytes_used = bytes_used;
907     byte_cnt += bytes_used;
908
909     next_page = first_page+1;
910
911     /* All the rest of the pages should be free. We need to set their
912      * first_object_offset pointer to the start of the region, and
913      * set the bytes_used. */
914     while (more) {
915         gc_assert(page_table[next_page].allocated == FREE_PAGE);
916         gc_assert(page_table[next_page].bytes_used == 0);
917         if (unboxed)
918             page_table[next_page].allocated = UNBOXED_PAGE;
919         else
920             page_table[next_page].allocated = BOXED_PAGE;
921         page_table[next_page].gen = gc_alloc_generation;
922         page_table[next_page].large_object = large;
923
924         page_table[next_page].first_object_offset =
925             orig_first_page_bytes_used - 4096*(next_page-first_page);
926
927         /* Calculate the number of bytes used in this page. */
928         more = 0;
929         if ((bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt) > 4096) {
930             bytes_used = 4096;
931             more = 1;
932         }
933         page_table[next_page].bytes_used = bytes_used;
934         byte_cnt += bytes_used;
935
936         next_page++;
937     }
938
939     gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
940
941     bytes_allocated += nbytes;
942     generations[gc_alloc_generation].bytes_allocated += nbytes;
943
944     /* Add the region to the new_areas if requested. */
945     if (!unboxed)
946         add_new_area(first_page,orig_first_page_bytes_used,nbytes);
947
948     /* Bump up last_free_page */
949     if (last_page+1 > last_free_page) {
950         last_free_page = last_page+1;
951         SetSymbolValue(ALLOCATION_POINTER,
952                        (lispobj)(((char *)heap_base) + last_free_page*4096),0);
953     }
954     free_pages_lock=0;
955
956     return((void *)(page_address(first_page)+orig_first_page_bytes_used));
957 }
958
959 int
960 gc_find_freeish_pages(int *restart_page_ptr, int nbytes, int unboxed, struct alloc_region *alloc_region)
961 {
962     /* if alloc_region is 0, we assume this is for a potentially large
963        object */
964     int first_page;
965     int last_page;
966     int region_size;
967     int restart_page=*restart_page_ptr;
968     int bytes_found;
969     int num_pages;
970     int large = !alloc_region && (nbytes >= large_object_size);
971
972     gc_assert(free_pages_lock);
973     /* Search for a contiguous free space of at least nbytes. If it's a
974        large object then align it on a page boundary by searching for a
975        free page. */
976
977     /* To allow the allocation of small objects without the danger of
978        using a page in the current boxed region, the search starts after
979        the current boxed free region. XX could probably keep a page
980        index ahead of the current region and bumped up here to save a
981        lot of re-scanning. */
982
983     do {
984         first_page = restart_page;
985         if (large)              
986             while ((first_page < NUM_PAGES)
987                    && (page_table[first_page].allocated != FREE_PAGE))
988                 first_page++;
989         else
990             while (first_page < NUM_PAGES) {
991                 if(page_table[first_page].allocated == FREE_PAGE)
992                     break;
993                 /* I don't know why we need the gen=0 test, but it
994                  * breaks randomly if that's omitted -dan 2003.02.26
995                  */
996                 if((page_table[first_page].allocated ==
997                     (unboxed ? UNBOXED_PAGE : BOXED_PAGE)) &&
998                    (page_table[first_page].large_object == 0) &&
999                    (gc_alloc_generation == 0) &&
1000                    (page_table[first_page].gen == gc_alloc_generation) &&
1001                    (page_table[first_page].bytes_used < (4096-32)) &&
1002                    (page_table[first_page].write_protected == 0) &&
1003                    (page_table[first_page].dont_move == 0))
1004                     break;
1005                 first_page++;
1006             }
1007         
1008         if (first_page >= NUM_PAGES) {
1009             fprintf(stderr,
1010                     "Argh! gc_find_free_space failed (first_page), nbytes=%d.\n",
1011                     nbytes);
1012             print_generation_stats(1);
1013             lose(NULL);
1014         }
1015
1016         gc_assert(page_table[first_page].write_protected == 0);
1017
1018         last_page = first_page;
1019         bytes_found = 4096 - page_table[first_page].bytes_used;
1020         num_pages = 1;
1021         while (((bytes_found < nbytes) 
1022                 || (alloc_region && (num_pages < 2)))
1023                && (last_page < (NUM_PAGES-1))
1024                && (page_table[last_page+1].allocated == FREE_PAGE)) {
1025             last_page++;
1026             num_pages++;
1027             bytes_found += 4096;
1028             gc_assert(page_table[last_page].write_protected == 0);
1029         }
1030
1031         region_size = (4096 - page_table[first_page].bytes_used)
1032             + 4096*(last_page-first_page);
1033
1034         gc_assert(bytes_found == region_size);
1035         restart_page = last_page + 1;
1036     } while ((restart_page < NUM_PAGES) && (bytes_found < nbytes));
1037
1038     /* Check for a failure */
1039     if ((restart_page >= NUM_PAGES) && (bytes_found < nbytes)) {
1040         fprintf(stderr,
1041                 "Argh! gc_find_freeish_pages failed (restart_page), nbytes=%d.\n",
1042                 nbytes);
1043         print_generation_stats(1);
1044         lose(NULL);
1045     }
1046     *restart_page_ptr=first_page;
1047     return last_page;
1048 }
1049
1050 /* Allocate bytes.  All the rest of the special-purpose allocation
1051  * functions will eventually call this (instead of just duplicating
1052  * parts of its code) */
1053
1054 void *
1055 gc_alloc_with_region(int nbytes,int unboxed_p, struct alloc_region *my_region,
1056                      int quick_p)
1057 {
1058     void *new_free_pointer;
1059
1060     /* FSHOW((stderr, "/gc_alloc %d\n", nbytes)); */
1061
1062     /* Check whether there is room in the current alloc region. */
1063     new_free_pointer = my_region->free_pointer + nbytes;
1064
1065     if (new_free_pointer <= my_region->end_addr) {
1066         /* If so then allocate from the current alloc region. */
1067         void *new_obj = my_region->free_pointer;
1068         my_region->free_pointer = new_free_pointer;
1069
1070         /* Unless a `quick' alloc was requested, check whether the
1071            alloc region is almost empty. */
1072         if (!quick_p &&
1073             (my_region->end_addr - my_region->free_pointer) <= 32) {
1074             /* If so, finished with the current region. */
1075             gc_alloc_update_page_tables(unboxed_p, my_region);
1076             /* Set up a new region. */
1077             gc_alloc_new_region(32 /*bytes*/, unboxed_p, my_region);
1078         }
1079
1080         return((void *)new_obj);
1081     }
1082
1083     /* Else not enough free space in the current region. */
1084
1085     /* If there some room left in the current region, enough to be worth
1086      * saving, then allocate a large object. */
1087     /* FIXME: "32" should be a named parameter. */
1088     if ((my_region->end_addr-my_region->free_pointer) > 32)
1089         return gc_alloc_large(nbytes, unboxed_p, my_region);
1090
1091     /* Else find a new region. */
1092
1093     /* Finished with the current region. */
1094     gc_alloc_update_page_tables(unboxed_p, my_region);
1095
1096     /* Set up a new region. */
1097     gc_alloc_new_region(nbytes, unboxed_p, my_region);
1098
1099     /* Should now be enough room. */
1100
1101     /* Check whether there is room in the current region. */
1102     new_free_pointer = my_region->free_pointer + nbytes;
1103
1104     if (new_free_pointer <= my_region->end_addr) {
1105         /* If so then allocate from the current region. */
1106         void *new_obj = my_region->free_pointer;
1107         my_region->free_pointer = new_free_pointer;
1108         /* Check whether the current region is almost empty. */
1109         if ((my_region->end_addr - my_region->free_pointer) <= 32) {
1110             /* If so find, finished with the current region. */
1111             gc_alloc_update_page_tables(unboxed_p, my_region);
1112
1113             /* Set up a new region. */
1114             gc_alloc_new_region(32, unboxed_p, my_region);
1115         }
1116
1117         return((void *)new_obj);
1118     }
1119
1120     /* shouldn't happen */
1121     gc_assert(0);
1122     return((void *) NIL); /* dummy value: return something ... */
1123 }
1124
1125 void *
1126 gc_general_alloc(int nbytes,int unboxed_p,int quick_p)
1127 {
1128     struct alloc_region *my_region = 
1129       unboxed_p ? &unboxed_region : &boxed_region;
1130     return gc_alloc_with_region(nbytes,unboxed_p, my_region,quick_p);
1131 }
1132
1133
1134
1135 static void *
1136 gc_alloc(int nbytes,int unboxed_p)
1137 {
1138     /* this is the only function that the external interface to
1139      * allocation presently knows how to call: Lisp code will never
1140      * allocate large objects, or to unboxed space, or `quick'ly.
1141      * Any of that stuff will only ever happen inside of GC */
1142     return gc_general_alloc(nbytes,unboxed_p,0);
1143 }
1144
1145 /* Allocate space from the boxed_region. If there is not enough free
1146  * space then call gc_alloc to do the job. A pointer to the start of
1147  * the object is returned. */
1148 static inline void *
1149 gc_quick_alloc(int nbytes)
1150 {
1151     return gc_general_alloc(nbytes,ALLOC_BOXED,ALLOC_QUICK);
1152 }
1153
1154 /* Allocate space for the possibly large boxed object. If it is a
1155  * large object then do a large alloc else use gc_quick_alloc.  Note
1156  * that gc_quick_alloc will eventually fall through to
1157  * gc_general_alloc which may allocate the object in a large way
1158  * anyway, but based on decisions about the free space in the current
1159  * region, not the object size itself */
1160
1161 static inline void *
1162 gc_quick_alloc_large(int nbytes)
1163 {
1164     if (nbytes >= large_object_size)
1165         return gc_alloc_large(nbytes, ALLOC_BOXED, &boxed_region);
1166     else
1167         return gc_general_alloc(nbytes,ALLOC_BOXED,ALLOC_QUICK);
1168 }
1169
1170 static inline void *
1171 gc_alloc_unboxed(int nbytes)
1172 {
1173     return gc_general_alloc(nbytes,ALLOC_UNBOXED,0);
1174 }
1175
1176 static inline void *
1177 gc_quick_alloc_unboxed(int nbytes)
1178 {
1179     return gc_general_alloc(nbytes,ALLOC_UNBOXED,ALLOC_QUICK);
1180 }
1181
1182 /* Allocate space for the object. If it is a large object then do a
1183  * large alloc else allocate from the current region. If there is not
1184  * enough free space then call general gc_alloc_unboxed() to do the job.
1185  *
1186  * A pointer to the start of the object is returned. */
1187 static inline void *
1188 gc_quick_alloc_large_unboxed(int nbytes)
1189 {
1190     if (nbytes >= large_object_size)
1191         return gc_alloc_large(nbytes,ALLOC_UNBOXED,&unboxed_region);
1192     else
1193         return gc_quick_alloc_unboxed(nbytes);
1194 }
1195 \f
1196 /*
1197  * scavenging/transporting routines derived from gc.c in CMU CL ca. 18b
1198  */
1199
1200 extern int (*scavtab[256])(lispobj *where, lispobj object);
1201 extern lispobj (*transother[256])(lispobj object);
1202 extern int (*sizetab[256])(lispobj *where);
1203
1204 /* Copy a large boxed object. If the object is in a large object
1205  * region then it is simply promoted, else it is copied. If it's large
1206  * enough then it's copied to a large object region.
1207  *
1208  * Vectors may have shrunk. If the object is not copied the space
1209  * needs to be reclaimed, and the page_tables corrected. */
1210 lispobj
1211 copy_large_object(lispobj object, int nwords)
1212 {
1213     int tag;
1214     lispobj *new;
1215     lispobj *source, *dest;
1216     int first_page;
1217
1218     gc_assert(is_lisp_pointer(object));
1219     gc_assert(from_space_p(object));
1220     gc_assert((nwords & 0x01) == 0);
1221
1222
1223     /* Check whether it's a large object. */
1224     first_page = find_page_index((void *)object);
1225     gc_assert(first_page >= 0);
1226
1227     if (page_table[first_page].large_object) {
1228
1229         /* Promote the object. */
1230
1231         int remaining_bytes;
1232         int next_page;
1233         int bytes_freed;
1234         int old_bytes_used;
1235
1236         /* Note: Any page write-protection must be removed, else a
1237          * later scavenge_newspace may incorrectly not scavenge these
1238          * pages. This would not be necessary if they are added to the
1239          * new areas, but let's do it for them all (they'll probably
1240          * be written anyway?). */
1241
1242         gc_assert(page_table[first_page].first_object_offset == 0);
1243
1244         next_page = first_page;
1245         remaining_bytes = nwords*4;
1246         while (remaining_bytes > 4096) {
1247             gc_assert(page_table[next_page].gen == from_space);
1248             gc_assert(page_table[next_page].allocated == BOXED_PAGE);
1249             gc_assert(page_table[next_page].large_object);
1250             gc_assert(page_table[next_page].first_object_offset==
1251                       -4096*(next_page-first_page));
1252             gc_assert(page_table[next_page].bytes_used == 4096);
1253
1254             page_table[next_page].gen = new_space;
1255
1256             /* Remove any write-protection. We should be able to rely
1257              * on the write-protect flag to avoid redundant calls. */
1258             if (page_table[next_page].write_protected) {
1259                 os_protect(page_address(next_page), 4096, OS_VM_PROT_ALL);
1260                 page_table[next_page].write_protected = 0;
1261             }
1262             remaining_bytes -= 4096;
1263             next_page++;
1264         }
1265
1266         /* Now only one page remains, but the object may have shrunk
1267          * so there may be more unused pages which will be freed. */
1268
1269         /* The object may have shrunk but shouldn't have grown. */
1270         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1271
1272         page_table[next_page].gen = new_space;
1273         gc_assert(page_table[next_page].allocated == BOXED_PAGE);
1274
1275         /* Adjust the bytes_used. */
1276         old_bytes_used = page_table[next_page].bytes_used;
1277         page_table[next_page].bytes_used = remaining_bytes;
1278
1279         bytes_freed = old_bytes_used - remaining_bytes;
1280
1281         /* Free any remaining pages; needs care. */
1282         next_page++;
1283         while ((old_bytes_used == 4096) &&
1284                (page_table[next_page].gen == from_space) &&
1285                (page_table[next_page].allocated == BOXED_PAGE) &&
1286                page_table[next_page].large_object &&
1287                (page_table[next_page].first_object_offset ==
1288                 -(next_page - first_page)*4096)) {
1289             /* Checks out OK, free the page. Don't need to bother zeroing
1290              * pages as this should have been done before shrinking the
1291              * object. These pages shouldn't be write-protected as they
1292              * should be zero filled. */
1293             gc_assert(page_table[next_page].write_protected == 0);
1294
1295             old_bytes_used = page_table[next_page].bytes_used;
1296             page_table[next_page].allocated = FREE_PAGE;
1297             page_table[next_page].bytes_used = 0;
1298             bytes_freed += old_bytes_used;
1299             next_page++;
1300         }
1301
1302         generations[from_space].bytes_allocated -= 4*nwords + bytes_freed;
1303         generations[new_space].bytes_allocated += 4*nwords;
1304         bytes_allocated -= bytes_freed;
1305
1306         /* Add the region to the new_areas if requested. */
1307         add_new_area(first_page,0,nwords*4);
1308
1309         return(object);
1310     } else {
1311         /* Get tag of object. */
1312         tag = lowtag_of(object);
1313
1314         /* Allocate space. */
1315         new = gc_quick_alloc_large(nwords*4);
1316
1317         dest = new;
1318         source = (lispobj *) native_pointer(object);
1319
1320         /* Copy the object. */
1321         while (nwords > 0) {
1322             dest[0] = source[0];
1323             dest[1] = source[1];
1324             dest += 2;
1325             source += 2;
1326             nwords -= 2;
1327         }
1328
1329         /* Return Lisp pointer of new object. */
1330         return ((lispobj) new) | tag;
1331     }
1332 }
1333
1334 /* to copy unboxed objects */
1335 lispobj
1336 copy_unboxed_object(lispobj object, int nwords)
1337 {
1338     int tag;
1339     lispobj *new;
1340     lispobj *source, *dest;
1341
1342     gc_assert(is_lisp_pointer(object));
1343     gc_assert(from_space_p(object));
1344     gc_assert((nwords & 0x01) == 0);
1345
1346     /* Get tag of object. */
1347     tag = lowtag_of(object);
1348
1349     /* Allocate space. */
1350     new = gc_quick_alloc_unboxed(nwords*4);
1351
1352     dest = new;
1353     source = (lispobj *) native_pointer(object);
1354
1355     /* Copy the object. */
1356     while (nwords > 0) {
1357         dest[0] = source[0];
1358         dest[1] = source[1];
1359         dest += 2;
1360         source += 2;
1361         nwords -= 2;
1362     }
1363
1364     /* Return Lisp pointer of new object. */
1365     return ((lispobj) new) | tag;
1366 }
1367
1368 /* to copy large unboxed objects
1369  *
1370  * If the object is in a large object region then it is simply
1371  * promoted, else it is copied. If it's large enough then it's copied
1372  * to a large object region.
1373  *
1374  * Bignums and vectors may have shrunk. If the object is not copied
1375  * the space needs to be reclaimed, and the page_tables corrected.
1376  *
1377  * KLUDGE: There's a lot of cut-and-paste duplication between this
1378  * function and copy_large_object(..). -- WHN 20000619 */
1379 lispobj
1380 copy_large_unboxed_object(lispobj object, int nwords)
1381 {
1382     int tag;
1383     lispobj *new;
1384     lispobj *source, *dest;
1385     int first_page;
1386
1387     gc_assert(is_lisp_pointer(object));
1388     gc_assert(from_space_p(object));
1389     gc_assert((nwords & 0x01) == 0);
1390
1391     if ((nwords > 1024*1024) && gencgc_verbose)
1392         FSHOW((stderr, "/copy_large_unboxed_object: %d bytes\n", nwords*4));
1393
1394     /* Check whether it's a large object. */
1395     first_page = find_page_index((void *)object);
1396     gc_assert(first_page >= 0);
1397
1398     if (page_table[first_page].large_object) {
1399         /* Promote the object. Note: Unboxed objects may have been
1400          * allocated to a BOXED region so it may be necessary to
1401          * change the region to UNBOXED. */
1402         int remaining_bytes;
1403         int next_page;
1404         int bytes_freed;
1405         int old_bytes_used;
1406
1407         gc_assert(page_table[first_page].first_object_offset == 0);
1408
1409         next_page = first_page;
1410         remaining_bytes = nwords*4;
1411         while (remaining_bytes > 4096) {
1412             gc_assert(page_table[next_page].gen == from_space);
1413             gc_assert((page_table[next_page].allocated == UNBOXED_PAGE)
1414                       || (page_table[next_page].allocated == BOXED_PAGE));
1415             gc_assert(page_table[next_page].large_object);
1416             gc_assert(page_table[next_page].first_object_offset==
1417                       -4096*(next_page-first_page));
1418             gc_assert(page_table[next_page].bytes_used == 4096);
1419
1420             page_table[next_page].gen = new_space;
1421             page_table[next_page].allocated = UNBOXED_PAGE;
1422             remaining_bytes -= 4096;
1423             next_page++;
1424         }
1425
1426         /* Now only one page remains, but the object may have shrunk so
1427          * there may be more unused pages which will be freed. */
1428
1429         /* Object may have shrunk but shouldn't have grown - check. */
1430         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1431
1432         page_table[next_page].gen = new_space;
1433         page_table[next_page].allocated = UNBOXED_PAGE;
1434
1435         /* Adjust the bytes_used. */
1436         old_bytes_used = page_table[next_page].bytes_used;
1437         page_table[next_page].bytes_used = remaining_bytes;
1438
1439         bytes_freed = old_bytes_used - remaining_bytes;
1440
1441         /* Free any remaining pages; needs care. */
1442         next_page++;
1443         while ((old_bytes_used == 4096) &&
1444                (page_table[next_page].gen == from_space) &&
1445                ((page_table[next_page].allocated == UNBOXED_PAGE)
1446                 || (page_table[next_page].allocated == BOXED_PAGE)) &&
1447                page_table[next_page].large_object &&
1448                (page_table[next_page].first_object_offset ==
1449                 -(next_page - first_page)*4096)) {
1450             /* Checks out OK, free the page. Don't need to both zeroing
1451              * pages as this should have been done before shrinking the
1452              * object. These pages shouldn't be write-protected, even if
1453              * boxed they should be zero filled. */
1454             gc_assert(page_table[next_page].write_protected == 0);
1455
1456             old_bytes_used = page_table[next_page].bytes_used;
1457             page_table[next_page].allocated = FREE_PAGE;
1458             page_table[next_page].bytes_used = 0;
1459             bytes_freed += old_bytes_used;
1460             next_page++;
1461         }
1462
1463         if ((bytes_freed > 0) && gencgc_verbose)
1464             FSHOW((stderr,
1465                    "/copy_large_unboxed bytes_freed=%d\n",
1466                    bytes_freed));
1467
1468         generations[from_space].bytes_allocated -= 4*nwords + bytes_freed;
1469         generations[new_space].bytes_allocated += 4*nwords;
1470         bytes_allocated -= bytes_freed;
1471
1472         return(object);
1473     }
1474     else {
1475         /* Get tag of object. */
1476         tag = lowtag_of(object);
1477
1478         /* Allocate space. */
1479         new = gc_quick_alloc_large_unboxed(nwords*4);
1480
1481         dest = new;
1482         source = (lispobj *) native_pointer(object);
1483
1484         /* Copy the object. */
1485         while (nwords > 0) {
1486             dest[0] = source[0];
1487             dest[1] = source[1];
1488             dest += 2;
1489             source += 2;
1490             nwords -= 2;
1491         }
1492
1493         /* Return Lisp pointer of new object. */
1494         return ((lispobj) new) | tag;
1495     }
1496 }
1497
1498
1499
1500 \f
1501
1502 /*
1503  * code and code-related objects
1504  */
1505 /*
1506 static lispobj trans_fun_header(lispobj object);
1507 static lispobj trans_boxed(lispobj object);
1508 */
1509
1510 /* Scan a x86 compiled code object, looking for possible fixups that
1511  * have been missed after a move.
1512  *
1513  * Two types of fixups are needed:
1514  * 1. Absolute fixups to within the code object.
1515  * 2. Relative fixups to outside the code object.
1516  *
1517  * Currently only absolute fixups to the constant vector, or to the
1518  * code area are checked. */
1519 void
1520 sniff_code_object(struct code *code, unsigned displacement)
1521 {
1522     int nheader_words, ncode_words, nwords;
1523     void *p;
1524     void *constants_start_addr, *constants_end_addr;
1525     void *code_start_addr, *code_end_addr;
1526     int fixup_found = 0;
1527
1528     if (!check_code_fixups)
1529         return;
1530
1531     ncode_words = fixnum_value(code->code_size);
1532     nheader_words = HeaderValue(*(lispobj *)code);
1533     nwords = ncode_words + nheader_words;
1534
1535     constants_start_addr = (void *)code + 5*4;
1536     constants_end_addr = (void *)code + nheader_words*4;
1537     code_start_addr = (void *)code + nheader_words*4;
1538     code_end_addr = (void *)code + nwords*4;
1539
1540     /* Work through the unboxed code. */
1541     for (p = code_start_addr; p < code_end_addr; p++) {
1542         void *data = *(void **)p;
1543         unsigned d1 = *((unsigned char *)p - 1);
1544         unsigned d2 = *((unsigned char *)p - 2);
1545         unsigned d3 = *((unsigned char *)p - 3);
1546         unsigned d4 = *((unsigned char *)p - 4);
1547 #if QSHOW
1548         unsigned d5 = *((unsigned char *)p - 5);
1549         unsigned d6 = *((unsigned char *)p - 6);
1550 #endif
1551
1552         /* Check for code references. */
1553         /* Check for a 32 bit word that looks like an absolute
1554            reference to within the code adea of the code object. */
1555         if ((data >= (code_start_addr-displacement))
1556             && (data < (code_end_addr-displacement))) {
1557             /* function header */
1558             if ((d4 == 0x5e)
1559                 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) == (unsigned)code)) {
1560                 /* Skip the function header */
1561                 p += 6*4 - 4 - 1;
1562                 continue;
1563             }
1564             /* the case of PUSH imm32 */
1565             if (d1 == 0x68) {
1566                 fixup_found = 1;
1567                 FSHOW((stderr,
1568                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1569                        p, d6, d5, d4, d3, d2, d1, data));
1570                 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1571             }
1572             /* the case of MOV [reg-8],imm32 */
1573             if ((d3 == 0xc7)
1574                 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1575                     || d2==0x45 || d2==0x46 || d2==0x47)
1576                 && (d1 == 0xf8)) {
1577                 fixup_found = 1;
1578                 FSHOW((stderr,
1579                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1580                        p, d6, d5, d4, d3, d2, d1, data));
1581                 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1582             }
1583             /* the case of LEA reg,[disp32] */
1584             if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1585                 fixup_found = 1;
1586                 FSHOW((stderr,
1587                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1588                        p, d6, d5, d4, d3, d2, d1, data));
1589                 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1590             }
1591         }
1592
1593         /* Check for constant references. */
1594         /* Check for a 32 bit word that looks like an absolute
1595            reference to within the constant vector. Constant references
1596            will be aligned. */
1597         if ((data >= (constants_start_addr-displacement))
1598             && (data < (constants_end_addr-displacement))
1599             && (((unsigned)data & 0x3) == 0)) {
1600             /*  Mov eax,m32 */
1601             if (d1 == 0xa1) {
1602                 fixup_found = 1;
1603                 FSHOW((stderr,
1604                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1605                        p, d6, d5, d4, d3, d2, d1, data));
1606                 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1607             }
1608
1609             /*  the case of MOV m32,EAX */
1610             if (d1 == 0xa3) {
1611                 fixup_found = 1;
1612                 FSHOW((stderr,
1613                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1614                        p, d6, d5, d4, d3, d2, d1, data));
1615                 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1616             }
1617
1618             /* the case of CMP m32,imm32 */             
1619             if ((d1 == 0x3d) && (d2 == 0x81)) {
1620                 fixup_found = 1;
1621                 FSHOW((stderr,
1622                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1623                        p, d6, d5, d4, d3, d2, d1, data));
1624                 /* XX Check this */
1625                 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1626             }
1627
1628             /* Check for a mod=00, r/m=101 byte. */
1629             if ((d1 & 0xc7) == 5) {
1630                 /* Cmp m32,reg */
1631                 if (d2 == 0x39) {
1632                     fixup_found = 1;
1633                     FSHOW((stderr,
1634                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1635                            p, d6, d5, d4, d3, d2, d1, data));
1636                     FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1637                 }
1638                 /* the case of CMP reg32,m32 */
1639                 if (d2 == 0x3b) {
1640                     fixup_found = 1;
1641                     FSHOW((stderr,
1642                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1643                            p, d6, d5, d4, d3, d2, d1, data));
1644                     FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1645                 }
1646                 /* the case of MOV m32,reg32 */
1647                 if (d2 == 0x89) {
1648                     fixup_found = 1;
1649                     FSHOW((stderr,
1650                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1651                            p, d6, d5, d4, d3, d2, d1, data));
1652                     FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1653                 }
1654                 /* the case of MOV reg32,m32 */
1655                 if (d2 == 0x8b) {
1656                     fixup_found = 1;
1657                     FSHOW((stderr,
1658                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1659                            p, d6, d5, d4, d3, d2, d1, data));
1660                     FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1661                 }
1662                 /* the case of LEA reg32,m32 */
1663                 if (d2 == 0x8d) {
1664                     fixup_found = 1;
1665                     FSHOW((stderr,
1666                            "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1667                            p, d6, d5, d4, d3, d2, d1, data));
1668                     FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1669                 }
1670             }
1671         }
1672     }
1673
1674     /* If anything was found, print some information on the code
1675      * object. */
1676     if (fixup_found) {
1677         FSHOW((stderr,
1678                "/compiled code object at %x: header words = %d, code words = %d\n",
1679                code, nheader_words, ncode_words));
1680         FSHOW((stderr,
1681                "/const start = %x, end = %x\n",
1682                constants_start_addr, constants_end_addr));
1683         FSHOW((stderr,
1684                "/code start = %x, end = %x\n",
1685                code_start_addr, code_end_addr));
1686     }
1687 }
1688
1689 void
1690 gencgc_apply_code_fixups(struct code *old_code, struct code *new_code)
1691 {
1692     int nheader_words, ncode_words, nwords;
1693     void *constants_start_addr, *constants_end_addr;
1694     void *code_start_addr, *code_end_addr;
1695     lispobj fixups = NIL;
1696     unsigned displacement = (unsigned)new_code - (unsigned)old_code;
1697     struct vector *fixups_vector;
1698
1699     ncode_words = fixnum_value(new_code->code_size);
1700     nheader_words = HeaderValue(*(lispobj *)new_code);
1701     nwords = ncode_words + nheader_words;
1702     /* FSHOW((stderr,
1703              "/compiled code object at %x: header words = %d, code words = %d\n",
1704              new_code, nheader_words, ncode_words)); */
1705     constants_start_addr = (void *)new_code + 5*4;
1706     constants_end_addr = (void *)new_code + nheader_words*4;
1707     code_start_addr = (void *)new_code + nheader_words*4;
1708     code_end_addr = (void *)new_code + nwords*4;
1709     /*
1710     FSHOW((stderr,
1711            "/const start = %x, end = %x\n",
1712            constants_start_addr,constants_end_addr));
1713     FSHOW((stderr,
1714            "/code start = %x; end = %x\n",
1715            code_start_addr,code_end_addr));
1716     */
1717
1718     /* The first constant should be a pointer to the fixups for this
1719        code objects. Check. */
1720     fixups = new_code->constants[0];
1721
1722     /* It will be 0 or the unbound-marker if there are no fixups, and
1723      * will be an other pointer if it is valid. */
1724     if ((fixups == 0) || (fixups == UNBOUND_MARKER_WIDETAG) ||
1725         !is_lisp_pointer(fixups)) {
1726         /* Check for possible errors. */
1727         if (check_code_fixups)
1728             sniff_code_object(new_code, displacement);
1729
1730         /*fprintf(stderr,"Fixups for code object not found!?\n");
1731           fprintf(stderr,"*** Compiled code object at %x: header_words=%d code_words=%d .\n",
1732           new_code, nheader_words, ncode_words);
1733           fprintf(stderr,"*** Const. start = %x; end= %x; Code start = %x; end = %x\n",
1734           constants_start_addr,constants_end_addr,
1735           code_start_addr,code_end_addr);*/
1736         return;
1737     }
1738
1739     fixups_vector = (struct vector *)native_pointer(fixups);
1740
1741     /* Could be pointing to a forwarding pointer. */
1742     if (is_lisp_pointer(fixups) &&
1743         (find_page_index((void*)fixups_vector) != -1) &&
1744         (fixups_vector->header == 0x01)) {
1745         /* If so, then follow it. */
1746         /*SHOW("following pointer to a forwarding pointer");*/
1747         fixups_vector = (struct vector *)native_pointer((lispobj)fixups_vector->length);
1748     }
1749
1750     /*SHOW("got fixups");*/
1751
1752     if (widetag_of(fixups_vector->header) ==
1753         SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG) {
1754         /* Got the fixups for the code block. Now work through the vector,
1755            and apply a fixup at each address. */
1756         int length = fixnum_value(fixups_vector->length);
1757         int i;
1758         for (i = 0; i < length; i++) {
1759             unsigned offset = fixups_vector->data[i];
1760             /* Now check the current value of offset. */
1761             unsigned old_value =
1762                 *(unsigned *)((unsigned)code_start_addr + offset);
1763
1764             /* If it's within the old_code object then it must be an
1765              * absolute fixup (relative ones are not saved) */
1766             if ((old_value >= (unsigned)old_code)
1767                 && (old_value < ((unsigned)old_code + nwords*4)))
1768                 /* So add the dispacement. */
1769                 *(unsigned *)((unsigned)code_start_addr + offset) =
1770                     old_value + displacement;
1771             else
1772                 /* It is outside the old code object so it must be a
1773                  * relative fixup (absolute fixups are not saved). So
1774                  * subtract the displacement. */
1775                 *(unsigned *)((unsigned)code_start_addr + offset) =
1776                     old_value - displacement;
1777         }
1778     }
1779
1780     /* Check for possible errors. */
1781     if (check_code_fixups) {
1782         sniff_code_object(new_code,displacement);
1783     }
1784 }
1785
1786
1787 static lispobj
1788 trans_boxed_large(lispobj object)
1789 {
1790     lispobj header;
1791     unsigned long length;
1792
1793     gc_assert(is_lisp_pointer(object));
1794
1795     header = *((lispobj *) native_pointer(object));
1796     length = HeaderValue(header) + 1;
1797     length = CEILING(length, 2);
1798
1799     return copy_large_object(object, length);
1800 }
1801
1802
1803 static lispobj
1804 trans_unboxed_large(lispobj object)
1805 {
1806     lispobj header;
1807     unsigned long length;
1808
1809
1810     gc_assert(is_lisp_pointer(object));
1811
1812     header = *((lispobj *) native_pointer(object));
1813     length = HeaderValue(header) + 1;
1814     length = CEILING(length, 2);
1815
1816     return copy_large_unboxed_object(object, length);
1817 }
1818
1819 \f
1820 /*
1821  * vector-like objects
1822  */
1823
1824
1825 /* FIXME: What does this mean? */
1826 int gencgc_hash = 1;
1827
1828 static int
1829 scav_vector(lispobj *where, lispobj object)
1830 {
1831     unsigned int kv_length;
1832     lispobj *kv_vector;
1833     unsigned int length = 0; /* (0 = dummy to stop GCC warning) */
1834     lispobj *hash_table;
1835     lispobj empty_symbol;
1836     unsigned int *index_vector = NULL; /* (NULL = dummy to stop GCC warning) */
1837     unsigned int *next_vector = NULL; /* (NULL = dummy to stop GCC warning) */
1838     unsigned int *hash_vector = NULL; /* (NULL = dummy to stop GCC warning) */
1839     lispobj weak_p_obj;
1840     unsigned next_vector_length = 0;
1841
1842     /* FIXME: A comment explaining this would be nice. It looks as
1843      * though SB-VM:VECTOR-VALID-HASHING-SUBTYPE is set for EQ-based
1844      * hash tables in the Lisp HASH-TABLE code, and nowhere else. */
1845     if (HeaderValue(object) != subtype_VectorValidHashing)
1846         return 1;
1847
1848     if (!gencgc_hash) {
1849         /* This is set for backward compatibility. FIXME: Do we need
1850          * this any more? */
1851         *where =
1852             (subtype_VectorMustRehash<<N_WIDETAG_BITS) | SIMPLE_VECTOR_WIDETAG;
1853         return 1;
1854     }
1855
1856     kv_length = fixnum_value(where[1]);
1857     kv_vector = where + 2;  /* Skip the header and length. */
1858     /*FSHOW((stderr,"/kv_length = %d\n", kv_length));*/
1859
1860     /* Scavenge element 0, which may be a hash-table structure. */
1861     scavenge(where+2, 1);
1862     if (!is_lisp_pointer(where[2])) {
1863         lose("no pointer at %x in hash table", where[2]);
1864     }
1865     hash_table = (lispobj *)native_pointer(where[2]);
1866     /*FSHOW((stderr,"/hash_table = %x\n", hash_table));*/
1867     if (widetag_of(hash_table[0]) != INSTANCE_HEADER_WIDETAG) {
1868         lose("hash table not instance (%x at %x)", hash_table[0], hash_table);
1869     }
1870
1871     /* Scavenge element 1, which should be some internal symbol that
1872      * the hash table code reserves for marking empty slots. */
1873     scavenge(where+3, 1);
1874     if (!is_lisp_pointer(where[3])) {
1875         lose("not empty-hash-table-slot symbol pointer: %x", where[3]);
1876     }
1877     empty_symbol = where[3];
1878     /* fprintf(stderr,"* empty_symbol = %x\n", empty_symbol);*/
1879     if (widetag_of(*(lispobj *)native_pointer(empty_symbol)) !=
1880         SYMBOL_HEADER_WIDETAG) {
1881         lose("not a symbol where empty-hash-table-slot symbol expected: %x",
1882              *(lispobj *)native_pointer(empty_symbol));
1883     }
1884
1885     /* Scavenge hash table, which will fix the positions of the other
1886      * needed objects. */
1887     scavenge(hash_table, 16);
1888
1889     /* Cross-check the kv_vector. */
1890     if (where != (lispobj *)native_pointer(hash_table[9])) {
1891         lose("hash_table table!=this table %x", hash_table[9]);
1892     }
1893
1894     /* WEAK-P */
1895     weak_p_obj = hash_table[10];
1896
1897     /* index vector */
1898     {
1899         lispobj index_vector_obj = hash_table[13];
1900
1901         if (is_lisp_pointer(index_vector_obj) &&
1902             (widetag_of(*(lispobj *)native_pointer(index_vector_obj)) ==
1903              SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG)) {
1904             index_vector = ((unsigned int *)native_pointer(index_vector_obj)) + 2;
1905             /*FSHOW((stderr, "/index_vector = %x\n",index_vector));*/
1906             length = fixnum_value(((unsigned int *)native_pointer(index_vector_obj))[1]);
1907             /*FSHOW((stderr, "/length = %d\n", length));*/
1908         } else {
1909             lose("invalid index_vector %x", index_vector_obj);
1910         }
1911     }
1912
1913     /* next vector */
1914     {
1915         lispobj next_vector_obj = hash_table[14];
1916
1917         if (is_lisp_pointer(next_vector_obj) &&
1918             (widetag_of(*(lispobj *)native_pointer(next_vector_obj)) ==
1919              SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG)) {
1920             next_vector = ((unsigned int *)native_pointer(next_vector_obj)) + 2;
1921             /*FSHOW((stderr, "/next_vector = %x\n", next_vector));*/
1922             next_vector_length = fixnum_value(((unsigned int *)native_pointer(next_vector_obj))[1]);
1923             /*FSHOW((stderr, "/next_vector_length = %d\n", next_vector_length));*/
1924         } else {
1925             lose("invalid next_vector %x", next_vector_obj);
1926         }
1927     }
1928
1929     /* maybe hash vector */
1930     {
1931         /* FIXME: This bare "15" offset should become a symbolic
1932          * expression of some sort. And all the other bare offsets
1933          * too. And the bare "16" in scavenge(hash_table, 16). And
1934          * probably other stuff too. Ugh.. */
1935         lispobj hash_vector_obj = hash_table[15];
1936
1937         if (is_lisp_pointer(hash_vector_obj) &&
1938             (widetag_of(*(lispobj *)native_pointer(hash_vector_obj))
1939              == SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG)) {
1940             hash_vector = ((unsigned int *)native_pointer(hash_vector_obj)) + 2;
1941             /*FSHOW((stderr, "/hash_vector = %x\n", hash_vector));*/
1942             gc_assert(fixnum_value(((unsigned int *)native_pointer(hash_vector_obj))[1])
1943                       == next_vector_length);
1944         } else {
1945             hash_vector = NULL;
1946             /*FSHOW((stderr, "/no hash_vector: %x\n", hash_vector_obj));*/
1947         }
1948     }
1949
1950     /* These lengths could be different as the index_vector can be a
1951      * different length from the others, a larger index_vector could help
1952      * reduce collisions. */
1953     gc_assert(next_vector_length*2 == kv_length);
1954
1955     /* now all set up.. */
1956
1957     /* Work through the KV vector. */
1958     {
1959         int i;
1960         for (i = 1; i < next_vector_length; i++) {
1961             lispobj old_key = kv_vector[2*i];
1962             unsigned int  old_index = (old_key & 0x1fffffff)%length;
1963
1964             /* Scavenge the key and value. */
1965             scavenge(&kv_vector[2*i],2);
1966
1967             /* Check whether the key has moved and is EQ based. */
1968             {
1969                 lispobj new_key = kv_vector[2*i];
1970                 unsigned int new_index = (new_key & 0x1fffffff)%length;
1971
1972                 if ((old_index != new_index) &&
1973                     ((!hash_vector) || (hash_vector[i] == 0x80000000)) &&
1974                     ((new_key != empty_symbol) ||
1975                      (kv_vector[2*i] != empty_symbol))) {
1976
1977                     /*FSHOW((stderr,
1978                            "* EQ key %d moved from %x to %x; index %d to %d\n",
1979                            i, old_key, new_key, old_index, new_index));*/
1980
1981                     if (index_vector[old_index] != 0) {
1982                         /*FSHOW((stderr, "/P1 %d\n", index_vector[old_index]));*/
1983
1984                         /* Unlink the key from the old_index chain. */
1985                         if (index_vector[old_index] == i) {
1986                             /*FSHOW((stderr, "/P2a %d\n", next_vector[i]));*/
1987                             index_vector[old_index] = next_vector[i];
1988                             /* Link it into the needing rehash chain. */
1989                             next_vector[i] = fixnum_value(hash_table[11]);
1990                             hash_table[11] = make_fixnum(i);
1991                             /*SHOW("P2");*/
1992                         } else {
1993                             unsigned prior = index_vector[old_index];
1994                             unsigned next = next_vector[prior];
1995
1996                             /*FSHOW((stderr, "/P3a %d %d\n", prior, next));*/
1997
1998                             while (next != 0) {
1999                                 /*FSHOW((stderr, "/P3b %d %d\n", prior, next));*/
2000                                 if (next == i) {
2001                                     /* Unlink it. */
2002                                     next_vector[prior] = next_vector[next];
2003                                     /* Link it into the needing rehash
2004                                      * chain. */
2005                                     next_vector[next] =
2006                                         fixnum_value(hash_table[11]);
2007                                     hash_table[11] = make_fixnum(next);
2008                                     /*SHOW("/P3");*/
2009                                     break;
2010                                 }
2011                                 prior = next;
2012                                 next = next_vector[next];
2013                             }
2014                         }
2015                     }
2016                 }
2017             }
2018         }
2019     }
2020     return (CEILING(kv_length + 2, 2));
2021 }
2022
2023
2024 \f
2025 /*
2026  * weak pointers
2027  */
2028
2029 /* XX This is a hack adapted from cgc.c. These don't work too
2030  * efficiently with the gencgc as a list of the weak pointers is
2031  * maintained within the objects which causes writes to the pages. A
2032  * limited attempt is made to avoid unnecessary writes, but this needs
2033  * a re-think. */
2034 #define WEAK_POINTER_NWORDS \
2035     CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
2036
2037 static int
2038 scav_weak_pointer(lispobj *where, lispobj object)
2039 {
2040     struct weak_pointer *wp = weak_pointers;
2041     /* Push the weak pointer onto the list of weak pointers.
2042      * Do I have to watch for duplicates? Originally this was
2043      * part of trans_weak_pointer but that didn't work in the
2044      * case where the WP was in a promoted region.
2045      */
2046
2047     /* Check whether it's already in the list. */
2048     while (wp != NULL) {
2049         if (wp == (struct weak_pointer*)where) {
2050             break;
2051         }
2052         wp = wp->next;
2053     }
2054     if (wp == NULL) {
2055         /* Add it to the start of the list. */
2056         wp = (struct weak_pointer*)where;
2057         if (wp->next != weak_pointers) {
2058             wp->next = weak_pointers;
2059         } else {
2060             /*SHOW("avoided write to weak pointer");*/
2061         }
2062         weak_pointers = wp;
2063     }
2064
2065     /* Do not let GC scavenge the value slot of the weak pointer.
2066      * (That is why it is a weak pointer.) */
2067
2068     return WEAK_POINTER_NWORDS;
2069 }
2070
2071 \f
2072 /* Scan an area looking for an object which encloses the given pointer.
2073  * Return the object start on success or NULL on failure. */
2074 static lispobj *
2075 search_space(lispobj *start, size_t words, lispobj *pointer)
2076 {
2077     while (words > 0) {
2078         size_t count = 1;
2079         lispobj thing = *start;
2080
2081         /* If thing is an immediate then this is a cons. */
2082         if (is_lisp_pointer(thing)
2083             || ((thing & 3) == 0) /* fixnum */
2084             || (widetag_of(thing) == BASE_CHAR_WIDETAG)
2085             || (widetag_of(thing) == UNBOUND_MARKER_WIDETAG))
2086             count = 2;
2087         else
2088             count = (sizetab[widetag_of(thing)])(start);
2089
2090         /* Check whether the pointer is within this object. */
2091         if ((pointer >= start) && (pointer < (start+count))) {
2092             /* found it! */
2093             /*FSHOW((stderr,"/found %x in %x %x\n", pointer, start, thing));*/
2094             return(start);
2095         }
2096
2097         /* Round up the count. */
2098         count = CEILING(count,2);
2099
2100         start += count;
2101         words -= count;
2102     }
2103     return (NULL);
2104 }
2105
2106 static lispobj*
2107 search_read_only_space(lispobj *pointer)
2108 {
2109     lispobj* start = (lispobj*)READ_ONLY_SPACE_START;
2110     lispobj* end = (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
2111     if ((pointer < start) || (pointer >= end))
2112         return NULL;
2113     return (search_space(start, (pointer+2)-start, pointer));
2114 }
2115
2116 static lispobj *
2117 search_static_space(lispobj *pointer)
2118 {
2119     lispobj* start = (lispobj*)STATIC_SPACE_START;
2120     lispobj* end = (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
2121     if ((pointer < start) || (pointer >= end))
2122         return NULL;
2123     return (search_space(start, (pointer+2)-start, pointer));
2124 }
2125
2126 /* a faster version for searching the dynamic space. This will work even
2127  * if the object is in a current allocation region. */
2128 lispobj *
2129 search_dynamic_space(lispobj *pointer)
2130 {
2131     int  page_index = find_page_index(pointer);
2132     lispobj *start;
2133
2134     /* The address may be invalid, so do some checks. */
2135     if ((page_index == -1) || (page_table[page_index].allocated == FREE_PAGE))
2136         return NULL;
2137     start = (lispobj *)((void *)page_address(page_index)
2138                         + page_table[page_index].first_object_offset);
2139     return (search_space(start, (pointer+2)-start, pointer));
2140 }
2141
2142 /* Is there any possibility that pointer is a valid Lisp object
2143  * reference, and/or something else (e.g. subroutine call return
2144  * address) which should prevent us from moving the referred-to thing? */
2145 static int
2146 possibly_valid_dynamic_space_pointer(lispobj *pointer)
2147 {
2148     lispobj *start_addr;
2149
2150     /* Find the object start address. */
2151     if ((start_addr = search_dynamic_space(pointer)) == NULL) {
2152         return 0;
2153     }
2154
2155     /* We need to allow raw pointers into Code objects for return
2156      * addresses. This will also pick up pointers to functions in code
2157      * objects. */
2158     if (widetag_of(*start_addr) == CODE_HEADER_WIDETAG) {
2159         /* XXX could do some further checks here */
2160         return 1;
2161     }
2162
2163     /* If it's not a return address then it needs to be a valid Lisp
2164      * pointer. */
2165     if (!is_lisp_pointer((lispobj)pointer)) {
2166         return 0;
2167     }
2168
2169     /* Check that the object pointed to is consistent with the pointer
2170      * low tag.
2171      *
2172      * FIXME: It's not safe to rely on the result from this check
2173      * before an object is initialized. Thus, if we were interrupted
2174      * just as an object had been allocated but not initialized, the
2175      * GC relying on this result could bogusly reclaim the memory.
2176      * However, we can't really afford to do without this check. So
2177      * we should make it safe somehow. 
2178      *   (1) Perhaps just review the code to make sure
2179      *       that WITHOUT-GCING or WITHOUT-INTERRUPTS or some such
2180      *       thing is wrapped around critical sections where allocated
2181      *       memory type bits haven't been set.
2182      *   (2) Perhaps find some other hack to protect against this, e.g.
2183      *       recording the result of the last call to allocate-lisp-memory,
2184      *       and returning true from this function when *pointer is
2185      *       a reference to that result. 
2186      *
2187      * (surely pseudo-atomic is supposed to be used for exactly this?)
2188      */
2189     switch (lowtag_of((lispobj)pointer)) {
2190     case FUN_POINTER_LOWTAG:
2191         /* Start_addr should be the enclosing code object, or a closure
2192          * header. */
2193         switch (widetag_of(*start_addr)) {
2194         case CODE_HEADER_WIDETAG:
2195             /* This case is probably caught above. */
2196             break;
2197         case CLOSURE_HEADER_WIDETAG:
2198         case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2199             if ((unsigned)pointer !=
2200                 ((unsigned)start_addr+FUN_POINTER_LOWTAG)) {
2201                 if (gencgc_verbose)
2202                     FSHOW((stderr,
2203                            "/Wf2: %x %x %x\n",
2204                            pointer, start_addr, *start_addr));
2205                 return 0;
2206             }
2207             break;
2208         default:
2209             if (gencgc_verbose)
2210                 FSHOW((stderr,
2211                        "/Wf3: %x %x %x\n",
2212                        pointer, start_addr, *start_addr));
2213             return 0;
2214         }
2215         break;
2216     case LIST_POINTER_LOWTAG:
2217         if ((unsigned)pointer !=
2218             ((unsigned)start_addr+LIST_POINTER_LOWTAG)) {
2219             if (gencgc_verbose)
2220                 FSHOW((stderr,
2221                        "/Wl1: %x %x %x\n",
2222                        pointer, start_addr, *start_addr));
2223             return 0;
2224         }
2225         /* Is it plausible cons? */
2226         if ((is_lisp_pointer(start_addr[0])
2227             || ((start_addr[0] & 3) == 0) /* fixnum */
2228             || (widetag_of(start_addr[0]) == BASE_CHAR_WIDETAG)
2229             || (widetag_of(start_addr[0]) == UNBOUND_MARKER_WIDETAG))
2230            && (is_lisp_pointer(start_addr[1])
2231                || ((start_addr[1] & 3) == 0) /* fixnum */
2232                || (widetag_of(start_addr[1]) == BASE_CHAR_WIDETAG)
2233                || (widetag_of(start_addr[1]) == UNBOUND_MARKER_WIDETAG)))
2234             break;
2235         else {
2236             if (gencgc_verbose)
2237                 FSHOW((stderr,
2238                        "/Wl2: %x %x %x\n",
2239                        pointer, start_addr, *start_addr));
2240             return 0;
2241         }
2242     case INSTANCE_POINTER_LOWTAG:
2243         if ((unsigned)pointer !=
2244             ((unsigned)start_addr+INSTANCE_POINTER_LOWTAG)) {
2245             if (gencgc_verbose)
2246                 FSHOW((stderr,
2247                        "/Wi1: %x %x %x\n",
2248                        pointer, start_addr, *start_addr));
2249             return 0;
2250         }
2251         if (widetag_of(start_addr[0]) != INSTANCE_HEADER_WIDETAG) {
2252             if (gencgc_verbose)
2253                 FSHOW((stderr,
2254                        "/Wi2: %x %x %x\n",
2255                        pointer, start_addr, *start_addr));
2256             return 0;
2257         }
2258         break;
2259     case OTHER_POINTER_LOWTAG:
2260         if ((unsigned)pointer !=
2261             ((int)start_addr+OTHER_POINTER_LOWTAG)) {
2262             if (gencgc_verbose)
2263                 FSHOW((stderr,
2264                        "/Wo1: %x %x %x\n",
2265                        pointer, start_addr, *start_addr));
2266             return 0;
2267         }
2268         /* Is it plausible?  Not a cons. XXX should check the headers. */
2269         if (is_lisp_pointer(start_addr[0]) || ((start_addr[0] & 3) == 0)) {
2270             if (gencgc_verbose)
2271                 FSHOW((stderr,
2272                        "/Wo2: %x %x %x\n",
2273                        pointer, start_addr, *start_addr));
2274             return 0;
2275         }
2276         switch (widetag_of(start_addr[0])) {
2277         case UNBOUND_MARKER_WIDETAG:
2278         case BASE_CHAR_WIDETAG:
2279             if (gencgc_verbose)
2280                 FSHOW((stderr,
2281                        "*Wo3: %x %x %x\n",
2282                        pointer, start_addr, *start_addr));
2283             return 0;
2284
2285             /* only pointed to by function pointers? */
2286         case CLOSURE_HEADER_WIDETAG:
2287         case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2288             if (gencgc_verbose)
2289                 FSHOW((stderr,
2290                        "*Wo4: %x %x %x\n",
2291                        pointer, start_addr, *start_addr));
2292             return 0;
2293
2294         case INSTANCE_HEADER_WIDETAG:
2295             if (gencgc_verbose)
2296                 FSHOW((stderr,
2297                        "*Wo5: %x %x %x\n",
2298                        pointer, start_addr, *start_addr));
2299             return 0;
2300
2301             /* the valid other immediate pointer objects */
2302         case SIMPLE_VECTOR_WIDETAG:
2303         case RATIO_WIDETAG:
2304         case COMPLEX_WIDETAG:
2305 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
2306         case COMPLEX_SINGLE_FLOAT_WIDETAG:
2307 #endif
2308 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
2309         case COMPLEX_DOUBLE_FLOAT_WIDETAG:
2310 #endif
2311 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
2312         case COMPLEX_LONG_FLOAT_WIDETAG:
2313 #endif
2314         case SIMPLE_ARRAY_WIDETAG:
2315         case COMPLEX_STRING_WIDETAG:
2316         case COMPLEX_BIT_VECTOR_WIDETAG:
2317         case COMPLEX_VECTOR_WIDETAG:
2318         case COMPLEX_ARRAY_WIDETAG:
2319         case VALUE_CELL_HEADER_WIDETAG:
2320         case SYMBOL_HEADER_WIDETAG:
2321         case FDEFN_WIDETAG:
2322         case CODE_HEADER_WIDETAG:
2323         case BIGNUM_WIDETAG:
2324         case SINGLE_FLOAT_WIDETAG:
2325         case DOUBLE_FLOAT_WIDETAG:
2326 #ifdef LONG_FLOAT_WIDETAG
2327         case LONG_FLOAT_WIDETAG:
2328 #endif
2329         case SIMPLE_STRING_WIDETAG:
2330         case SIMPLE_BIT_VECTOR_WIDETAG:
2331         case SIMPLE_ARRAY_NIL_WIDETAG:
2332         case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2333         case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2334         case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2335         case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2336         case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2337 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2338         case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2339 #endif
2340 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2341         case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2342 #endif
2343 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
2344         case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
2345 #endif
2346 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2347         case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2348 #endif
2349         case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2350         case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2351 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2352         case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2353 #endif
2354 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2355         case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2356 #endif
2357 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2358         case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2359 #endif
2360 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2361         case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2362 #endif
2363         case SAP_WIDETAG:
2364         case WEAK_POINTER_WIDETAG:
2365             break;
2366
2367         default:
2368             if (gencgc_verbose)
2369                 FSHOW((stderr,
2370                        "/Wo6: %x %x %x\n",
2371                        pointer, start_addr, *start_addr));
2372             return 0;
2373         }
2374         break;
2375     default:
2376         if (gencgc_verbose)
2377             FSHOW((stderr,
2378                    "*W?: %x %x %x\n",
2379                    pointer, start_addr, *start_addr));
2380         return 0;
2381     }
2382
2383     /* looks good */
2384     return 1;
2385 }
2386
2387 /* Adjust large bignum and vector objects. This will adjust the
2388  * allocated region if the size has shrunk, and move unboxed objects
2389  * into unboxed pages. The pages are not promoted here, and the
2390  * promoted region is not added to the new_regions; this is really
2391  * only designed to be called from preserve_pointer(). Shouldn't fail
2392  * if this is missed, just may delay the moving of objects to unboxed
2393  * pages, and the freeing of pages. */
2394 static void
2395 maybe_adjust_large_object(lispobj *where)
2396 {
2397     int first_page;
2398     int nwords;
2399
2400     int remaining_bytes;
2401     int next_page;
2402     int bytes_freed;
2403     int old_bytes_used;
2404
2405     int boxed;
2406
2407     /* Check whether it's a vector or bignum object. */
2408     switch (widetag_of(where[0])) {
2409     case SIMPLE_VECTOR_WIDETAG:
2410         boxed = BOXED_PAGE;
2411         break;
2412     case BIGNUM_WIDETAG:
2413     case SIMPLE_STRING_WIDETAG:
2414     case SIMPLE_BIT_VECTOR_WIDETAG:
2415     case SIMPLE_ARRAY_NIL_WIDETAG:
2416     case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2417     case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2418     case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2419     case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2420     case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2421 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2422     case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2423 #endif
2424 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2425     case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2426 #endif
2427 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
2428     case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
2429 #endif
2430 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2431     case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2432 #endif
2433     case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2434     case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2435 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2436     case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2437 #endif
2438 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2439     case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2440 #endif
2441 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2442     case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2443 #endif
2444 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2445     case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2446 #endif
2447         boxed = UNBOXED_PAGE;
2448         break;
2449     default:
2450         return;
2451     }
2452
2453     /* Find its current size. */
2454     nwords = (sizetab[widetag_of(where[0])])(where);
2455
2456     first_page = find_page_index((void *)where);
2457     gc_assert(first_page >= 0);
2458
2459     /* Note: Any page write-protection must be removed, else a later
2460      * scavenge_newspace may incorrectly not scavenge these pages.
2461      * This would not be necessary if they are added to the new areas,
2462      * but lets do it for them all (they'll probably be written
2463      * anyway?). */
2464
2465     gc_assert(page_table[first_page].first_object_offset == 0);
2466
2467     next_page = first_page;
2468     remaining_bytes = nwords*4;
2469     while (remaining_bytes > 4096) {
2470         gc_assert(page_table[next_page].gen == from_space);
2471         gc_assert((page_table[next_page].allocated == BOXED_PAGE)
2472                   || (page_table[next_page].allocated == UNBOXED_PAGE));
2473         gc_assert(page_table[next_page].large_object);
2474         gc_assert(page_table[next_page].first_object_offset ==
2475                   -4096*(next_page-first_page));
2476         gc_assert(page_table[next_page].bytes_used == 4096);
2477
2478         page_table[next_page].allocated = boxed;
2479
2480         /* Shouldn't be write-protected at this stage. Essential that the
2481          * pages aren't. */
2482         gc_assert(!page_table[next_page].write_protected);
2483         remaining_bytes -= 4096;
2484         next_page++;
2485     }
2486
2487     /* Now only one page remains, but the object may have shrunk so
2488      * there may be more unused pages which will be freed. */
2489
2490     /* Object may have shrunk but shouldn't have grown - check. */
2491     gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2492
2493     page_table[next_page].allocated = boxed;
2494     gc_assert(page_table[next_page].allocated ==
2495               page_table[first_page].allocated);
2496
2497     /* Adjust the bytes_used. */
2498     old_bytes_used = page_table[next_page].bytes_used;
2499     page_table[next_page].bytes_used = remaining_bytes;
2500
2501     bytes_freed = old_bytes_used - remaining_bytes;
2502
2503     /* Free any remaining pages; needs care. */
2504     next_page++;
2505     while ((old_bytes_used == 4096) &&
2506            (page_table[next_page].gen == from_space) &&
2507            ((page_table[next_page].allocated == UNBOXED_PAGE)
2508             || (page_table[next_page].allocated == BOXED_PAGE)) &&
2509            page_table[next_page].large_object &&
2510            (page_table[next_page].first_object_offset ==
2511             -(next_page - first_page)*4096)) {
2512         /* It checks out OK, free the page. We don't need to both zeroing
2513          * pages as this should have been done before shrinking the
2514          * object. These pages shouldn't be write protected as they
2515          * should be zero filled. */
2516         gc_assert(page_table[next_page].write_protected == 0);
2517
2518         old_bytes_used = page_table[next_page].bytes_used;
2519         page_table[next_page].allocated = FREE_PAGE;
2520         page_table[next_page].bytes_used = 0;
2521         bytes_freed += old_bytes_used;
2522         next_page++;
2523     }
2524
2525     if ((bytes_freed > 0) && gencgc_verbose) {
2526         FSHOW((stderr,
2527                "/maybe_adjust_large_object() freed %d\n",
2528                bytes_freed));
2529     }
2530
2531     generations[from_space].bytes_allocated -= bytes_freed;
2532     bytes_allocated -= bytes_freed;
2533
2534     return;
2535 }
2536
2537 /* Take a possible pointer to a Lisp object and mark its page in the
2538  * page_table so that it will not be relocated during a GC.
2539  *
2540  * This involves locating the page it points to, then backing up to
2541  * the first page that has its first object start at offset 0, and
2542  * then marking all pages dont_move from the first until a page that
2543  * ends by being full, or having free gen.
2544  *
2545  * This ensures that objects spanning pages are not broken.
2546  *
2547  * It is assumed that all the page static flags have been cleared at
2548  * the start of a GC.
2549  *
2550  * It is also assumed that the current gc_alloc() region has been
2551  * flushed and the tables updated. */
2552 static void
2553 preserve_pointer(void *addr)
2554 {
2555     int addr_page_index = find_page_index(addr);
2556     int first_page;
2557     int i;
2558     unsigned region_allocation;
2559
2560     /* quick check 1: Address is quite likely to have been invalid. */
2561     if ((addr_page_index == -1)
2562         || (page_table[addr_page_index].allocated == FREE_PAGE)
2563         || (page_table[addr_page_index].bytes_used == 0)
2564         || (page_table[addr_page_index].gen != from_space)
2565         /* Skip if already marked dont_move. */
2566         || (page_table[addr_page_index].dont_move != 0))
2567         return;
2568     gc_assert(!(page_table[addr_page_index].allocated & OPEN_REGION_PAGE));
2569     /* (Now that we know that addr_page_index is in range, it's
2570      * safe to index into page_table[] with it.) */
2571     region_allocation = page_table[addr_page_index].allocated;
2572
2573     /* quick check 2: Check the offset within the page.
2574      *
2575      * FIXME: The mask should have a symbolic name, and ideally should
2576      * be derived from page size instead of hardwired to 0xfff.
2577      * (Also fix other uses of 0xfff, elsewhere.) */
2578     if (((unsigned)addr & 0xfff) > page_table[addr_page_index].bytes_used)
2579         return;
2580
2581     /* Filter out anything which can't be a pointer to a Lisp object
2582      * (or, as a special case which also requires dont_move, a return
2583      * address referring to something in a CodeObject). This is
2584      * expensive but important, since it vastly reduces the
2585      * probability that random garbage will be bogusly interpreter as
2586      * a pointer which prevents a page from moving. */
2587     if (!(possibly_valid_dynamic_space_pointer(addr)))
2588         return;
2589     first_page = addr_page_index;
2590
2591     /* Work backwards to find a page with a first_object_offset of 0.
2592      * The pages should be contiguous with all bytes used in the same
2593      * gen. Assumes the first_object_offset is negative or zero. */
2594
2595     /* this is probably needlessly conservative.  The first object in
2596      * the page may not even be the one we were passed a pointer to:
2597      * if this is the case, we will write-protect all the previous
2598      * object's pages too.
2599      */
2600
2601     while (page_table[first_page].first_object_offset != 0) {
2602         --first_page;
2603         /* Do some checks. */
2604         gc_assert(page_table[first_page].bytes_used == 4096);
2605         gc_assert(page_table[first_page].gen == from_space);
2606         gc_assert(page_table[first_page].allocated == region_allocation);
2607     }
2608
2609     /* Adjust any large objects before promotion as they won't be
2610      * copied after promotion. */
2611     if (page_table[first_page].large_object) {
2612         maybe_adjust_large_object(page_address(first_page));
2613         /* If a large object has shrunk then addr may now point to a
2614          * free area in which case it's ignored here. Note it gets
2615          * through the valid pointer test above because the tail looks
2616          * like conses. */
2617         if ((page_table[addr_page_index].allocated == FREE_PAGE)
2618             || (page_table[addr_page_index].bytes_used == 0)
2619             /* Check the offset within the page. */
2620             || (((unsigned)addr & 0xfff)
2621                 > page_table[addr_page_index].bytes_used)) {
2622             FSHOW((stderr,
2623                    "weird? ignore ptr 0x%x to freed area of large object\n",
2624                    addr));
2625             return;
2626         }
2627         /* It may have moved to unboxed pages. */
2628         region_allocation = page_table[first_page].allocated;
2629     }
2630
2631     /* Now work forward until the end of this contiguous area is found,
2632      * marking all pages as dont_move. */
2633     for (i = first_page; ;i++) {
2634         gc_assert(page_table[i].allocated == region_allocation);
2635
2636         /* Mark the page static. */
2637         page_table[i].dont_move = 1;
2638
2639         /* Move the page to the new_space. XX I'd rather not do this
2640          * but the GC logic is not quite able to copy with the static
2641          * pages remaining in the from space. This also requires the
2642          * generation bytes_allocated counters be updated. */
2643         page_table[i].gen = new_space;
2644         generations[new_space].bytes_allocated += page_table[i].bytes_used;
2645         generations[from_space].bytes_allocated -= page_table[i].bytes_used;
2646
2647         /* It is essential that the pages are not write protected as
2648          * they may have pointers into the old-space which need
2649          * scavenging. They shouldn't be write protected at this
2650          * stage. */
2651         gc_assert(!page_table[i].write_protected);
2652
2653         /* Check whether this is the last page in this contiguous block.. */
2654         if ((page_table[i].bytes_used < 4096)
2655             /* ..or it is 4096 and is the last in the block */
2656             || (page_table[i+1].allocated == FREE_PAGE)
2657             || (page_table[i+1].bytes_used == 0) /* next page free */
2658             || (page_table[i+1].gen != from_space) /* diff. gen */
2659             || (page_table[i+1].first_object_offset == 0))
2660             break;
2661     }
2662
2663     /* Check that the page is now static. */
2664     gc_assert(page_table[addr_page_index].dont_move != 0);
2665 }
2666 \f
2667 /* If the given page is not write-protected, then scan it for pointers
2668  * to younger generations or the top temp. generation, if no
2669  * suspicious pointers are found then the page is write-protected.
2670  *
2671  * Care is taken to check for pointers to the current gc_alloc()
2672  * region if it is a younger generation or the temp. generation. This
2673  * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2674  * the gc_alloc_generation does not need to be checked as this is only
2675  * called from scavenge_generation() when the gc_alloc generation is
2676  * younger, so it just checks if there is a pointer to the current
2677  * region.
2678  *
2679  * We return 1 if the page was write-protected, else 0. */
2680 static int
2681 update_page_write_prot(int page)
2682 {
2683     int gen = page_table[page].gen;
2684     int j;
2685     int wp_it = 1;
2686     void **page_addr = (void **)page_address(page);
2687     int num_words = page_table[page].bytes_used / 4;
2688
2689     /* Shouldn't be a free page. */
2690     gc_assert(page_table[page].allocated != FREE_PAGE);
2691     gc_assert(page_table[page].bytes_used != 0);
2692
2693     /* Skip if it's already write-protected or an unboxed page. */
2694     if (page_table[page].write_protected
2695         || (page_table[page].allocated & UNBOXED_PAGE))
2696         return (0);
2697
2698     /* Scan the page for pointers to younger generations or the
2699      * top temp. generation. */
2700
2701     for (j = 0; j < num_words; j++) {
2702         void *ptr = *(page_addr+j);
2703         int index = find_page_index(ptr);
2704
2705         /* Check that it's in the dynamic space */
2706         if (index != -1)
2707             if (/* Does it point to a younger or the temp. generation? */
2708                 ((page_table[index].allocated != FREE_PAGE)
2709                  && (page_table[index].bytes_used != 0)
2710                  && ((page_table[index].gen < gen)
2711                      || (page_table[index].gen == NUM_GENERATIONS)))
2712
2713                 /* Or does it point within a current gc_alloc() region? */
2714                 || ((boxed_region.start_addr <= ptr)
2715                     && (ptr <= boxed_region.free_pointer))
2716                 || ((unboxed_region.start_addr <= ptr)
2717                     && (ptr <= unboxed_region.free_pointer))) {
2718                 wp_it = 0;
2719                 break;
2720             }
2721     }
2722
2723     if (wp_it == 1) {
2724         /* Write-protect the page. */
2725         /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2726
2727         os_protect((void *)page_addr,
2728                    4096,
2729                    OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2730
2731         /* Note the page as protected in the page tables. */
2732         page_table[page].write_protected = 1;
2733     }
2734
2735     return (wp_it);
2736 }
2737
2738 /* Scavenge a generation.
2739  *
2740  * This will not resolve all pointers when generation is the new
2741  * space, as new objects may be added which are not check here - use
2742  * scavenge_newspace generation.
2743  *
2744  * Write-protected pages should not have any pointers to the
2745  * from_space so do need scavenging; thus write-protected pages are
2746  * not always scavenged. There is some code to check that these pages
2747  * are not written; but to check fully the write-protected pages need
2748  * to be scavenged by disabling the code to skip them.
2749  *
2750  * Under the current scheme when a generation is GCed the younger
2751  * generations will be empty. So, when a generation is being GCed it
2752  * is only necessary to scavenge the older generations for pointers
2753  * not the younger. So a page that does not have pointers to younger
2754  * generations does not need to be scavenged.
2755  *
2756  * The write-protection can be used to note pages that don't have
2757  * pointers to younger pages. But pages can be written without having
2758  * pointers to younger generations. After the pages are scavenged here
2759  * they can be scanned for pointers to younger generations and if
2760  * there are none the page can be write-protected.
2761  *
2762  * One complication is when the newspace is the top temp. generation.
2763  *
2764  * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2765  * that none were written, which they shouldn't be as they should have
2766  * no pointers to younger generations. This breaks down for weak
2767  * pointers as the objects contain a link to the next and are written
2768  * if a weak pointer is scavenged. Still it's a useful check. */
2769 static void
2770 scavenge_generation(int generation)
2771 {
2772     int i;
2773     int num_wp = 0;
2774
2775 #define SC_GEN_CK 0
2776 #if SC_GEN_CK
2777     /* Clear the write_protected_cleared flags on all pages. */
2778     for (i = 0; i < NUM_PAGES; i++)
2779         page_table[i].write_protected_cleared = 0;
2780 #endif
2781
2782     for (i = 0; i < last_free_page; i++) {
2783         if ((page_table[i].allocated & BOXED_PAGE)
2784             && (page_table[i].bytes_used != 0)
2785             && (page_table[i].gen == generation)) {
2786             int last_page;
2787
2788             /* This should be the start of a contiguous block. */
2789             gc_assert(page_table[i].first_object_offset == 0);
2790
2791             /* We need to find the full extent of this contiguous
2792              * block in case objects span pages. */
2793
2794             /* Now work forward until the end of this contiguous area
2795              * is found. A small area is preferred as there is a
2796              * better chance of its pages being write-protected. */
2797             for (last_page = i; ; last_page++)
2798                 /* Check whether this is the last page in this contiguous
2799                  * block. */
2800                 if ((page_table[last_page].bytes_used < 4096)
2801                     /* Or it is 4096 and is the last in the block */
2802                     || (!(page_table[last_page+1].allocated & BOXED_PAGE))
2803                     || (page_table[last_page+1].bytes_used == 0)
2804                     || (page_table[last_page+1].gen != generation)
2805                     || (page_table[last_page+1].first_object_offset == 0))
2806                     break;
2807
2808             /* Do a limited check for write_protected pages. If all pages
2809              * are write_protected then there is no need to scavenge. */
2810             {
2811                 int j, all_wp = 1;
2812                 for (j = i; j <= last_page; j++)
2813                     if (page_table[j].write_protected == 0) {
2814                         all_wp = 0;
2815                         break;
2816                     }
2817 #if !SC_GEN_CK
2818                 if (all_wp == 0)
2819 #endif
2820                     {
2821                         scavenge(page_address(i), (page_table[last_page].bytes_used
2822                                                    + (last_page-i)*4096)/4);
2823
2824                         /* Now scan the pages and write protect those
2825                          * that don't have pointers to younger
2826                          * generations. */
2827                         if (enable_page_protection) {
2828                             for (j = i; j <= last_page; j++) {
2829                                 num_wp += update_page_write_prot(j);
2830                             }
2831                         }
2832                     }
2833             }
2834             i = last_page;
2835         }
2836     }
2837
2838     if ((gencgc_verbose > 1) && (num_wp != 0)) {
2839         FSHOW((stderr,
2840                "/write protected %d pages within generation %d\n",
2841                num_wp, generation));
2842     }
2843
2844 #if SC_GEN_CK
2845     /* Check that none of the write_protected pages in this generation
2846      * have been written to. */
2847     for (i = 0; i < NUM_PAGES; i++) {
2848         if ((page_table[i].allocation ! =FREE_PAGE)
2849             && (page_table[i].bytes_used != 0)
2850             && (page_table[i].gen == generation)
2851             && (page_table[i].write_protected_cleared != 0)) {
2852             FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2853             FSHOW((stderr,
2854                    "/page bytes_used=%d first_object_offset=%d dont_move=%d\n",
2855                     page_table[i].bytes_used,
2856                     page_table[i].first_object_offset,
2857                     page_table[i].dont_move));
2858             lose("write to protected page %d in scavenge_generation()", i);
2859         }
2860     }
2861 #endif
2862 }
2863
2864 \f
2865 /* Scavenge a newspace generation. As it is scavenged new objects may
2866  * be allocated to it; these will also need to be scavenged. This
2867  * repeats until there are no more objects unscavenged in the
2868  * newspace generation.
2869  *
2870  * To help improve the efficiency, areas written are recorded by
2871  * gc_alloc() and only these scavenged. Sometimes a little more will be
2872  * scavenged, but this causes no harm. An easy check is done that the
2873  * scavenged bytes equals the number allocated in the previous
2874  * scavenge.
2875  *
2876  * Write-protected pages are not scanned except if they are marked
2877  * dont_move in which case they may have been promoted and still have
2878  * pointers to the from space.
2879  *
2880  * Write-protected pages could potentially be written by alloc however
2881  * to avoid having to handle re-scavenging of write-protected pages
2882  * gc_alloc() does not write to write-protected pages.
2883  *
2884  * New areas of objects allocated are recorded alternatively in the two
2885  * new_areas arrays below. */
2886 static struct new_area new_areas_1[NUM_NEW_AREAS];
2887 static struct new_area new_areas_2[NUM_NEW_AREAS];
2888
2889 /* Do one full scan of the new space generation. This is not enough to
2890  * complete the job as new objects may be added to the generation in
2891  * the process which are not scavenged. */
2892 static void
2893 scavenge_newspace_generation_one_scan(int generation)
2894 {
2895     int i;
2896
2897     FSHOW((stderr,
2898            "/starting one full scan of newspace generation %d\n",
2899            generation));
2900     for (i = 0; i < last_free_page; i++) {
2901         /* note that this skips over open regions when it encounters them */
2902         if ((page_table[i].allocated == BOXED_PAGE)
2903             && (page_table[i].bytes_used != 0)
2904             && (page_table[i].gen == generation)
2905             && ((page_table[i].write_protected == 0)
2906                 /* (This may be redundant as write_protected is now
2907                  * cleared before promotion.) */
2908                 || (page_table[i].dont_move == 1))) {
2909             int last_page;
2910
2911             /* The scavenge will start at the first_object_offset of page i.
2912              *
2913              * We need to find the full extent of this contiguous
2914              * block in case objects span pages.
2915              *
2916              * Now work forward until the end of this contiguous area
2917              * is found. A small area is preferred as there is a
2918              * better chance of its pages being write-protected. */
2919             for (last_page = i; ;last_page++) {
2920                 /* Check whether this is the last page in this
2921                  * contiguous block */
2922                 if ((page_table[last_page].bytes_used < 4096)
2923                     /* Or it is 4096 and is the last in the block */
2924                     || (!(page_table[last_page+1].allocated & BOXED_PAGE))
2925                     || (page_table[last_page+1].bytes_used == 0)
2926                     || (page_table[last_page+1].gen != generation)
2927                     || (page_table[last_page+1].first_object_offset == 0))
2928                     break;
2929             }
2930
2931             /* Do a limited check for write-protected pages. If all
2932              * pages are write-protected then no need to scavenge,
2933              * except if the pages are marked dont_move. */
2934             {
2935                 int j, all_wp = 1;
2936                 for (j = i; j <= last_page; j++)
2937                     if ((page_table[j].write_protected == 0)
2938                         || (page_table[j].dont_move != 0)) {
2939                         all_wp = 0;
2940                         break;
2941                     }
2942
2943                 if (!all_wp) {
2944                     int size;
2945
2946                     /* Calculate the size. */
2947                     if (last_page == i)
2948                         size = (page_table[last_page].bytes_used
2949                                 - page_table[i].first_object_offset)/4;
2950                     else
2951                         size = (page_table[last_page].bytes_used
2952                                 + (last_page-i)*4096
2953                                 - page_table[i].first_object_offset)/4;
2954                     
2955                     {
2956                         new_areas_ignore_page = last_page;
2957                         
2958                         scavenge(page_address(i) +
2959                                  page_table[i].first_object_offset,
2960                                  size);
2961
2962                     }
2963                 }
2964             }
2965
2966             i = last_page;
2967         }
2968     }
2969     FSHOW((stderr,
2970            "/done with one full scan of newspace generation %d\n",
2971            generation));
2972 }
2973
2974 /* Do a complete scavenge of the newspace generation. */
2975 static void
2976 scavenge_newspace_generation(int generation)
2977 {
2978     int i;
2979
2980     /* the new_areas array currently being written to by gc_alloc() */
2981     struct new_area (*current_new_areas)[] = &new_areas_1;
2982     int current_new_areas_index;
2983
2984     /* the new_areas created but the previous scavenge cycle */
2985     struct new_area (*previous_new_areas)[] = NULL;
2986     int previous_new_areas_index;
2987
2988     /* Flush the current regions updating the tables. */
2989     gc_alloc_update_all_page_tables();
2990
2991     /* Turn on the recording of new areas by gc_alloc(). */
2992     new_areas = current_new_areas;
2993     new_areas_index = 0;
2994
2995     /* Don't need to record new areas that get scavenged anyway during
2996      * scavenge_newspace_generation_one_scan. */
2997     record_new_objects = 1;
2998
2999     /* Start with a full scavenge. */
3000     scavenge_newspace_generation_one_scan(generation);
3001
3002     /* Record all new areas now. */
3003     record_new_objects = 2;
3004
3005     /* Flush the current regions updating the tables. */
3006     gc_alloc_update_all_page_tables();
3007
3008     /* Grab new_areas_index. */
3009     current_new_areas_index = new_areas_index;
3010
3011     /*FSHOW((stderr,
3012              "The first scan is finished; current_new_areas_index=%d.\n",
3013              current_new_areas_index));*/
3014
3015     while (current_new_areas_index > 0) {
3016         /* Move the current to the previous new areas */
3017         previous_new_areas = current_new_areas;
3018         previous_new_areas_index = current_new_areas_index;
3019
3020         /* Scavenge all the areas in previous new areas. Any new areas
3021          * allocated are saved in current_new_areas. */
3022
3023         /* Allocate an array for current_new_areas; alternating between
3024          * new_areas_1 and 2 */
3025         if (previous_new_areas == &new_areas_1)
3026             current_new_areas = &new_areas_2;
3027         else
3028             current_new_areas = &new_areas_1;
3029
3030         /* Set up for gc_alloc(). */
3031         new_areas = current_new_areas;
3032         new_areas_index = 0;
3033
3034         /* Check whether previous_new_areas had overflowed. */
3035         if (previous_new_areas_index >= NUM_NEW_AREAS) {
3036
3037             /* New areas of objects allocated have been lost so need to do a
3038              * full scan to be sure! If this becomes a problem try
3039              * increasing NUM_NEW_AREAS. */
3040             if (gencgc_verbose)
3041                 SHOW("new_areas overflow, doing full scavenge");
3042
3043             /* Don't need to record new areas that get scavenge anyway
3044              * during scavenge_newspace_generation_one_scan. */
3045             record_new_objects = 1;
3046
3047             scavenge_newspace_generation_one_scan(generation);
3048
3049             /* Record all new areas now. */
3050             record_new_objects = 2;
3051
3052             /* Flush the current regions updating the tables. */
3053             gc_alloc_update_all_page_tables();
3054
3055         } else {
3056
3057             /* Work through previous_new_areas. */
3058             for (i = 0; i < previous_new_areas_index; i++) {
3059                 /* FIXME: All these bare *4 and /4 should be something
3060                  * like BYTES_PER_WORD or WBYTES. */
3061                 int page = (*previous_new_areas)[i].page;
3062                 int offset = (*previous_new_areas)[i].offset;
3063                 int size = (*previous_new_areas)[i].size / 4;
3064                 gc_assert((*previous_new_areas)[i].size % 4 == 0);
3065                 scavenge(page_address(page)+offset, size);
3066             }
3067
3068             /* Flush the current regions updating the tables. */
3069             gc_alloc_update_all_page_tables();
3070         }
3071
3072         current_new_areas_index = new_areas_index;
3073
3074         /*FSHOW((stderr,
3075                  "The re-scan has finished; current_new_areas_index=%d.\n",
3076                  current_new_areas_index));*/
3077     }
3078
3079     /* Turn off recording of areas allocated by gc_alloc(). */
3080     record_new_objects = 0;
3081
3082 #if SC_NS_GEN_CK
3083     /* Check that none of the write_protected pages in this generation
3084      * have been written to. */
3085     for (i = 0; i < NUM_PAGES; i++) {
3086         if ((page_table[i].allocation != FREE_PAGE)
3087             && (page_table[i].bytes_used != 0)
3088             && (page_table[i].gen == generation)
3089             && (page_table[i].write_protected_cleared != 0)
3090             && (page_table[i].dont_move == 0)) {
3091             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d",
3092                  i, generation, page_table[i].dont_move);
3093         }
3094     }
3095 #endif
3096 }
3097 \f
3098 /* Un-write-protect all the pages in from_space. This is done at the
3099  * start of a GC else there may be many page faults while scavenging
3100  * the newspace (I've seen drive the system time to 99%). These pages
3101  * would need to be unprotected anyway before unmapping in
3102  * free_oldspace; not sure what effect this has on paging.. */
3103 static void
3104 unprotect_oldspace(void)
3105 {
3106     int i;
3107
3108     for (i = 0; i < last_free_page; i++) {
3109         if ((page_table[i].allocated != FREE_PAGE)
3110             && (page_table[i].bytes_used != 0)
3111             && (page_table[i].gen == from_space)) {
3112             void *page_start;
3113
3114             page_start = (void *)page_address(i);
3115
3116             /* Remove any write-protection. We should be able to rely
3117              * on the write-protect flag to avoid redundant calls. */
3118             if (page_table[i].write_protected) {
3119                 os_protect(page_start, 4096, OS_VM_PROT_ALL);
3120                 page_table[i].write_protected = 0;
3121             }
3122         }
3123     }
3124 }
3125
3126 /* Work through all the pages and free any in from_space. This
3127  * assumes that all objects have been copied or promoted to an older
3128  * generation. Bytes_allocated and the generation bytes_allocated
3129  * counter are updated. The number of bytes freed is returned. */
3130 extern void i586_bzero(void *addr, int nbytes);
3131 static int
3132 free_oldspace(void)
3133 {
3134     int bytes_freed = 0;
3135     int first_page, last_page;
3136
3137     first_page = 0;
3138
3139     do {
3140         /* Find a first page for the next region of pages. */
3141         while ((first_page < last_free_page)
3142                && ((page_table[first_page].allocated == FREE_PAGE)
3143                    || (page_table[first_page].bytes_used == 0)
3144                    || (page_table[first_page].gen != from_space)))
3145             first_page++;
3146
3147         if (first_page >= last_free_page)
3148             break;
3149
3150         /* Find the last page of this region. */
3151         last_page = first_page;
3152
3153         do {
3154             /* Free the page. */
3155             bytes_freed += page_table[last_page].bytes_used;
3156             generations[page_table[last_page].gen].bytes_allocated -=
3157                 page_table[last_page].bytes_used;
3158             page_table[last_page].allocated = FREE_PAGE;
3159             page_table[last_page].bytes_used = 0;
3160
3161             /* Remove any write-protection. We should be able to rely
3162              * on the write-protect flag to avoid redundant calls. */
3163             {
3164                 void  *page_start = (void *)page_address(last_page);
3165         
3166                 if (page_table[last_page].write_protected) {
3167                     os_protect(page_start, 4096, OS_VM_PROT_ALL);
3168                     page_table[last_page].write_protected = 0;
3169                 }
3170             }
3171             last_page++;
3172         }
3173         while ((last_page < last_free_page)
3174                && (page_table[last_page].allocated != FREE_PAGE)
3175                && (page_table[last_page].bytes_used != 0)
3176                && (page_table[last_page].gen == from_space));
3177
3178         /* Zero pages from first_page to (last_page-1).
3179          *
3180          * FIXME: Why not use os_zero(..) function instead of
3181          * hand-coding this again? (Check other gencgc_unmap_zero
3182          * stuff too. */
3183         if (gencgc_unmap_zero) {
3184             void *page_start, *addr;
3185
3186             page_start = (void *)page_address(first_page);
3187
3188             os_invalidate(page_start, 4096*(last_page-first_page));
3189             addr = os_validate(page_start, 4096*(last_page-first_page));
3190             if (addr == NULL || addr != page_start) {
3191                 /* Is this an error condition? I couldn't really tell from
3192                  * the old CMU CL code, which fprintf'ed a message with
3193                  * an exclamation point at the end. But I've never seen the
3194                  * message, so it must at least be unusual..
3195                  *
3196                  * (The same condition is also tested for in gc_free_heap.)
3197                  *
3198                  * -- WHN 19991129 */
3199                 lose("i586_bzero: page moved, 0x%08x ==> 0x%08x",
3200                      page_start,
3201                      addr);
3202             }
3203         } else {
3204             int *page_start;
3205
3206             page_start = (int *)page_address(first_page);
3207             i586_bzero(page_start, 4096*(last_page-first_page));
3208         }
3209
3210         first_page = last_page;
3211
3212     } while (first_page < last_free_page);
3213
3214     bytes_allocated -= bytes_freed;
3215     return bytes_freed;
3216 }
3217 \f
3218 #if 0
3219 /* Print some information about a pointer at the given address. */
3220 static void
3221 print_ptr(lispobj *addr)
3222 {
3223     /* If addr is in the dynamic space then out the page information. */
3224     int pi1 = find_page_index((void*)addr);
3225
3226     if (pi1 != -1)
3227         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %d  dont_move %d\n",
3228                 (unsigned int) addr,
3229                 pi1,
3230                 page_table[pi1].allocated,
3231                 page_table[pi1].gen,
3232                 page_table[pi1].bytes_used,
3233                 page_table[pi1].first_object_offset,
3234                 page_table[pi1].dont_move);
3235     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
3236             *(addr-4),
3237             *(addr-3),
3238             *(addr-2),
3239             *(addr-1),
3240             *(addr-0),
3241             *(addr+1),
3242             *(addr+2),
3243             *(addr+3),
3244             *(addr+4));
3245 }
3246 #endif
3247
3248 extern int undefined_tramp;
3249
3250 static void
3251 verify_space(lispobj *start, size_t words)
3252 {
3253     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
3254     int is_in_readonly_space =
3255         (READ_ONLY_SPACE_START <= (unsigned)start &&
3256          (unsigned)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3257
3258     while (words > 0) {
3259         size_t count = 1;
3260         lispobj thing = *(lispobj*)start;
3261
3262         if (is_lisp_pointer(thing)) {
3263             int page_index = find_page_index((void*)thing);
3264             int to_readonly_space =
3265                 (READ_ONLY_SPACE_START <= thing &&
3266                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3267             int to_static_space =
3268                 (STATIC_SPACE_START <= thing &&
3269                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3270
3271             /* Does it point to the dynamic space? */
3272             if (page_index != -1) {
3273                 /* If it's within the dynamic space it should point to a used
3274                  * page. XX Could check the offset too. */
3275                 if ((page_table[page_index].allocated != FREE_PAGE)
3276                     && (page_table[page_index].bytes_used == 0))
3277                     lose ("Ptr %x @ %x sees free page.", thing, start);
3278                 /* Check that it doesn't point to a forwarding pointer! */
3279                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3280                     lose("Ptr %x @ %x sees forwarding ptr.", thing, start);
3281                 }
3282                 /* Check that its not in the RO space as it would then be a
3283                  * pointer from the RO to the dynamic space. */
3284                 if (is_in_readonly_space) {
3285                     lose("ptr to dynamic space %x from RO space %x",
3286                          thing, start);
3287                 }
3288                 /* Does it point to a plausible object? This check slows
3289                  * it down a lot (so it's commented out).
3290                  *
3291                  * "a lot" is serious: it ate 50 minutes cpu time on
3292                  * my duron 950 before I came back from lunch and
3293                  * killed it.
3294                  *
3295                  *   FIXME: Add a variable to enable this
3296                  * dynamically. */
3297                 /*
3298                 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
3299                     lose("ptr %x to invalid object %x", thing, start); 
3300                 }
3301                 */
3302             } else {
3303                 /* Verify that it points to another valid space. */
3304                 if (!to_readonly_space && !to_static_space
3305                     && (thing != (unsigned)&undefined_tramp)) {
3306                     lose("Ptr %x @ %x sees junk.", thing, start);
3307                 }
3308             }
3309         } else {
3310             if (thing & 0x3) { /* Skip fixnums. FIXME: There should be an
3311                                 * is_fixnum for this. */
3312
3313                 switch(widetag_of(*start)) {
3314
3315                     /* boxed objects */
3316                 case SIMPLE_VECTOR_WIDETAG:
3317                 case RATIO_WIDETAG:
3318                 case COMPLEX_WIDETAG:
3319                 case SIMPLE_ARRAY_WIDETAG:
3320                 case COMPLEX_STRING_WIDETAG:
3321                 case COMPLEX_BIT_VECTOR_WIDETAG:
3322                 case COMPLEX_VECTOR_WIDETAG:
3323                 case COMPLEX_ARRAY_WIDETAG:
3324                 case CLOSURE_HEADER_WIDETAG:
3325                 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3326                 case VALUE_CELL_HEADER_WIDETAG:
3327                 case SYMBOL_HEADER_WIDETAG:
3328                 case BASE_CHAR_WIDETAG:
3329                 case UNBOUND_MARKER_WIDETAG:
3330                 case INSTANCE_HEADER_WIDETAG:
3331                 case FDEFN_WIDETAG:
3332                     count = 1;
3333                     break;
3334
3335                 case CODE_HEADER_WIDETAG:
3336                     {
3337                         lispobj object = *start;
3338                         struct code *code;
3339                         int nheader_words, ncode_words, nwords;
3340                         lispobj fheaderl;
3341                         struct simple_fun *fheaderp;
3342
3343                         code = (struct code *) start;
3344
3345                         /* Check that it's not in the dynamic space.
3346                          * FIXME: Isn't is supposed to be OK for code
3347                          * objects to be in the dynamic space these days? */
3348                         if (is_in_dynamic_space
3349                             /* It's ok if it's byte compiled code. The trace
3350                              * table offset will be a fixnum if it's x86
3351                              * compiled code - check.
3352                              *
3353                              * FIXME: #^#@@! lack of abstraction here..
3354                              * This line can probably go away now that
3355                              * there's no byte compiler, but I've got
3356                              * too much to worry about right now to try
3357                              * to make sure. -- WHN 2001-10-06 */
3358                             && !(code->trace_table_offset & 0x3)
3359                             /* Only when enabled */
3360                             && verify_dynamic_code_check) {
3361                             FSHOW((stderr,
3362                                    "/code object at %x in the dynamic space\n",
3363                                    start));
3364                         }
3365
3366                         ncode_words = fixnum_value(code->code_size);
3367                         nheader_words = HeaderValue(object);
3368                         nwords = ncode_words + nheader_words;
3369                         nwords = CEILING(nwords, 2);
3370                         /* Scavenge the boxed section of the code data block */
3371                         verify_space(start + 1, nheader_words - 1);
3372
3373                         /* Scavenge the boxed section of each function
3374                          * object in the code data block. */
3375                         fheaderl = code->entry_points;
3376                         while (fheaderl != NIL) {
3377                             fheaderp =
3378                                 (struct simple_fun *) native_pointer(fheaderl);
3379                             gc_assert(widetag_of(fheaderp->header) == SIMPLE_FUN_HEADER_WIDETAG);
3380                             verify_space(&fheaderp->name, 1);
3381                             verify_space(&fheaderp->arglist, 1);
3382                             verify_space(&fheaderp->type, 1);
3383                             fheaderl = fheaderp->next;
3384                         }
3385                         count = nwords;
3386                         break;
3387                     }
3388         
3389                     /* unboxed objects */
3390                 case BIGNUM_WIDETAG:
3391                 case SINGLE_FLOAT_WIDETAG:
3392                 case DOUBLE_FLOAT_WIDETAG:
3393 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3394                 case LONG_FLOAT_WIDETAG:
3395 #endif
3396 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3397                 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3398 #endif
3399 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3400                 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3401 #endif
3402 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3403                 case COMPLEX_LONG_FLOAT_WIDETAG:
3404 #endif
3405                 case SIMPLE_STRING_WIDETAG:
3406                 case SIMPLE_BIT_VECTOR_WIDETAG:
3407                 case SIMPLE_ARRAY_NIL_WIDETAG:
3408                 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3409                 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3410                 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3411                 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3412                 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3413 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3414                 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3415 #endif
3416 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3417                 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3418 #endif
3419 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
3420                 case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
3421 #endif
3422 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3423                 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3424 #endif
3425                 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3426                 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3427 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3428                 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3429 #endif
3430 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3431                 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3432 #endif
3433 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3434                 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3435 #endif
3436 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3437                 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3438 #endif
3439                 case SAP_WIDETAG:
3440                 case WEAK_POINTER_WIDETAG:
3441                     count = (sizetab[widetag_of(*start)])(start);
3442                     break;
3443
3444                 default:
3445                     gc_abort();
3446                 }
3447             }
3448         }
3449         start += count;
3450         words -= count;
3451     }
3452 }
3453
3454 static void
3455 verify_gc(void)
3456 {
3457     /* FIXME: It would be nice to make names consistent so that
3458      * foo_size meant size *in* *bytes* instead of size in some
3459      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3460      * Some counts of lispobjs are called foo_count; it might be good
3461      * to grep for all foo_size and rename the appropriate ones to
3462      * foo_count. */
3463     int read_only_space_size =
3464         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3465         - (lispobj*)READ_ONLY_SPACE_START;
3466     int static_space_size =
3467         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3468         - (lispobj*)STATIC_SPACE_START;
3469     struct thread *th;
3470     for_each_thread(th) {
3471     int binding_stack_size =
3472             (lispobj*)SymbolValue(BINDING_STACK_POINTER,th)
3473             - (lispobj*)th->binding_stack_start;
3474         verify_space(th->binding_stack_start, binding_stack_size);
3475     }
3476     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3477     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
3478 }
3479
3480 static void
3481 verify_generation(int  generation)
3482 {
3483     int i;
3484
3485     for (i = 0; i < last_free_page; i++) {
3486         if ((page_table[i].allocated != FREE_PAGE)
3487             && (page_table[i].bytes_used != 0)
3488             && (page_table[i].gen == generation)) {
3489             int last_page;
3490             int region_allocation = page_table[i].allocated;
3491
3492             /* This should be the start of a contiguous block */
3493             gc_assert(page_table[i].first_object_offset == 0);
3494
3495             /* Need to find the full extent of this contiguous block in case
3496                objects span pages. */
3497
3498             /* Now work forward until the end of this contiguous area is
3499                found. */
3500             for (last_page = i; ;last_page++)
3501                 /* Check whether this is the last page in this contiguous
3502                  * block. */
3503                 if ((page_table[last_page].bytes_used < 4096)
3504                     /* Or it is 4096 and is the last in the block */
3505                     || (page_table[last_page+1].allocated != region_allocation)
3506                     || (page_table[last_page+1].bytes_used == 0)
3507                     || (page_table[last_page+1].gen != generation)
3508                     || (page_table[last_page+1].first_object_offset == 0))
3509                     break;
3510
3511             verify_space(page_address(i), (page_table[last_page].bytes_used
3512                                            + (last_page-i)*4096)/4);
3513             i = last_page;
3514         }
3515     }
3516 }
3517
3518 /* Check that all the free space is zero filled. */
3519 static void
3520 verify_zero_fill(void)
3521 {
3522     int page;
3523
3524     for (page = 0; page < last_free_page; page++) {
3525         if (page_table[page].allocated == FREE_PAGE) {
3526             /* The whole page should be zero filled. */
3527             int *start_addr = (int *)page_address(page);
3528             int size = 1024;
3529             int i;
3530             for (i = 0; i < size; i++) {
3531                 if (start_addr[i] != 0) {
3532                     lose("free page not zero at %x", start_addr + i);
3533                 }
3534             }
3535         } else {
3536             int free_bytes = 4096 - page_table[page].bytes_used;
3537             if (free_bytes > 0) {
3538                 int *start_addr = (int *)((unsigned)page_address(page)
3539                                           + page_table[page].bytes_used);
3540                 int size = free_bytes / 4;
3541                 int i;
3542                 for (i = 0; i < size; i++) {
3543                     if (start_addr[i] != 0) {
3544                         lose("free region not zero at %x", start_addr + i);
3545                     }
3546                 }
3547             }
3548         }
3549     }
3550 }
3551
3552 /* External entry point for verify_zero_fill */
3553 void
3554 gencgc_verify_zero_fill(void)
3555 {
3556     /* Flush the alloc regions updating the tables. */
3557     gc_alloc_update_all_page_tables();
3558     SHOW("verifying zero fill");
3559     verify_zero_fill();
3560 }
3561
3562 static void
3563 verify_dynamic_space(void)
3564 {
3565     int i;
3566
3567     for (i = 0; i < NUM_GENERATIONS; i++)
3568         verify_generation(i);
3569
3570     if (gencgc_enable_verify_zero_fill)
3571         verify_zero_fill();
3572 }
3573 \f
3574 /* Write-protect all the dynamic boxed pages in the given generation. */
3575 static void
3576 write_protect_generation_pages(int generation)
3577 {
3578     int i;
3579
3580     gc_assert(generation < NUM_GENERATIONS);
3581
3582     for (i = 0; i < last_free_page; i++)
3583         if ((page_table[i].allocated == BOXED_PAGE)
3584             && (page_table[i].bytes_used != 0)
3585             && (page_table[i].gen == generation))  {
3586             void *page_start;
3587
3588             page_start = (void *)page_address(i);
3589
3590             os_protect(page_start,
3591                        4096,
3592                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3593
3594             /* Note the page as protected in the page tables. */
3595             page_table[i].write_protected = 1;
3596         }
3597
3598     if (gencgc_verbose > 1) {
3599         FSHOW((stderr,
3600                "/write protected %d of %d pages in generation %d\n",
3601                count_write_protect_generation_pages(generation),
3602                count_generation_pages(generation),
3603                generation));
3604     }
3605 }
3606
3607 /* Garbage collect a generation. If raise is 0 then the remains of the
3608  * generation are not raised to the next generation. */
3609 static void
3610 garbage_collect_generation(int generation, int raise)
3611 {
3612     unsigned long bytes_freed;
3613     unsigned long i;
3614     unsigned long static_space_size;
3615     struct thread *th;
3616     gc_assert(generation <= (NUM_GENERATIONS-1));
3617
3618     /* The oldest generation can't be raised. */
3619     gc_assert((generation != (NUM_GENERATIONS-1)) || (raise == 0));
3620
3621     /* Initialize the weak pointer list. */
3622     weak_pointers = NULL;
3623
3624     /* When a generation is not being raised it is transported to a
3625      * temporary generation (NUM_GENERATIONS), and lowered when
3626      * done. Set up this new generation. There should be no pages
3627      * allocated to it yet. */
3628     if (!raise)
3629         gc_assert(generations[NUM_GENERATIONS].bytes_allocated == 0);
3630
3631     /* Set the global src and dest. generations */
3632     from_space = generation;
3633     if (raise)
3634         new_space = generation+1;
3635     else
3636         new_space = NUM_GENERATIONS;
3637
3638     /* Change to a new space for allocation, resetting the alloc_start_page */
3639     gc_alloc_generation = new_space;
3640     generations[new_space].alloc_start_page = 0;
3641     generations[new_space].alloc_unboxed_start_page = 0;
3642     generations[new_space].alloc_large_start_page = 0;
3643     generations[new_space].alloc_large_unboxed_start_page = 0;
3644
3645     /* Before any pointers are preserved, the dont_move flags on the
3646      * pages need to be cleared. */
3647     for (i = 0; i < last_free_page; i++)
3648         page_table[i].dont_move = 0;
3649
3650     /* Un-write-protect the old-space pages. This is essential for the
3651      * promoted pages as they may contain pointers into the old-space
3652      * which need to be scavenged. It also helps avoid unnecessary page
3653      * faults as forwarding pointers are written into them. They need to
3654      * be un-protected anyway before unmapping later. */
3655     unprotect_oldspace();
3656
3657     /* Scavenge the stacks' conservative roots. */
3658     for_each_thread(th) {
3659         void **ptr;
3660 #ifdef LISP_FEATURE_SB_THREAD
3661         struct user_regs_struct regs;
3662         if(ptrace(PTRACE_GETREGS,th->pid,0,&regs)){
3663             /* probably doesn't exist any more. */
3664             fprintf(stderr,"child pid %d, %s\n",th->pid,strerror(errno));
3665             perror("PTRACE_GETREGS");
3666         }
3667         preserve_pointer(regs.ebx);
3668         preserve_pointer(regs.ecx);
3669         preserve_pointer(regs.edx);
3670         preserve_pointer(regs.esi);
3671         preserve_pointer(regs.edi);
3672         preserve_pointer(regs.ebp);
3673         preserve_pointer(regs.eax);
3674 #endif
3675         for (ptr = th->control_stack_end;
3676 #ifdef LISP_FEATURE_SB_THREAD
3677              ptr > regs.esp;
3678 #else
3679              ptr > (void **)&raise;
3680 #endif
3681              ptr--) {
3682             preserve_pointer(*ptr);
3683         }
3684     }
3685
3686 #if QSHOW
3687     if (gencgc_verbose > 1) {
3688         int num_dont_move_pages = count_dont_move_pages();
3689         fprintf(stderr,
3690                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3691                 num_dont_move_pages,
3692                 /* FIXME: 4096 should be symbolic constant here and
3693                  * prob'ly elsewhere too. */
3694                 num_dont_move_pages * 4096);
3695     }
3696 #endif
3697
3698     /* Scavenge all the rest of the roots. */
3699
3700     /* Scavenge the Lisp functions of the interrupt handlers, taking
3701      * care to avoid SIG_DFL and SIG_IGN. */
3702     for_each_thread(th) {
3703         struct interrupt_data *data=th->interrupt_data;
3704     for (i = 0; i < NSIG; i++) {
3705             union interrupt_handler handler = data->interrupt_handlers[i];
3706         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3707             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3708                 scavenge((lispobj *)(data->interrupt_handlers + i), 1);
3709             }
3710         }
3711     }
3712     /* Scavenge the binding stacks. */
3713  {
3714      struct thread *th;
3715      for_each_thread(th) {
3716          long len= (lispobj *)SymbolValue(BINDING_STACK_POINTER,th) -
3717              th->binding_stack_start;
3718          scavenge((lispobj *) th->binding_stack_start,len);
3719 #ifdef LISP_FEATURE_SB_THREAD
3720          /* do the tls as well */
3721          len=fixnum_value(SymbolValue(FREE_TLS_INDEX,0)) -
3722              (sizeof (struct thread))/(sizeof (lispobj));
3723          scavenge((lispobj *) (th+1),len);
3724 #endif
3725         }
3726     }
3727
3728     /* The original CMU CL code had scavenge-read-only-space code
3729      * controlled by the Lisp-level variable
3730      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3731      * wasn't documented under what circumstances it was useful or
3732      * safe to turn it on, so it's been turned off in SBCL. If you
3733      * want/need this functionality, and can test and document it,
3734      * please submit a patch. */
3735 #if 0
3736     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3737         unsigned long read_only_space_size =
3738             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3739             (lispobj*)READ_ONLY_SPACE_START;
3740         FSHOW((stderr,
3741                "/scavenge read only space: %d bytes\n",
3742                read_only_space_size * sizeof(lispobj)));
3743         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3744     }
3745 #endif
3746
3747     /* Scavenge static space. */
3748     static_space_size =
3749         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3750         (lispobj *)STATIC_SPACE_START;
3751     if (gencgc_verbose > 1) {
3752         FSHOW((stderr,
3753                "/scavenge static space: %d bytes\n",
3754                static_space_size * sizeof(lispobj)));
3755     }
3756     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3757
3758     /* All generations but the generation being GCed need to be
3759      * scavenged. The new_space generation needs special handling as
3760      * objects may be moved in - it is handled separately below. */
3761     for (i = 0; i < NUM_GENERATIONS; i++) {
3762         if ((i != generation) && (i != new_space)) {
3763             scavenge_generation(i);
3764         }
3765     }
3766
3767     /* Finally scavenge the new_space generation. Keep going until no
3768      * more objects are moved into the new generation */
3769     scavenge_newspace_generation(new_space);
3770
3771     /* FIXME: I tried reenabling this check when debugging unrelated
3772      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3773      * Since the current GC code seems to work well, I'm guessing that
3774      * this debugging code is just stale, but I haven't tried to
3775      * figure it out. It should be figured out and then either made to
3776      * work or just deleted. */
3777 #define RESCAN_CHECK 0
3778 #if RESCAN_CHECK
3779     /* As a check re-scavenge the newspace once; no new objects should
3780      * be found. */
3781     {
3782         int old_bytes_allocated = bytes_allocated;
3783         int bytes_allocated;
3784
3785         /* Start with a full scavenge. */
3786         scavenge_newspace_generation_one_scan(new_space);
3787
3788         /* Flush the current regions, updating the tables. */
3789         gc_alloc_update_all_page_tables();
3790
3791         bytes_allocated = bytes_allocated - old_bytes_allocated;
3792
3793         if (bytes_allocated != 0) {
3794             lose("Rescan of new_space allocated %d more bytes.",
3795                  bytes_allocated);
3796         }
3797     }
3798 #endif
3799
3800     scan_weak_pointers();
3801
3802     /* Flush the current regions, updating the tables. */
3803     gc_alloc_update_all_page_tables();
3804
3805     /* Free the pages in oldspace, but not those marked dont_move. */
3806     bytes_freed = free_oldspace();
3807
3808     /* If the GC is not raising the age then lower the generation back
3809      * to its normal generation number */
3810     if (!raise) {
3811         for (i = 0; i < last_free_page; i++)
3812             if ((page_table[i].bytes_used != 0)
3813                 && (page_table[i].gen == NUM_GENERATIONS))
3814                 page_table[i].gen = generation;
3815         gc_assert(generations[generation].bytes_allocated == 0);
3816         generations[generation].bytes_allocated =
3817             generations[NUM_GENERATIONS].bytes_allocated;
3818         generations[NUM_GENERATIONS].bytes_allocated = 0;
3819     }
3820
3821     /* Reset the alloc_start_page for generation. */
3822     generations[generation].alloc_start_page = 0;
3823     generations[generation].alloc_unboxed_start_page = 0;
3824     generations[generation].alloc_large_start_page = 0;
3825     generations[generation].alloc_large_unboxed_start_page = 0;
3826
3827     if (generation >= verify_gens) {
3828         if (gencgc_verbose)
3829             SHOW("verifying");
3830         verify_gc();
3831         verify_dynamic_space();
3832     }
3833
3834     /* Set the new gc trigger for the GCed generation. */
3835     generations[generation].gc_trigger =
3836         generations[generation].bytes_allocated
3837         + generations[generation].bytes_consed_between_gc;
3838
3839     if (raise)
3840         generations[generation].num_gc = 0;
3841     else
3842         ++generations[generation].num_gc;
3843 }
3844
3845 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3846 int
3847 update_x86_dynamic_space_free_pointer(void)
3848 {
3849     int last_page = -1;
3850     int i;
3851
3852     for (i = 0; i < NUM_PAGES; i++)
3853         if ((page_table[i].allocated != FREE_PAGE)
3854             && (page_table[i].bytes_used != 0))
3855             last_page = i;
3856
3857     last_free_page = last_page+1;
3858
3859     SetSymbolValue(ALLOCATION_POINTER,
3860                    (lispobj)(((char *)heap_base) + last_free_page*4096),0);
3861     return 0; /* dummy value: return something ... */
3862 }
3863
3864 /* GC all generations newer than last_gen, raising the objects in each
3865  * to the next older generation - we finish when all generations below
3866  * last_gen are empty.  Then if last_gen is due for a GC, or if
3867  * last_gen==NUM_GENERATIONS (the scratch generation?  eh?) we GC that
3868  * too.  The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3869  *
3870  * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3871  * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3872  
3873 void
3874 collect_garbage(unsigned last_gen)
3875 {
3876     int gen = 0;
3877     int raise;
3878     int gen_to_wp;
3879     int i;
3880
3881     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
3882
3883     if (last_gen > NUM_GENERATIONS) {
3884         FSHOW((stderr,
3885                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3886                last_gen));
3887         last_gen = 0;
3888     }
3889
3890     /* Flush the alloc regions updating the tables. */
3891     gc_alloc_update_all_page_tables();
3892
3893     /* Verify the new objects created by Lisp code. */
3894     if (pre_verify_gen_0) {
3895         FSHOW((stderr, "pre-checking generation 0\n"));
3896         verify_generation(0);
3897     }
3898
3899     if (gencgc_verbose > 1)
3900         print_generation_stats(0);
3901
3902     do {
3903         /* Collect the generation. */
3904
3905         if (gen >= gencgc_oldest_gen_to_gc) {
3906             /* Never raise the oldest generation. */
3907             raise = 0;
3908         } else {
3909             raise =
3910                 (gen < last_gen)
3911                 || (generations[gen].num_gc >= generations[gen].trigger_age);
3912         }
3913
3914         if (gencgc_verbose > 1) {
3915             FSHOW((stderr,
3916                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3917                    gen,
3918                    raise,
3919                    generations[gen].bytes_allocated,
3920                    generations[gen].gc_trigger,
3921                    generations[gen].num_gc));
3922         }
3923
3924         /* If an older generation is being filled, then update its
3925          * memory age. */
3926         if (raise == 1) {
3927             generations[gen+1].cum_sum_bytes_allocated +=
3928                 generations[gen+1].bytes_allocated;
3929         }
3930
3931         garbage_collect_generation(gen, raise);
3932
3933         /* Reset the memory age cum_sum. */
3934         generations[gen].cum_sum_bytes_allocated = 0;
3935
3936         if (gencgc_verbose > 1) {
3937             FSHOW((stderr, "GC of generation %d finished:\n", gen));
3938             print_generation_stats(0);
3939         }
3940
3941         gen++;
3942     } while ((gen <= gencgc_oldest_gen_to_gc)
3943              && ((gen < last_gen)
3944                  || ((gen <= gencgc_oldest_gen_to_gc)
3945                      && raise
3946                      && (generations[gen].bytes_allocated
3947                          > generations[gen].gc_trigger)
3948                      && (gen_av_mem_age(gen)
3949                          > generations[gen].min_av_mem_age))));
3950
3951     /* Now if gen-1 was raised all generations before gen are empty.
3952      * If it wasn't raised then all generations before gen-1 are empty.
3953      *
3954      * Now objects within this gen's pages cannot point to younger
3955      * generations unless they are written to. This can be exploited
3956      * by write-protecting the pages of gen; then when younger
3957      * generations are GCed only the pages which have been written
3958      * need scanning. */
3959     if (raise)
3960         gen_to_wp = gen;
3961     else
3962         gen_to_wp = gen - 1;
3963
3964     /* There's not much point in WPing pages in generation 0 as it is
3965      * never scavenged (except promoted pages). */
3966     if ((gen_to_wp > 0) && enable_page_protection) {
3967         /* Check that they are all empty. */
3968         for (i = 0; i < gen_to_wp; i++) {
3969             if (generations[i].bytes_allocated)
3970                 lose("trying to write-protect gen. %d when gen. %d nonempty",
3971                      gen_to_wp, i);
3972         }
3973         write_protect_generation_pages(gen_to_wp);
3974     }
3975
3976     /* Set gc_alloc() back to generation 0. The current regions should
3977      * be flushed after the above GCs. */
3978     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
3979     gc_alloc_generation = 0;
3980
3981     update_x86_dynamic_space_free_pointer();
3982
3983     SHOW("returning from collect_garbage");
3984 }
3985
3986 /* This is called by Lisp PURIFY when it is finished. All live objects
3987  * will have been moved to the RO and Static heaps. The dynamic space
3988  * will need a full re-initialization. We don't bother having Lisp
3989  * PURIFY flush the current gc_alloc() region, as the page_tables are
3990  * re-initialized, and every page is zeroed to be sure. */
3991 void
3992 gc_free_heap(void)
3993 {
3994     int page;
3995
3996     if (gencgc_verbose > 1)
3997         SHOW("entering gc_free_heap");
3998
3999     for (page = 0; page < NUM_PAGES; page++) {
4000         /* Skip free pages which should already be zero filled. */
4001         if (page_table[page].allocated != FREE_PAGE) {
4002             void *page_start, *addr;
4003
4004             /* Mark the page free. The other slots are assumed invalid
4005              * when it is a FREE_PAGE and bytes_used is 0 and it
4006              * should not be write-protected -- except that the
4007              * generation is used for the current region but it sets
4008              * that up. */
4009             page_table[page].allocated = FREE_PAGE;
4010             page_table[page].bytes_used = 0;
4011
4012             /* Zero the page. */
4013             page_start = (void *)page_address(page);
4014
4015             /* First, remove any write-protection. */
4016             os_protect(page_start, 4096, OS_VM_PROT_ALL);
4017             page_table[page].write_protected = 0;
4018
4019             os_invalidate(page_start,4096);
4020             addr = os_validate(page_start,4096);
4021             if (addr == NULL || addr != page_start) {
4022                 lose("gc_free_heap: page moved, 0x%08x ==> 0x%08x",
4023                      page_start,
4024                      addr);
4025             }
4026         } else if (gencgc_zero_check_during_free_heap) {
4027             /* Double-check that the page is zero filled. */
4028             int *page_start, i;
4029             gc_assert(page_table[page].allocated == FREE_PAGE);
4030             gc_assert(page_table[page].bytes_used == 0);
4031             page_start = (int *)page_address(page);
4032             for (i=0; i<1024; i++) {
4033                 if (page_start[i] != 0) {
4034                     lose("free region not zero at %x", page_start + i);
4035                 }
4036             }
4037         }
4038     }
4039
4040     bytes_allocated = 0;
4041
4042     /* Initialize the generations. */
4043     for (page = 0; page < NUM_GENERATIONS; page++) {
4044         generations[page].alloc_start_page = 0;
4045         generations[page].alloc_unboxed_start_page = 0;
4046         generations[page].alloc_large_start_page = 0;
4047         generations[page].alloc_large_unboxed_start_page = 0;
4048         generations[page].bytes_allocated = 0;
4049         generations[page].gc_trigger = 2000000;
4050         generations[page].num_gc = 0;
4051         generations[page].cum_sum_bytes_allocated = 0;
4052     }
4053
4054     if (gencgc_verbose > 1)
4055         print_generation_stats(0);
4056
4057     /* Initialize gc_alloc(). */
4058     gc_alloc_generation = 0;
4059
4060     gc_set_region_empty(&boxed_region);
4061     gc_set_region_empty(&unboxed_region);
4062
4063     last_free_page = 0;
4064     SetSymbolValue(ALLOCATION_POINTER, (lispobj)((char *)heap_base),0);
4065
4066     if (verify_after_free_heap) {
4067         /* Check whether purify has left any bad pointers. */
4068         if (gencgc_verbose)
4069             SHOW("checking after free_heap\n");
4070         verify_gc();
4071     }
4072 }
4073 \f
4074 void
4075 gc_init(void)
4076 {
4077     int i;
4078
4079     gc_init_tables();
4080     scavtab[SIMPLE_VECTOR_WIDETAG] = scav_vector;
4081     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4082     transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4083
4084     heap_base = (void*)DYNAMIC_SPACE_START;
4085
4086     /* Initialize each page structure. */
4087     for (i = 0; i < NUM_PAGES; i++) {
4088         /* Initialize all pages as free. */
4089         page_table[i].allocated = FREE_PAGE;
4090         page_table[i].bytes_used = 0;
4091
4092         /* Pages are not write-protected at startup. */
4093         page_table[i].write_protected = 0;
4094     }
4095
4096     bytes_allocated = 0;
4097
4098     /* Initialize the generations.
4099      *
4100      * FIXME: very similar to code in gc_free_heap(), should be shared */
4101     for (i = 0; i < NUM_GENERATIONS; i++) {
4102         generations[i].alloc_start_page = 0;
4103         generations[i].alloc_unboxed_start_page = 0;
4104         generations[i].alloc_large_start_page = 0;
4105         generations[i].alloc_large_unboxed_start_page = 0;
4106         generations[i].bytes_allocated = 0;
4107         generations[i].gc_trigger = 2000000;
4108         generations[i].num_gc = 0;
4109         generations[i].cum_sum_bytes_allocated = 0;
4110         /* the tune-able parameters */
4111         generations[i].bytes_consed_between_gc = 2000000;
4112         generations[i].trigger_age = 1;
4113         generations[i].min_av_mem_age = 0.75;
4114     }
4115
4116     /* Initialize gc_alloc. */
4117     gc_alloc_generation = 0;
4118     gc_set_region_empty(&boxed_region);
4119     gc_set_region_empty(&unboxed_region);
4120
4121     last_free_page = 0;
4122
4123 }
4124
4125 /*  Pick up the dynamic space from after a core load.
4126  *
4127  *  The ALLOCATION_POINTER points to the end of the dynamic space.
4128  *
4129  *  XX A scan is needed to identify the closest first objects for pages. */
4130 static void
4131 gencgc_pickup_dynamic(void)
4132 {
4133     int page = 0;
4134     int addr = DYNAMIC_SPACE_START;
4135     int alloc_ptr = SymbolValue(ALLOCATION_POINTER,0);
4136
4137     /* Initialize the first region. */
4138     do {
4139         page_table[page].allocated = BOXED_PAGE;
4140         page_table[page].gen = 0;
4141         page_table[page].bytes_used = 4096;
4142         page_table[page].large_object = 0;
4143         page_table[page].first_object_offset =
4144             (void *)DYNAMIC_SPACE_START - page_address(page);
4145         addr += 4096;
4146         page++;
4147     } while (addr < alloc_ptr);
4148
4149     generations[0].bytes_allocated = 4096*page;
4150     bytes_allocated = 4096*page;
4151
4152 }
4153
4154 void
4155 gc_initialize_pointers(void)
4156 {
4157     gencgc_pickup_dynamic();
4158 }
4159
4160
4161 \f
4162
4163 extern boolean maybe_gc_pending ;
4164 /* alloc(..) is the external interface for memory allocation. It
4165  * allocates to generation 0. It is not called from within the garbage
4166  * collector as it is only external uses that need the check for heap
4167  * size (GC trigger) and to disable the interrupts (interrupts are
4168  * always disabled during a GC).
4169  *
4170  * The vops that call alloc(..) assume that the returned space is zero-filled.
4171  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4172  *
4173  * The check for a GC trigger is only performed when the current
4174  * region is full, so in most cases it's not needed. */
4175
4176 char *
4177 alloc(int nbytes)
4178 {
4179     struct thread *th=arch_os_get_current_thread();
4180     struct alloc_region *region= 
4181         th ? &(th->alloc_region) : &boxed_region; 
4182     void *new_obj;
4183     void *new_free_pointer;
4184
4185     /* Check for alignment allocation problems. */
4186     gc_assert((((unsigned)region->free_pointer & 0x7) == 0)
4187               && ((nbytes & 0x7) == 0));
4188     if(all_threads)
4189         /* there are a few places in the C code that allocate data in the
4190          * heap before Lisp starts.  This is before interrupts are enabled,
4191          * so we don't need to check for pseudo-atomic */
4192         gc_assert(SymbolValue(PSEUDO_ATOMIC_ATOMIC,th));
4193
4194     /* maybe we can do this quickly ... */
4195     new_free_pointer = region->free_pointer + nbytes;
4196     if (new_free_pointer <= region->end_addr) {
4197         new_obj = (void*)(region->free_pointer);
4198         region->free_pointer = new_free_pointer;
4199         return(new_obj);        /* yup */
4200     }
4201     
4202     /* we have to go the long way around, it seems.  Check whether 
4203      * we should GC in the near future
4204      */
4205     if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
4206         auto_gc_trigger *= 2;
4207         /* set things up so that GC happens when we finish the PA
4208          * section.  */
4209         maybe_gc_pending=1;
4210         SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(1),th);
4211     }
4212     new_obj = gc_alloc_with_region(nbytes,0,region,0);
4213     return (new_obj);
4214 }
4215
4216 \f
4217 /*
4218  * noise to manipulate the gc trigger stuff
4219  */
4220
4221 void
4222 set_auto_gc_trigger(os_vm_size_t dynamic_usage)
4223 {
4224     auto_gc_trigger += dynamic_usage;
4225 }
4226
4227 void
4228 clear_auto_gc_trigger(void)
4229 {
4230     auto_gc_trigger = 0;
4231 }
4232 \f
4233 /* Find the code object for the given pc, or return NULL on failure.
4234  *
4235  * FIXME: PC shouldn't be lispobj*, should it? Maybe void*? */
4236 lispobj *
4237 component_ptr_from_pc(lispobj *pc)
4238 {
4239     lispobj *object = NULL;
4240
4241     if ( (object = search_read_only_space(pc)) )
4242         ;
4243     else if ( (object = search_static_space(pc)) )
4244         ;
4245     else
4246         object = search_dynamic_space(pc);
4247
4248     if (object) /* if we found something */
4249         if (widetag_of(*object) == CODE_HEADER_WIDETAG) /* if it's a code object */
4250             return(object);
4251
4252     return (NULL);
4253 }
4254 \f
4255 /*
4256  * shared support for the OS-dependent signal handlers which
4257  * catch GENCGC-related write-protect violations
4258  */
4259
4260 void unhandled_sigmemoryfault(void);
4261
4262 /* Depending on which OS we're running under, different signals might
4263  * be raised for a violation of write protection in the heap. This
4264  * function factors out the common generational GC magic which needs
4265  * to invoked in this case, and should be called from whatever signal
4266  * handler is appropriate for the OS we're running under.
4267  *
4268  * Return true if this signal is a normal generational GC thing that
4269  * we were able to handle, or false if it was abnormal and control
4270  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
4271
4272 int
4273 gencgc_handle_wp_violation(void* fault_addr)
4274 {
4275     int  page_index = find_page_index(fault_addr);
4276
4277 #if defined QSHOW_SIGNALS
4278     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4279            fault_addr, page_index));
4280 #endif
4281
4282     /* Check whether the fault is within the dynamic space. */
4283     if (page_index == (-1)) {
4284
4285         /* It can be helpful to be able to put a breakpoint on this
4286          * case to help diagnose low-level problems. */
4287         unhandled_sigmemoryfault();
4288
4289         /* not within the dynamic space -- not our responsibility */
4290         return 0;
4291
4292     } else {
4293
4294         /* The only acceptable reason for an signal like this from the
4295          * heap is that the generational GC write-protected the page. */
4296         if (page_table[page_index].write_protected != 1) {
4297             lose("access failure in heap page not marked as write-protected");
4298         }
4299         
4300         /* Unprotect the page. */
4301         os_protect(page_address(page_index), 4096, OS_VM_PROT_ALL);
4302         page_table[page_index].write_protected = 0;
4303         page_table[page_index].write_protected_cleared = 1;
4304
4305         /* Don't worry, we can handle it. */
4306         return 1;
4307     }
4308 }
4309
4310 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4311  * it's not just a case of the program hitting the write barrier, and
4312  * are about to let Lisp deal with it. It's basically just a
4313  * convenient place to set a gdb breakpoint. */
4314 void
4315 unhandled_sigmemoryfault()
4316 {}
4317
4318 gc_alloc_update_all_page_tables(void)
4319 {
4320     /* Flush the alloc regions updating the tables. */
4321     struct thread *th;
4322     for_each_thread(th) 
4323         gc_alloc_update_page_tables(0, &th->alloc_region);
4324     gc_alloc_update_page_tables(1, &unboxed_region);
4325     gc_alloc_update_page_tables(0, &boxed_region);
4326 }
4327 void 
4328 gc_set_region_empty(struct alloc_region *region)
4329 {
4330     region->first_page = 0;
4331     region->last_page = -1;
4332     region->start_addr = page_address(0);
4333     region->free_pointer = page_address(0);
4334     region->end_addr = page_address(0);
4335 }
4336