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