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