0.8.14.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]) == BASE_CHAR_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]) == BASE_CHAR_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 BASE_CHAR_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         case COMPLEX_VECTOR_NIL_WIDETAG:
2149         case COMPLEX_BIT_VECTOR_WIDETAG:
2150         case COMPLEX_VECTOR_WIDETAG:
2151         case COMPLEX_ARRAY_WIDETAG:
2152         case VALUE_CELL_HEADER_WIDETAG:
2153         case SYMBOL_HEADER_WIDETAG:
2154         case FDEFN_WIDETAG:
2155         case CODE_HEADER_WIDETAG:
2156         case BIGNUM_WIDETAG:
2157         case SINGLE_FLOAT_WIDETAG:
2158         case DOUBLE_FLOAT_WIDETAG:
2159 #ifdef LONG_FLOAT_WIDETAG
2160         case LONG_FLOAT_WIDETAG:
2161 #endif
2162         case SIMPLE_BASE_STRING_WIDETAG:
2163         case SIMPLE_BIT_VECTOR_WIDETAG:
2164         case SIMPLE_ARRAY_NIL_WIDETAG:
2165         case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2166         case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2167         case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2168         case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2169         case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2170         case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2171         case SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG:
2172         case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2173         case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2174 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2175         case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2176 #endif
2177 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2178         case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2179 #endif
2180 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
2181         case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
2182 #endif
2183 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2184         case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2185 #endif
2186         case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2187         case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2188 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2189         case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2190 #endif
2191 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2192         case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2193 #endif
2194 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2195         case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2196 #endif
2197 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2198         case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2199 #endif
2200         case SAP_WIDETAG:
2201         case WEAK_POINTER_WIDETAG:
2202             break;
2203
2204         default:
2205             if (gencgc_verbose)
2206                 FSHOW((stderr,
2207                        "/Wo6: %x %x %x\n",
2208                        pointer, start_addr, *start_addr));
2209             return 0;
2210         }
2211         break;
2212     default:
2213         if (gencgc_verbose)
2214             FSHOW((stderr,
2215                    "*W?: %x %x %x\n",
2216                    pointer, start_addr, *start_addr));
2217         return 0;
2218     }
2219
2220     /* looks good */
2221     return 1;
2222 }
2223
2224 /* Adjust large bignum and vector objects. This will adjust the
2225  * allocated region if the size has shrunk, and move unboxed objects
2226  * into unboxed pages. The pages are not promoted here, and the
2227  * promoted region is not added to the new_regions; this is really
2228  * only designed to be called from preserve_pointer(). Shouldn't fail
2229  * if this is missed, just may delay the moving of objects to unboxed
2230  * pages, and the freeing of pages. */
2231 static void
2232 maybe_adjust_large_object(lispobj *where)
2233 {
2234     int first_page;
2235     int nwords;
2236
2237     int remaining_bytes;
2238     int next_page;
2239     int bytes_freed;
2240     int old_bytes_used;
2241
2242     int boxed;
2243
2244     /* Check whether it's a vector or bignum object. */
2245     switch (widetag_of(where[0])) {
2246     case SIMPLE_VECTOR_WIDETAG:
2247         boxed = BOXED_PAGE_FLAG;
2248         break;
2249     case BIGNUM_WIDETAG:
2250     case SIMPLE_BASE_STRING_WIDETAG:
2251     case SIMPLE_BIT_VECTOR_WIDETAG:
2252     case SIMPLE_ARRAY_NIL_WIDETAG:
2253     case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2254     case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2255     case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2256     case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2257     case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2258     case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2259     case SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG:
2260     case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2261     case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2262 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2263     case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2264 #endif
2265 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2266     case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2267 #endif
2268 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
2269     case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
2270 #endif
2271 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2272     case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2273 #endif
2274     case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2275     case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2276 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2277     case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2278 #endif
2279 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2280     case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2281 #endif
2282 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2283     case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2284 #endif
2285 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2286     case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2287 #endif
2288         boxed = UNBOXED_PAGE_FLAG;
2289         break;
2290     default:
2291         return;
2292     }
2293
2294     /* Find its current size. */
2295     nwords = (sizetab[widetag_of(where[0])])(where);
2296
2297     first_page = find_page_index((void *)where);
2298     gc_assert(first_page >= 0);
2299
2300     /* Note: Any page write-protection must be removed, else a later
2301      * scavenge_newspace may incorrectly not scavenge these pages.
2302      * This would not be necessary if they are added to the new areas,
2303      * but lets do it for them all (they'll probably be written
2304      * anyway?). */
2305
2306     gc_assert(page_table[first_page].first_object_offset == 0);
2307
2308     next_page = first_page;
2309     remaining_bytes = nwords*N_WORD_BYTES;
2310     while (remaining_bytes > PAGE_BYTES) {
2311         gc_assert(page_table[next_page].gen == from_space);
2312         gc_assert((page_table[next_page].allocated == BOXED_PAGE_FLAG)
2313                   || (page_table[next_page].allocated == UNBOXED_PAGE_FLAG));
2314         gc_assert(page_table[next_page].large_object);
2315         gc_assert(page_table[next_page].first_object_offset ==
2316                   -PAGE_BYTES*(next_page-first_page));
2317         gc_assert(page_table[next_page].bytes_used == PAGE_BYTES);
2318
2319         page_table[next_page].allocated = boxed;
2320
2321         /* Shouldn't be write-protected at this stage. Essential that the
2322          * pages aren't. */
2323         gc_assert(!page_table[next_page].write_protected);
2324         remaining_bytes -= PAGE_BYTES;
2325         next_page++;
2326     }
2327
2328     /* Now only one page remains, but the object may have shrunk so
2329      * there may be more unused pages which will be freed. */
2330
2331     /* Object may have shrunk but shouldn't have grown - check. */
2332     gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2333
2334     page_table[next_page].allocated = boxed;
2335     gc_assert(page_table[next_page].allocated ==
2336               page_table[first_page].allocated);
2337
2338     /* Adjust the bytes_used. */
2339     old_bytes_used = page_table[next_page].bytes_used;
2340     page_table[next_page].bytes_used = remaining_bytes;
2341
2342     bytes_freed = old_bytes_used - remaining_bytes;
2343
2344     /* Free any remaining pages; needs care. */
2345     next_page++;
2346     while ((old_bytes_used == PAGE_BYTES) &&
2347            (page_table[next_page].gen == from_space) &&
2348            ((page_table[next_page].allocated == UNBOXED_PAGE_FLAG)
2349             || (page_table[next_page].allocated == BOXED_PAGE_FLAG)) &&
2350            page_table[next_page].large_object &&
2351            (page_table[next_page].first_object_offset ==
2352             -(next_page - first_page)*PAGE_BYTES)) {
2353         /* It checks out OK, free the page. We don't need to both zeroing
2354          * pages as this should have been done before shrinking the
2355          * object. These pages shouldn't be write protected as they
2356          * should be zero filled. */
2357         gc_assert(page_table[next_page].write_protected == 0);
2358
2359         old_bytes_used = page_table[next_page].bytes_used;
2360         page_table[next_page].allocated = FREE_PAGE_FLAG;
2361         page_table[next_page].bytes_used = 0;
2362         bytes_freed += old_bytes_used;
2363         next_page++;
2364     }
2365
2366     if ((bytes_freed > 0) && gencgc_verbose) {
2367         FSHOW((stderr,
2368                "/maybe_adjust_large_object() freed %d\n",
2369                bytes_freed));
2370     }
2371
2372     generations[from_space].bytes_allocated -= bytes_freed;
2373     bytes_allocated -= bytes_freed;
2374
2375     return;
2376 }
2377
2378 /* Take a possible pointer to a Lisp object and mark its page in the
2379  * page_table so that it will not be relocated during a GC.
2380  *
2381  * This involves locating the page it points to, then backing up to
2382  * the start of its region, then marking all pages dont_move from there
2383  * up to the first page that's not full or has a different generation
2384  *
2385  * It is assumed that all the page static flags have been cleared at
2386  * the start of a GC.
2387  *
2388  * It is also assumed that the current gc_alloc() region has been
2389  * flushed and the tables updated. */
2390 static void
2391 preserve_pointer(void *addr)
2392 {
2393     int addr_page_index = find_page_index(addr);
2394     int first_page;
2395     int i;
2396     unsigned region_allocation;
2397
2398     /* quick check 1: Address is quite likely to have been invalid. */
2399     if ((addr_page_index == -1)
2400         || (page_table[addr_page_index].allocated == FREE_PAGE_FLAG)
2401         || (page_table[addr_page_index].bytes_used == 0)
2402         || (page_table[addr_page_index].gen != from_space)
2403         /* Skip if already marked dont_move. */
2404         || (page_table[addr_page_index].dont_move != 0))
2405         return;
2406     gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2407     /* (Now that we know that addr_page_index is in range, it's
2408      * safe to index into page_table[] with it.) */
2409     region_allocation = page_table[addr_page_index].allocated;
2410
2411     /* quick check 2: Check the offset within the page.
2412      *
2413      */
2414     if (((unsigned)addr & (PAGE_BYTES - 1)) > page_table[addr_page_index].bytes_used)
2415         return;
2416
2417     /* Filter out anything which can't be a pointer to a Lisp object
2418      * (or, as a special case which also requires dont_move, a return
2419      * address referring to something in a CodeObject). This is
2420      * expensive but important, since it vastly reduces the
2421      * probability that random garbage will be bogusly interpreted as
2422      * a pointer which prevents a page from moving. */
2423     if (!(possibly_valid_dynamic_space_pointer(addr)))
2424         return;
2425
2426     /* Find the beginning of the region.  Note that there may be
2427      * objects in the region preceding the one that we were passed a
2428      * pointer to: if this is the case, we will write-protect all the
2429      * previous objects' pages too.     */
2430
2431 #if 0
2432     /* I think this'd work just as well, but without the assertions.
2433      * -dan 2004.01.01 */
2434     first_page=
2435         find_page_index(page_address(addr_page_index)+
2436                         page_table[addr_page_index].first_object_offset);
2437 #else 
2438     first_page = addr_page_index;
2439     while (page_table[first_page].first_object_offset != 0) {
2440         --first_page;
2441         /* Do some checks. */
2442         gc_assert(page_table[first_page].bytes_used == PAGE_BYTES);
2443         gc_assert(page_table[first_page].gen == from_space);
2444         gc_assert(page_table[first_page].allocated == region_allocation);
2445     }
2446 #endif
2447
2448     /* Adjust any large objects before promotion as they won't be
2449      * copied after promotion. */
2450     if (page_table[first_page].large_object) {
2451         maybe_adjust_large_object(page_address(first_page));
2452         /* If a large object has shrunk then addr may now point to a
2453          * free area in which case it's ignored here. Note it gets
2454          * through the valid pointer test above because the tail looks
2455          * like conses. */
2456         if ((page_table[addr_page_index].allocated == FREE_PAGE_FLAG)
2457             || (page_table[addr_page_index].bytes_used == 0)
2458             /* Check the offset within the page. */
2459             || (((unsigned)addr & (PAGE_BYTES - 1))
2460                 > page_table[addr_page_index].bytes_used)) {
2461             FSHOW((stderr,
2462                    "weird? ignore ptr 0x%x to freed area of large object\n",
2463                    addr));
2464             return;
2465         }
2466         /* It may have moved to unboxed pages. */
2467         region_allocation = page_table[first_page].allocated;
2468     }
2469
2470     /* Now work forward until the end of this contiguous area is found,
2471      * marking all pages as dont_move. */
2472     for (i = first_page; ;i++) {
2473         gc_assert(page_table[i].allocated == region_allocation);
2474
2475         /* Mark the page static. */
2476         page_table[i].dont_move = 1;
2477
2478         /* Move the page to the new_space. XX I'd rather not do this
2479          * but the GC logic is not quite able to copy with the static
2480          * pages remaining in the from space. This also requires the
2481          * generation bytes_allocated counters be updated. */
2482         page_table[i].gen = new_space;
2483         generations[new_space].bytes_allocated += page_table[i].bytes_used;
2484         generations[from_space].bytes_allocated -= page_table[i].bytes_used;
2485
2486         /* It is essential that the pages are not write protected as
2487          * they may have pointers into the old-space which need
2488          * scavenging. They shouldn't be write protected at this
2489          * stage. */
2490         gc_assert(!page_table[i].write_protected);
2491
2492         /* Check whether this is the last page in this contiguous block.. */
2493         if ((page_table[i].bytes_used < PAGE_BYTES)
2494             /* ..or it is PAGE_BYTES and is the last in the block */
2495             || (page_table[i+1].allocated == FREE_PAGE_FLAG)
2496             || (page_table[i+1].bytes_used == 0) /* next page free */
2497             || (page_table[i+1].gen != from_space) /* diff. gen */
2498             || (page_table[i+1].first_object_offset == 0))
2499             break;
2500     }
2501
2502     /* Check that the page is now static. */
2503     gc_assert(page_table[addr_page_index].dont_move != 0);
2504 }
2505 \f
2506 /* If the given page is not write-protected, then scan it for pointers
2507  * to younger generations or the top temp. generation, if no
2508  * suspicious pointers are found then the page is write-protected.
2509  *
2510  * Care is taken to check for pointers to the current gc_alloc()
2511  * region if it is a younger generation or the temp. generation. This
2512  * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2513  * the gc_alloc_generation does not need to be checked as this is only
2514  * called from scavenge_generation() when the gc_alloc generation is
2515  * younger, so it just checks if there is a pointer to the current
2516  * region.
2517  *
2518  * We return 1 if the page was write-protected, else 0. */
2519 static int
2520 update_page_write_prot(int page)
2521 {
2522     int gen = page_table[page].gen;
2523     int j;
2524     int wp_it = 1;
2525     void **page_addr = (void **)page_address(page);
2526     int num_words = page_table[page].bytes_used / N_WORD_BYTES;
2527
2528     /* Shouldn't be a free page. */
2529     gc_assert(page_table[page].allocated != FREE_PAGE_FLAG);
2530     gc_assert(page_table[page].bytes_used != 0);
2531
2532     /* Skip if it's already write-protected, pinned, or unboxed */
2533     if (page_table[page].write_protected
2534         || page_table[page].dont_move
2535         || (page_table[page].allocated & UNBOXED_PAGE_FLAG))
2536         return (0);
2537
2538     /* Scan the page for pointers to younger generations or the
2539      * top temp. generation. */
2540
2541     for (j = 0; j < num_words; j++) {
2542         void *ptr = *(page_addr+j);
2543         int index = find_page_index(ptr);
2544
2545         /* Check that it's in the dynamic space */
2546         if (index != -1)
2547             if (/* Does it point to a younger or the temp. generation? */
2548                 ((page_table[index].allocated != FREE_PAGE_FLAG)
2549                  && (page_table[index].bytes_used != 0)
2550                  && ((page_table[index].gen < gen)
2551                      || (page_table[index].gen == NUM_GENERATIONS)))
2552
2553                 /* Or does it point within a current gc_alloc() region? */
2554                 || ((boxed_region.start_addr <= ptr)
2555                     && (ptr <= boxed_region.free_pointer))
2556                 || ((unboxed_region.start_addr <= ptr)
2557                     && (ptr <= unboxed_region.free_pointer))) {
2558                 wp_it = 0;
2559                 break;
2560             }
2561     }
2562
2563     if (wp_it == 1) {
2564         /* Write-protect the page. */
2565         /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2566
2567         os_protect((void *)page_addr,
2568                    PAGE_BYTES,
2569                    OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2570
2571         /* Note the page as protected in the page tables. */
2572         page_table[page].write_protected = 1;
2573     }
2574
2575     return (wp_it);
2576 }
2577
2578 /* Scavenge a generation.
2579  *
2580  * This will not resolve all pointers when generation is the new
2581  * space, as new objects may be added which are not checked here - use
2582  * scavenge_newspace generation.
2583  *
2584  * Write-protected pages should not have any pointers to the
2585  * from_space so do need scavenging; thus write-protected pages are
2586  * not always scavenged. There is some code to check that these pages
2587  * are not written; but to check fully the write-protected pages need
2588  * to be scavenged by disabling the code to skip them.
2589  *
2590  * Under the current scheme when a generation is GCed the younger
2591  * generations will be empty. So, when a generation is being GCed it
2592  * is only necessary to scavenge the older generations for pointers
2593  * not the younger. So a page that does not have pointers to younger
2594  * generations does not need to be scavenged.
2595  *
2596  * The write-protection can be used to note pages that don't have
2597  * pointers to younger pages. But pages can be written without having
2598  * pointers to younger generations. After the pages are scavenged here
2599  * they can be scanned for pointers to younger generations and if
2600  * there are none the page can be write-protected.
2601  *
2602  * One complication is when the newspace is the top temp. generation.
2603  *
2604  * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2605  * that none were written, which they shouldn't be as they should have
2606  * no pointers to younger generations. This breaks down for weak
2607  * pointers as the objects contain a link to the next and are written
2608  * if a weak pointer is scavenged. Still it's a useful check. */
2609 static void
2610 scavenge_generation(int generation)
2611 {
2612     int i;
2613     int num_wp = 0;
2614
2615 #define SC_GEN_CK 0
2616 #if SC_GEN_CK
2617     /* Clear the write_protected_cleared flags on all pages. */
2618     for (i = 0; i < NUM_PAGES; i++)
2619         page_table[i].write_protected_cleared = 0;
2620 #endif
2621
2622     for (i = 0; i < last_free_page; i++) {
2623         if ((page_table[i].allocated & BOXED_PAGE_FLAG)
2624             && (page_table[i].bytes_used != 0)
2625             && (page_table[i].gen == generation)) {
2626             int last_page,j;
2627             int write_protected=1;
2628
2629             /* This should be the start of a region */
2630             gc_assert(page_table[i].first_object_offset == 0);
2631
2632             /* Now work forward until the end of the region */
2633             for (last_page = i; ; last_page++) {
2634                 write_protected =
2635                     write_protected && page_table[last_page].write_protected;
2636                 if ((page_table[last_page].bytes_used < PAGE_BYTES)
2637                     /* Or it is PAGE_BYTES and is the last in the block */
2638                     || (!(page_table[last_page+1].allocated & BOXED_PAGE_FLAG))
2639                     || (page_table[last_page+1].bytes_used == 0)
2640                     || (page_table[last_page+1].gen != generation)
2641                     || (page_table[last_page+1].first_object_offset == 0))
2642                     break;
2643             }
2644             if (!write_protected) {
2645                 scavenge(page_address(i), (page_table[last_page].bytes_used
2646                                            + (last_page-i)*PAGE_BYTES)/4);
2647                 
2648                 /* Now scan the pages and write protect those that
2649                  * don't have pointers to younger generations. */
2650                 if (enable_page_protection) {
2651                     for (j = i; j <= last_page; j++) {
2652                         num_wp += update_page_write_prot(j);
2653                     }
2654                 }
2655             }
2656             i = last_page;
2657         }
2658     }
2659     if ((gencgc_verbose > 1) && (num_wp != 0)) {
2660         FSHOW((stderr,
2661                "/write protected %d pages within generation %d\n",
2662                num_wp, generation));
2663     }
2664
2665 #if SC_GEN_CK
2666     /* Check that none of the write_protected pages in this generation
2667      * have been written to. */
2668     for (i = 0; i < NUM_PAGES; i++) {
2669         if ((page_table[i].allocation != FREE_PAGE_FLAG)
2670             && (page_table[i].bytes_used != 0)
2671             && (page_table[i].gen == generation)
2672             && (page_table[i].write_protected_cleared != 0)) {
2673             FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2674             FSHOW((stderr,
2675                    "/page bytes_used=%d first_object_offset=%d dont_move=%d\n",
2676                     page_table[i].bytes_used,
2677                     page_table[i].first_object_offset,
2678                     page_table[i].dont_move));
2679             lose("write to protected page %d in scavenge_generation()", i);
2680         }
2681     }
2682 #endif
2683 }
2684
2685 \f
2686 /* Scavenge a newspace generation. As it is scavenged new objects may
2687  * be allocated to it; these will also need to be scavenged. This
2688  * repeats until there are no more objects unscavenged in the
2689  * newspace generation.
2690  *
2691  * To help improve the efficiency, areas written are recorded by
2692  * gc_alloc() and only these scavenged. Sometimes a little more will be
2693  * scavenged, but this causes no harm. An easy check is done that the
2694  * scavenged bytes equals the number allocated in the previous
2695  * scavenge.
2696  *
2697  * Write-protected pages are not scanned except if they are marked
2698  * dont_move in which case they may have been promoted and still have
2699  * pointers to the from space.
2700  *
2701  * Write-protected pages could potentially be written by alloc however
2702  * to avoid having to handle re-scavenging of write-protected pages
2703  * gc_alloc() does not write to write-protected pages.
2704  *
2705  * New areas of objects allocated are recorded alternatively in the two
2706  * new_areas arrays below. */
2707 static struct new_area new_areas_1[NUM_NEW_AREAS];
2708 static struct new_area new_areas_2[NUM_NEW_AREAS];
2709
2710 /* Do one full scan of the new space generation. This is not enough to
2711  * complete the job as new objects may be added to the generation in
2712  * the process which are not scavenged. */
2713 static void
2714 scavenge_newspace_generation_one_scan(int generation)
2715 {
2716     int i;
2717
2718     FSHOW((stderr,
2719            "/starting one full scan of newspace generation %d\n",
2720            generation));
2721     for (i = 0; i < last_free_page; i++) {
2722         /* Note that this skips over open regions when it encounters them. */
2723         if ((page_table[i].allocated & BOXED_PAGE_FLAG)
2724             && (page_table[i].bytes_used != 0)
2725             && (page_table[i].gen == generation)
2726             && ((page_table[i].write_protected == 0)
2727                 /* (This may be redundant as write_protected is now
2728                  * cleared before promotion.) */
2729                 || (page_table[i].dont_move == 1))) {
2730             int last_page;
2731             int all_wp=1;
2732
2733             /* The scavenge will start at the first_object_offset of page i.
2734              *
2735              * We need to find the full extent of this contiguous
2736              * block in case objects span pages.
2737              *
2738              * Now work forward until the end of this contiguous area
2739              * is found. A small area is preferred as there is a
2740              * better chance of its pages being write-protected. */
2741             for (last_page = i; ;last_page++) {
2742                 /* If all pages are write-protected and movable, 
2743                  * then no need to scavenge */
2744                 all_wp=all_wp && page_table[last_page].write_protected && 
2745                     !page_table[last_page].dont_move;
2746                 
2747                 /* Check whether this is the last page in this
2748                  * contiguous block */
2749                 if ((page_table[last_page].bytes_used < PAGE_BYTES)
2750                     /* Or it is PAGE_BYTES and is the last in the block */
2751                     || (!(page_table[last_page+1].allocated & BOXED_PAGE_FLAG))
2752                     || (page_table[last_page+1].bytes_used == 0)
2753                     || (page_table[last_page+1].gen != generation)
2754                     || (page_table[last_page+1].first_object_offset == 0))
2755                     break;
2756             }
2757
2758             /* Do a limited check for write-protected pages.  */
2759             if (!all_wp) {
2760                 int size;
2761                 
2762                 size = (page_table[last_page].bytes_used
2763                         + (last_page-i)*PAGE_BYTES
2764                         - page_table[i].first_object_offset)/4;
2765                 new_areas_ignore_page = last_page;
2766                 
2767                 scavenge(page_address(i) +
2768                          page_table[i].first_object_offset,
2769                          size);
2770                 
2771             }
2772             i = last_page;
2773         }
2774     }
2775     FSHOW((stderr,
2776            "/done with one full scan of newspace generation %d\n",
2777            generation));
2778 }
2779
2780 /* Do a complete scavenge of the newspace generation. */
2781 static void
2782 scavenge_newspace_generation(int generation)
2783 {
2784     int i;
2785
2786     /* the new_areas array currently being written to by gc_alloc() */
2787     struct new_area (*current_new_areas)[] = &new_areas_1;
2788     int current_new_areas_index;
2789
2790     /* the new_areas created by the previous scavenge cycle */
2791     struct new_area (*previous_new_areas)[] = NULL;
2792     int previous_new_areas_index;
2793
2794     /* Flush the current regions updating the tables. */
2795     gc_alloc_update_all_page_tables();
2796
2797     /* Turn on the recording of new areas by gc_alloc(). */
2798     new_areas = current_new_areas;
2799     new_areas_index = 0;
2800
2801     /* Don't need to record new areas that get scavenged anyway during
2802      * scavenge_newspace_generation_one_scan. */
2803     record_new_objects = 1;
2804
2805     /* Start with a full scavenge. */
2806     scavenge_newspace_generation_one_scan(generation);
2807
2808     /* Record all new areas now. */
2809     record_new_objects = 2;
2810
2811     /* Flush the current regions updating the tables. */
2812     gc_alloc_update_all_page_tables();
2813
2814     /* Grab new_areas_index. */
2815     current_new_areas_index = new_areas_index;
2816
2817     /*FSHOW((stderr,
2818              "The first scan is finished; current_new_areas_index=%d.\n",
2819              current_new_areas_index));*/
2820
2821     while (current_new_areas_index > 0) {
2822         /* Move the current to the previous new areas */
2823         previous_new_areas = current_new_areas;
2824         previous_new_areas_index = current_new_areas_index;
2825
2826         /* Scavenge all the areas in previous new areas. Any new areas
2827          * allocated are saved in current_new_areas. */
2828
2829         /* Allocate an array for current_new_areas; alternating between
2830          * new_areas_1 and 2 */
2831         if (previous_new_areas == &new_areas_1)
2832             current_new_areas = &new_areas_2;
2833         else
2834             current_new_areas = &new_areas_1;
2835
2836         /* Set up for gc_alloc(). */
2837         new_areas = current_new_areas;
2838         new_areas_index = 0;
2839
2840         /* Check whether previous_new_areas had overflowed. */
2841         if (previous_new_areas_index >= NUM_NEW_AREAS) {
2842
2843             /* New areas of objects allocated have been lost so need to do a
2844              * full scan to be sure! If this becomes a problem try
2845              * increasing NUM_NEW_AREAS. */
2846             if (gencgc_verbose)
2847                 SHOW("new_areas overflow, doing full scavenge");
2848
2849             /* Don't need to record new areas that get scavenge anyway
2850              * during scavenge_newspace_generation_one_scan. */
2851             record_new_objects = 1;
2852
2853             scavenge_newspace_generation_one_scan(generation);
2854
2855             /* Record all new areas now. */
2856             record_new_objects = 2;
2857
2858             /* Flush the current regions updating the tables. */
2859             gc_alloc_update_all_page_tables();
2860
2861         } else {
2862
2863             /* Work through previous_new_areas. */
2864             for (i = 0; i < previous_new_areas_index; i++) {
2865                 int page = (*previous_new_areas)[i].page;
2866                 int offset = (*previous_new_areas)[i].offset;
2867                 int size = (*previous_new_areas)[i].size / N_WORD_BYTES;
2868                 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
2869                 scavenge(page_address(page)+offset, size);
2870             }
2871
2872             /* Flush the current regions updating the tables. */
2873             gc_alloc_update_all_page_tables();
2874         }
2875
2876         current_new_areas_index = new_areas_index;
2877
2878         /*FSHOW((stderr,
2879                  "The re-scan has finished; current_new_areas_index=%d.\n",
2880                  current_new_areas_index));*/
2881     }
2882
2883     /* Turn off recording of areas allocated by gc_alloc(). */
2884     record_new_objects = 0;
2885
2886 #if SC_NS_GEN_CK
2887     /* Check that none of the write_protected pages in this generation
2888      * have been written to. */
2889     for (i = 0; i < NUM_PAGES; i++) {
2890         if ((page_table[i].allocation != FREE_PAGE_FLAG)
2891             && (page_table[i].bytes_used != 0)
2892             && (page_table[i].gen == generation)
2893             && (page_table[i].write_protected_cleared != 0)
2894             && (page_table[i].dont_move == 0)) {
2895             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d",
2896                  i, generation, page_table[i].dont_move);
2897         }
2898     }
2899 #endif
2900 }
2901 \f
2902 /* Un-write-protect all the pages in from_space. This is done at the
2903  * start of a GC else there may be many page faults while scavenging
2904  * the newspace (I've seen drive the system time to 99%). These pages
2905  * would need to be unprotected anyway before unmapping in
2906  * free_oldspace; not sure what effect this has on paging.. */
2907 static void
2908 unprotect_oldspace(void)
2909 {
2910     int i;
2911
2912     for (i = 0; i < last_free_page; i++) {
2913         if ((page_table[i].allocated != FREE_PAGE_FLAG)
2914             && (page_table[i].bytes_used != 0)
2915             && (page_table[i].gen == from_space)) {
2916             void *page_start;
2917
2918             page_start = (void *)page_address(i);
2919
2920             /* Remove any write-protection. We should be able to rely
2921              * on the write-protect flag to avoid redundant calls. */
2922             if (page_table[i].write_protected) {
2923                 os_protect(page_start, PAGE_BYTES, OS_VM_PROT_ALL);
2924                 page_table[i].write_protected = 0;
2925             }
2926         }
2927     }
2928 }
2929
2930 /* Work through all the pages and free any in from_space. This
2931  * assumes that all objects have been copied or promoted to an older
2932  * generation. Bytes_allocated and the generation bytes_allocated
2933  * counter are updated. The number of bytes freed is returned. */
2934 static int
2935 free_oldspace(void)
2936 {
2937     int bytes_freed = 0;
2938     int first_page, last_page;
2939
2940     first_page = 0;
2941
2942     do {
2943         /* Find a first page for the next region of pages. */
2944         while ((first_page < last_free_page)
2945                && ((page_table[first_page].allocated == FREE_PAGE_FLAG)
2946                    || (page_table[first_page].bytes_used == 0)
2947                    || (page_table[first_page].gen != from_space)))
2948             first_page++;
2949
2950         if (first_page >= last_free_page)
2951             break;
2952
2953         /* Find the last page of this region. */
2954         last_page = first_page;
2955
2956         do {
2957             /* Free the page. */
2958             bytes_freed += page_table[last_page].bytes_used;
2959             generations[page_table[last_page].gen].bytes_allocated -=
2960                 page_table[last_page].bytes_used;
2961             page_table[last_page].allocated = FREE_PAGE_FLAG;
2962             page_table[last_page].bytes_used = 0;
2963
2964             /* Remove any write-protection. We should be able to rely
2965              * on the write-protect flag to avoid redundant calls. */
2966             {
2967                 void  *page_start = (void *)page_address(last_page);
2968         
2969                 if (page_table[last_page].write_protected) {
2970                     os_protect(page_start, PAGE_BYTES, OS_VM_PROT_ALL);
2971                     page_table[last_page].write_protected = 0;
2972                 }
2973             }
2974             last_page++;
2975         }
2976         while ((last_page < last_free_page)
2977                && (page_table[last_page].allocated != FREE_PAGE_FLAG)
2978                && (page_table[last_page].bytes_used != 0)
2979                && (page_table[last_page].gen == from_space));
2980
2981         /* Zero pages from first_page to (last_page-1).
2982          *
2983          * FIXME: Why not use os_zero(..) function instead of
2984          * hand-coding this again? (Check other gencgc_unmap_zero
2985          * stuff too. */
2986         if (gencgc_unmap_zero) {
2987             void *page_start, *addr;
2988
2989             page_start = (void *)page_address(first_page);
2990
2991             os_invalidate(page_start, PAGE_BYTES*(last_page-first_page));
2992             addr = os_validate(page_start, PAGE_BYTES*(last_page-first_page));
2993             if (addr == NULL || addr != page_start) {
2994                 lose("free_oldspace: page moved, 0x%08x ==> 0x%08x",page_start,
2995                      addr);
2996             }
2997         } else {
2998             int *page_start;
2999
3000             page_start = (int *)page_address(first_page);
3001             memset(page_start, 0,PAGE_BYTES*(last_page-first_page));
3002         }
3003
3004         first_page = last_page;
3005
3006     } while (first_page < last_free_page);
3007
3008     bytes_allocated -= bytes_freed;
3009     return bytes_freed;
3010 }
3011 \f
3012 #if 0
3013 /* Print some information about a pointer at the given address. */
3014 static void
3015 print_ptr(lispobj *addr)
3016 {
3017     /* If addr is in the dynamic space then out the page information. */
3018     int pi1 = find_page_index((void*)addr);
3019
3020     if (pi1 != -1)
3021         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %d  dont_move %d\n",
3022                 (unsigned int) addr,
3023                 pi1,
3024                 page_table[pi1].allocated,
3025                 page_table[pi1].gen,
3026                 page_table[pi1].bytes_used,
3027                 page_table[pi1].first_object_offset,
3028                 page_table[pi1].dont_move);
3029     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
3030             *(addr-4),
3031             *(addr-3),
3032             *(addr-2),
3033             *(addr-1),
3034             *(addr-0),
3035             *(addr+1),
3036             *(addr+2),
3037             *(addr+3),
3038             *(addr+4));
3039 }
3040 #endif
3041
3042 extern int undefined_tramp;
3043
3044 static void
3045 verify_space(lispobj *start, size_t words)
3046 {
3047     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
3048     int is_in_readonly_space =
3049         (READ_ONLY_SPACE_START <= (unsigned)start &&
3050          (unsigned)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3051
3052     while (words > 0) {
3053         size_t count = 1;
3054         lispobj thing = *(lispobj*)start;
3055
3056         if (is_lisp_pointer(thing)) {
3057             int page_index = find_page_index((void*)thing);
3058             int to_readonly_space =
3059                 (READ_ONLY_SPACE_START <= thing &&
3060                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3061             int to_static_space =
3062                 (STATIC_SPACE_START <= thing &&
3063                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3064
3065             /* Does it point to the dynamic space? */
3066             if (page_index != -1) {
3067                 /* If it's within the dynamic space it should point to a used
3068                  * page. XX Could check the offset too. */
3069                 if ((page_table[page_index].allocated != FREE_PAGE_FLAG)
3070                     && (page_table[page_index].bytes_used == 0))
3071                     lose ("Ptr %x @ %x sees free page.", thing, start);
3072                 /* Check that it doesn't point to a forwarding pointer! */
3073                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3074                     lose("Ptr %x @ %x sees forwarding ptr.", thing, start);
3075                 }
3076                 /* Check that its not in the RO space as it would then be a
3077                  * pointer from the RO to the dynamic space. */
3078                 if (is_in_readonly_space) {
3079                     lose("ptr to dynamic space %x from RO space %x",
3080                          thing, start);
3081                 }
3082                 /* Does it point to a plausible object? This check slows
3083                  * it down a lot (so it's commented out).
3084                  *
3085                  * "a lot" is serious: it ate 50 minutes cpu time on
3086                  * my duron 950 before I came back from lunch and
3087                  * killed it.
3088                  *
3089                  *   FIXME: Add a variable to enable this
3090                  * dynamically. */
3091                 /*
3092                 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
3093                     lose("ptr %x to invalid object %x", thing, start); 
3094                 }
3095                 */
3096             } else {
3097                 /* Verify that it points to another valid space. */
3098                 if (!to_readonly_space && !to_static_space
3099                     && (thing != (unsigned)&undefined_tramp)) {
3100                     lose("Ptr %x @ %x sees junk.", thing, start);
3101                 }
3102             }
3103         } else {
3104             if (!(fixnump(thing))) { 
3105                 /* skip fixnums */
3106                 switch(widetag_of(*start)) {
3107
3108                     /* boxed objects */
3109                 case SIMPLE_VECTOR_WIDETAG:
3110                 case RATIO_WIDETAG:
3111                 case COMPLEX_WIDETAG:
3112                 case SIMPLE_ARRAY_WIDETAG:
3113                 case COMPLEX_BASE_STRING_WIDETAG:
3114                 case COMPLEX_VECTOR_NIL_WIDETAG:
3115                 case COMPLEX_BIT_VECTOR_WIDETAG:
3116                 case COMPLEX_VECTOR_WIDETAG:
3117                 case COMPLEX_ARRAY_WIDETAG:
3118                 case CLOSURE_HEADER_WIDETAG:
3119                 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3120                 case VALUE_CELL_HEADER_WIDETAG:
3121                 case SYMBOL_HEADER_WIDETAG:
3122                 case BASE_CHAR_WIDETAG:
3123                 case UNBOUND_MARKER_WIDETAG:
3124                 case INSTANCE_HEADER_WIDETAG:
3125                 case FDEFN_WIDETAG:
3126                     count = 1;
3127                     break;
3128
3129                 case CODE_HEADER_WIDETAG:
3130                     {
3131                         lispobj object = *start;
3132                         struct code *code;
3133                         int nheader_words, ncode_words, nwords;
3134                         lispobj fheaderl;
3135                         struct simple_fun *fheaderp;
3136
3137                         code = (struct code *) start;
3138
3139                         /* Check that it's not in the dynamic space.
3140                          * FIXME: Isn't is supposed to be OK for code
3141                          * objects to be in the dynamic space these days? */
3142                         if (is_in_dynamic_space
3143                             /* It's ok if it's byte compiled code. The trace
3144                              * table offset will be a fixnum if it's x86
3145                              * compiled code - check.
3146                              *
3147                              * FIXME: #^#@@! lack of abstraction here..
3148                              * This line can probably go away now that
3149                              * there's no byte compiler, but I've got
3150                              * too much to worry about right now to try
3151                              * to make sure. -- WHN 2001-10-06 */
3152                             && fixnump(code->trace_table_offset)
3153                             /* Only when enabled */
3154                             && verify_dynamic_code_check) {
3155                             FSHOW((stderr,
3156                                    "/code object at %x in the dynamic space\n",
3157                                    start));
3158                         }
3159
3160                         ncode_words = fixnum_value(code->code_size);
3161                         nheader_words = HeaderValue(object);
3162                         nwords = ncode_words + nheader_words;
3163                         nwords = CEILING(nwords, 2);
3164                         /* Scavenge the boxed section of the code data block */
3165                         verify_space(start + 1, nheader_words - 1);
3166
3167                         /* Scavenge the boxed section of each function
3168                          * object in the code data block. */
3169                         fheaderl = code->entry_points;
3170                         while (fheaderl != NIL) {
3171                             fheaderp =
3172                                 (struct simple_fun *) native_pointer(fheaderl);
3173                             gc_assert(widetag_of(fheaderp->header) == SIMPLE_FUN_HEADER_WIDETAG);
3174                             verify_space(&fheaderp->name, 1);
3175                             verify_space(&fheaderp->arglist, 1);
3176                             verify_space(&fheaderp->type, 1);
3177                             fheaderl = fheaderp->next;
3178                         }
3179                         count = nwords;
3180                         break;
3181                     }
3182         
3183                     /* unboxed objects */
3184                 case BIGNUM_WIDETAG:
3185                 case SINGLE_FLOAT_WIDETAG:
3186                 case DOUBLE_FLOAT_WIDETAG:
3187 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3188                 case LONG_FLOAT_WIDETAG:
3189 #endif
3190 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3191                 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3192 #endif
3193 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3194                 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3195 #endif
3196 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3197                 case COMPLEX_LONG_FLOAT_WIDETAG:
3198 #endif
3199                 case SIMPLE_BASE_STRING_WIDETAG:
3200                 case SIMPLE_BIT_VECTOR_WIDETAG:
3201                 case SIMPLE_ARRAY_NIL_WIDETAG:
3202                 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3203                 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3204                 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3205                 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3206                 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3207                 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3208                 case SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG:
3209                 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3210                 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3211 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3212                 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3213 #endif
3214 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3215                 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3216 #endif
3217 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
3218                 case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
3219 #endif
3220 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3221                 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3222 #endif
3223                 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3224                 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3225 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3226                 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3227 #endif
3228 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3229                 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3230 #endif
3231 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3232                 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3233 #endif
3234 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3235                 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3236 #endif
3237                 case SAP_WIDETAG:
3238                 case WEAK_POINTER_WIDETAG:
3239                     count = (sizetab[widetag_of(*start)])(start);
3240                     break;
3241
3242                 default:
3243                     gc_abort();
3244                 }
3245             }
3246         }
3247         start += count;
3248         words -= count;
3249     }
3250 }
3251
3252 static void
3253 verify_gc(void)
3254 {
3255     /* FIXME: It would be nice to make names consistent so that
3256      * foo_size meant size *in* *bytes* instead of size in some
3257      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3258      * Some counts of lispobjs are called foo_count; it might be good
3259      * to grep for all foo_size and rename the appropriate ones to
3260      * foo_count. */
3261     int read_only_space_size =
3262         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3263         - (lispobj*)READ_ONLY_SPACE_START;
3264     int static_space_size =
3265         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3266         - (lispobj*)STATIC_SPACE_START;
3267     struct thread *th;
3268     for_each_thread(th) {
3269     int binding_stack_size =
3270             (lispobj*)SymbolValue(BINDING_STACK_POINTER,th)
3271             - (lispobj*)th->binding_stack_start;
3272         verify_space(th->binding_stack_start, binding_stack_size);
3273     }
3274     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3275     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
3276 }
3277
3278 static void
3279 verify_generation(int  generation)
3280 {
3281     int i;
3282
3283     for (i = 0; i < last_free_page; i++) {
3284         if ((page_table[i].allocated != FREE_PAGE_FLAG)
3285             && (page_table[i].bytes_used != 0)
3286             && (page_table[i].gen == generation)) {
3287             int last_page;
3288             int region_allocation = page_table[i].allocated;
3289
3290             /* This should be the start of a contiguous block */
3291             gc_assert(page_table[i].first_object_offset == 0);
3292
3293             /* Need to find the full extent of this contiguous block in case
3294                objects span pages. */
3295
3296             /* Now work forward until the end of this contiguous area is
3297                found. */
3298             for (last_page = i; ;last_page++)
3299                 /* Check whether this is the last page in this contiguous
3300                  * block. */
3301                 if ((page_table[last_page].bytes_used < PAGE_BYTES)
3302                     /* Or it is PAGE_BYTES and is the last in the block */
3303                     || (page_table[last_page+1].allocated != region_allocation)
3304                     || (page_table[last_page+1].bytes_used == 0)
3305                     || (page_table[last_page+1].gen != generation)
3306                     || (page_table[last_page+1].first_object_offset == 0))
3307                     break;
3308
3309             verify_space(page_address(i), (page_table[last_page].bytes_used
3310                                            + (last_page-i)*PAGE_BYTES)/4);
3311             i = last_page;
3312         }
3313     }
3314 }
3315
3316 /* Check that all the free space is zero filled. */
3317 static void
3318 verify_zero_fill(void)
3319 {
3320     int page;
3321
3322     for (page = 0; page < last_free_page; page++) {
3323         if (page_table[page].allocated == FREE_PAGE_FLAG) {
3324             /* The whole page should be zero filled. */
3325             int *start_addr = (int *)page_address(page);
3326             int size = 1024;
3327             int i;
3328             for (i = 0; i < size; i++) {
3329                 if (start_addr[i] != 0) {
3330                     lose("free page not zero at %x", start_addr + i);
3331                 }
3332             }
3333         } else {
3334             int free_bytes = PAGE_BYTES - page_table[page].bytes_used;
3335             if (free_bytes > 0) {
3336                 int *start_addr = (int *)((unsigned)page_address(page)
3337                                           + page_table[page].bytes_used);
3338                 int size = free_bytes / N_WORD_BYTES;
3339                 int i;
3340                 for (i = 0; i < size; i++) {
3341                     if (start_addr[i] != 0) {
3342                         lose("free region not zero at %x", start_addr + i);
3343                     }
3344                 }
3345             }
3346         }
3347     }
3348 }
3349
3350 /* External entry point for verify_zero_fill */
3351 void
3352 gencgc_verify_zero_fill(void)
3353 {
3354     /* Flush the alloc regions updating the tables. */
3355     gc_alloc_update_all_page_tables();
3356     SHOW("verifying zero fill");
3357     verify_zero_fill();
3358 }
3359
3360 static void
3361 verify_dynamic_space(void)
3362 {
3363     int i;
3364
3365     for (i = 0; i < NUM_GENERATIONS; i++)
3366         verify_generation(i);
3367
3368     if (gencgc_enable_verify_zero_fill)
3369         verify_zero_fill();
3370 }
3371 \f
3372 /* Write-protect all the dynamic boxed pages in the given generation. */
3373 static void
3374 write_protect_generation_pages(int generation)
3375 {
3376     int i;
3377
3378     gc_assert(generation < NUM_GENERATIONS);
3379
3380     for (i = 0; i < last_free_page; i++)
3381         if ((page_table[i].allocated == BOXED_PAGE_FLAG)
3382             && (page_table[i].bytes_used != 0)
3383             && !page_table[i].dont_move
3384             && (page_table[i].gen == generation))  {
3385             void *page_start;
3386
3387             page_start = (void *)page_address(i);
3388
3389             os_protect(page_start,
3390                        PAGE_BYTES,
3391                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3392
3393             /* Note the page as protected in the page tables. */
3394             page_table[i].write_protected = 1;
3395         }
3396
3397     if (gencgc_verbose > 1) {
3398         FSHOW((stderr,
3399                "/write protected %d of %d pages in generation %d\n",
3400                count_write_protect_generation_pages(generation),
3401                count_generation_pages(generation),
3402                generation));
3403     }
3404 }
3405
3406 /* Garbage collect a generation. If raise is 0 then the remains of the
3407  * generation are not raised to the next generation. */
3408 static void
3409 garbage_collect_generation(int generation, int raise)
3410 {
3411     unsigned long bytes_freed;
3412     unsigned long i;
3413     unsigned long static_space_size;
3414     struct thread *th;
3415     gc_assert(generation <= (NUM_GENERATIONS-1));
3416
3417     /* The oldest generation can't be raised. */
3418     gc_assert((generation != (NUM_GENERATIONS-1)) || (raise == 0));
3419
3420     /* Initialize the weak pointer list. */
3421     weak_pointers = NULL;
3422
3423     /* When a generation is not being raised it is transported to a
3424      * temporary generation (NUM_GENERATIONS), and lowered when
3425      * done. Set up this new generation. There should be no pages
3426      * allocated to it yet. */
3427     if (!raise)
3428         gc_assert(generations[NUM_GENERATIONS].bytes_allocated == 0);
3429
3430     /* Set the global src and dest. generations */
3431     from_space = generation;
3432     if (raise)
3433         new_space = generation+1;
3434     else
3435         new_space = NUM_GENERATIONS;
3436
3437     /* Change to a new space for allocation, resetting the alloc_start_page */
3438     gc_alloc_generation = new_space;
3439     generations[new_space].alloc_start_page = 0;
3440     generations[new_space].alloc_unboxed_start_page = 0;
3441     generations[new_space].alloc_large_start_page = 0;
3442     generations[new_space].alloc_large_unboxed_start_page = 0;
3443
3444     /* Before any pointers are preserved, the dont_move flags on the
3445      * pages need to be cleared. */
3446     for (i = 0; i < last_free_page; i++)
3447         if(page_table[i].gen==from_space)
3448             page_table[i].dont_move = 0;
3449
3450     /* Un-write-protect the old-space pages. This is essential for the
3451      * promoted pages as they may contain pointers into the old-space
3452      * which need to be scavenged. It also helps avoid unnecessary page
3453      * faults as forwarding pointers are written into them. They need to
3454      * be un-protected anyway before unmapping later. */
3455     unprotect_oldspace();
3456
3457     /* Scavenge the stacks' conservative roots. */
3458
3459     /* there are potentially two stacks for each thread: the main
3460      * stack, which may contain Lisp pointers, and the alternate stack.
3461      * We don't ever run Lisp code on the altstack, but it may 
3462      * host a sigcontext with lisp objects in it */
3463
3464     /* what we need to do: (1) find the stack pointer for the main
3465      * stack; scavenge it (2) find the interrupt context on the
3466      * alternate stack that might contain lisp values, and scavenge
3467      * that */
3468
3469     /* we assume that none of the preceding applies to the thread that
3470      * initiates GC.  If you ever call GC from inside an altstack
3471      * handler, you will lose. */
3472     for_each_thread(th) {
3473         void **ptr;
3474         void **esp=(void **)-1;
3475 #ifdef LISP_FEATURE_SB_THREAD
3476         int i,free;
3477         if(th==arch_os_get_current_thread()) {
3478             esp = (void **) &raise;
3479         } else {
3480             void **esp1;
3481             free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3482             for(i=free-1;i>=0;i--) {
3483                 os_context_t *c=th->interrupt_contexts[i];
3484                 esp1 = (void **) *os_context_register_addr(c,reg_ESP);
3485                 if(esp1>=th->control_stack_start&& esp1<th->control_stack_end){
3486                     if(esp1<esp) esp=esp1;
3487                     for(ptr = (void **)(c+1); ptr>=(void **)c; ptr--) {
3488                         preserve_pointer(*ptr);
3489                     }
3490                 }
3491             }
3492         }
3493 #else
3494         esp = (void **) &raise;
3495 #endif
3496         for (ptr = (void **)th->control_stack_end; ptr > esp;  ptr--) {
3497             preserve_pointer(*ptr);
3498         }
3499     }
3500
3501 #ifdef QSHOW
3502     if (gencgc_verbose > 1) {
3503         int num_dont_move_pages = count_dont_move_pages();
3504         fprintf(stderr,
3505                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3506                 num_dont_move_pages,
3507                 num_dont_move_pages * PAGE_BYTES);
3508     }
3509 #endif
3510
3511     /* Scavenge all the rest of the roots. */
3512
3513     /* Scavenge the Lisp functions of the interrupt handlers, taking
3514      * care to avoid SIG_DFL and SIG_IGN. */
3515     for_each_thread(th) {
3516         struct interrupt_data *data=th->interrupt_data;
3517     for (i = 0; i < NSIG; i++) {
3518             union interrupt_handler handler = data->interrupt_handlers[i];
3519         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3520             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3521                 scavenge((lispobj *)(data->interrupt_handlers + i), 1);
3522             }
3523         }
3524     }
3525     /* Scavenge the binding stacks. */
3526  {
3527      struct thread *th;
3528      for_each_thread(th) {
3529          long len= (lispobj *)SymbolValue(BINDING_STACK_POINTER,th) -
3530              th->binding_stack_start;
3531          scavenge((lispobj *) th->binding_stack_start,len);
3532 #ifdef LISP_FEATURE_SB_THREAD
3533          /* do the tls as well */
3534          len=fixnum_value(SymbolValue(FREE_TLS_INDEX,0)) -
3535              (sizeof (struct thread))/(sizeof (lispobj));
3536          scavenge((lispobj *) (th+1),len);
3537 #endif
3538         }
3539     }
3540
3541     /* The original CMU CL code had scavenge-read-only-space code
3542      * controlled by the Lisp-level variable
3543      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3544      * wasn't documented under what circumstances it was useful or
3545      * safe to turn it on, so it's been turned off in SBCL. If you
3546      * want/need this functionality, and can test and document it,
3547      * please submit a patch. */
3548 #if 0
3549     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3550         unsigned long read_only_space_size =
3551             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3552             (lispobj*)READ_ONLY_SPACE_START;
3553         FSHOW((stderr,
3554                "/scavenge read only space: %d bytes\n",
3555                read_only_space_size * sizeof(lispobj)));
3556         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3557     }
3558 #endif
3559
3560     /* Scavenge static space. */
3561     static_space_size =
3562         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3563         (lispobj *)STATIC_SPACE_START;
3564     if (gencgc_verbose > 1) {
3565         FSHOW((stderr,
3566                "/scavenge static space: %d bytes\n",
3567                static_space_size * sizeof(lispobj)));
3568     }
3569     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3570
3571     /* All generations but the generation being GCed need to be
3572      * scavenged. The new_space generation needs special handling as
3573      * objects may be moved in - it is handled separately below. */
3574     for (i = 0; i < NUM_GENERATIONS; i++) {
3575         if ((i != generation) && (i != new_space)) {
3576             scavenge_generation(i);
3577         }
3578     }
3579
3580     /* Finally scavenge the new_space generation. Keep going until no
3581      * more objects are moved into the new generation */
3582     scavenge_newspace_generation(new_space);
3583
3584     /* FIXME: I tried reenabling this check when debugging unrelated
3585      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3586      * Since the current GC code seems to work well, I'm guessing that
3587      * this debugging code is just stale, but I haven't tried to
3588      * figure it out. It should be figured out and then either made to
3589      * work or just deleted. */
3590 #define RESCAN_CHECK 0
3591 #if RESCAN_CHECK
3592     /* As a check re-scavenge the newspace once; no new objects should
3593      * be found. */
3594     {
3595         int old_bytes_allocated = bytes_allocated;
3596         int bytes_allocated;
3597
3598         /* Start with a full scavenge. */
3599         scavenge_newspace_generation_one_scan(new_space);
3600
3601         /* Flush the current regions, updating the tables. */
3602         gc_alloc_update_all_page_tables();
3603
3604         bytes_allocated = bytes_allocated - old_bytes_allocated;
3605
3606         if (bytes_allocated != 0) {
3607             lose("Rescan of new_space allocated %d more bytes.",
3608                  bytes_allocated);
3609         }
3610     }
3611 #endif
3612
3613     scan_weak_pointers();
3614
3615     /* Flush the current regions, updating the tables. */
3616     gc_alloc_update_all_page_tables();
3617
3618     /* Free the pages in oldspace, but not those marked dont_move. */
3619     bytes_freed = free_oldspace();
3620
3621     /* If the GC is not raising the age then lower the generation back
3622      * to its normal generation number */
3623     if (!raise) {
3624         for (i = 0; i < last_free_page; i++)
3625             if ((page_table[i].bytes_used != 0)
3626                 && (page_table[i].gen == NUM_GENERATIONS))
3627                 page_table[i].gen = generation;
3628         gc_assert(generations[generation].bytes_allocated == 0);
3629         generations[generation].bytes_allocated =
3630             generations[NUM_GENERATIONS].bytes_allocated;
3631         generations[NUM_GENERATIONS].bytes_allocated = 0;
3632     }
3633
3634     /* Reset the alloc_start_page for generation. */
3635     generations[generation].alloc_start_page = 0;
3636     generations[generation].alloc_unboxed_start_page = 0;
3637     generations[generation].alloc_large_start_page = 0;
3638     generations[generation].alloc_large_unboxed_start_page = 0;
3639
3640     if (generation >= verify_gens) {
3641         if (gencgc_verbose)
3642             SHOW("verifying");
3643         verify_gc();
3644         verify_dynamic_space();
3645     }
3646
3647     /* Set the new gc trigger for the GCed generation. */
3648     generations[generation].gc_trigger =
3649         generations[generation].bytes_allocated
3650         + generations[generation].bytes_consed_between_gc;
3651
3652     if (raise)
3653         generations[generation].num_gc = 0;
3654     else
3655         ++generations[generation].num_gc;
3656 }
3657
3658 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3659 int
3660 update_x86_dynamic_space_free_pointer(void)
3661 {
3662     int last_page = -1;
3663     int i;
3664
3665     for (i = 0; i < NUM_PAGES; i++)
3666         if ((page_table[i].allocated != FREE_PAGE_FLAG)
3667             && (page_table[i].bytes_used != 0))
3668             last_page = i;
3669
3670     last_free_page = last_page+1;
3671
3672     SetSymbolValue(ALLOCATION_POINTER,
3673                    (lispobj)(((char *)heap_base) + last_free_page*PAGE_BYTES),0);
3674     return 0; /* dummy value: return something ... */
3675 }
3676
3677 /* GC all generations newer than last_gen, raising the objects in each
3678  * to the next older generation - we finish when all generations below
3679  * last_gen are empty.  Then if last_gen is due for a GC, or if
3680  * last_gen==NUM_GENERATIONS (the scratch generation?  eh?) we GC that
3681  * too.  The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3682  *
3683  * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3684  * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3685  
3686 void
3687 collect_garbage(unsigned last_gen)
3688 {
3689     int gen = 0;
3690     int raise;
3691     int gen_to_wp;
3692     int i;
3693
3694     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
3695
3696     if (last_gen > NUM_GENERATIONS) {
3697         FSHOW((stderr,
3698                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3699                last_gen));
3700         last_gen = 0;
3701     }
3702
3703     /* Flush the alloc regions updating the tables. */
3704     gc_alloc_update_all_page_tables();
3705
3706     /* Verify the new objects created by Lisp code. */
3707     if (pre_verify_gen_0) {
3708         FSHOW((stderr, "pre-checking generation 0\n"));
3709         verify_generation(0);
3710     }
3711
3712     if (gencgc_verbose > 1)
3713         print_generation_stats(0);
3714
3715     do {
3716         /* Collect the generation. */
3717
3718         if (gen >= gencgc_oldest_gen_to_gc) {
3719             /* Never raise the oldest generation. */
3720             raise = 0;
3721         } else {
3722             raise =
3723                 (gen < last_gen)
3724                 || (generations[gen].num_gc >= generations[gen].trigger_age);
3725         }
3726
3727         if (gencgc_verbose > 1) {
3728             FSHOW((stderr,
3729                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3730                    gen,
3731                    raise,
3732                    generations[gen].bytes_allocated,
3733                    generations[gen].gc_trigger,
3734                    generations[gen].num_gc));
3735         }
3736
3737         /* If an older generation is being filled, then update its
3738          * memory age. */
3739         if (raise == 1) {
3740             generations[gen+1].cum_sum_bytes_allocated +=
3741                 generations[gen+1].bytes_allocated;
3742         }
3743
3744         garbage_collect_generation(gen, raise);
3745
3746         /* Reset the memory age cum_sum. */
3747         generations[gen].cum_sum_bytes_allocated = 0;
3748
3749         if (gencgc_verbose > 1) {
3750             FSHOW((stderr, "GC of generation %d finished:\n", gen));
3751             print_generation_stats(0);
3752         }
3753
3754         gen++;
3755     } while ((gen <= gencgc_oldest_gen_to_gc)
3756              && ((gen < last_gen)
3757                  || ((gen <= gencgc_oldest_gen_to_gc)
3758                      && raise
3759                      && (generations[gen].bytes_allocated
3760                          > generations[gen].gc_trigger)
3761                      && (gen_av_mem_age(gen)
3762                          > generations[gen].min_av_mem_age))));
3763
3764     /* Now if gen-1 was raised all generations before gen are empty.
3765      * If it wasn't raised then all generations before gen-1 are empty.
3766      *
3767      * Now objects within this gen's pages cannot point to younger
3768      * generations unless they are written to. This can be exploited
3769      * by write-protecting the pages of gen; then when younger
3770      * generations are GCed only the pages which have been written
3771      * need scanning. */
3772     if (raise)
3773         gen_to_wp = gen;
3774     else
3775         gen_to_wp = gen - 1;
3776
3777     /* There's not much point in WPing pages in generation 0 as it is
3778      * never scavenged (except promoted pages). */
3779     if ((gen_to_wp > 0) && enable_page_protection) {
3780         /* Check that they are all empty. */
3781         for (i = 0; i < gen_to_wp; i++) {
3782             if (generations[i].bytes_allocated)
3783                 lose("trying to write-protect gen. %d when gen. %d nonempty",
3784                      gen_to_wp, i);
3785         }
3786         write_protect_generation_pages(gen_to_wp);
3787     }
3788
3789     /* Set gc_alloc() back to generation 0. The current regions should
3790      * be flushed after the above GCs. */
3791     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
3792     gc_alloc_generation = 0;
3793
3794     update_x86_dynamic_space_free_pointer();
3795     auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
3796     if(gencgc_verbose)
3797         fprintf(stderr,"Next gc when %ld bytes have been consed\n",
3798                 auto_gc_trigger);
3799     SHOW("returning from collect_garbage");
3800 }
3801
3802 /* This is called by Lisp PURIFY when it is finished. All live objects
3803  * will have been moved to the RO and Static heaps. The dynamic space
3804  * will need a full re-initialization. We don't bother having Lisp
3805  * PURIFY flush the current gc_alloc() region, as the page_tables are
3806  * re-initialized, and every page is zeroed to be sure. */
3807 void
3808 gc_free_heap(void)
3809 {
3810     int page;
3811
3812     if (gencgc_verbose > 1)
3813         SHOW("entering gc_free_heap");
3814
3815     for (page = 0; page < NUM_PAGES; page++) {
3816         /* Skip free pages which should already be zero filled. */
3817         if (page_table[page].allocated != FREE_PAGE_FLAG) {
3818             void *page_start, *addr;
3819
3820             /* Mark the page free. The other slots are assumed invalid
3821              * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
3822              * should not be write-protected -- except that the
3823              * generation is used for the current region but it sets
3824              * that up. */
3825             page_table[page].allocated = FREE_PAGE_FLAG;
3826             page_table[page].bytes_used = 0;
3827
3828             /* Zero the page. */
3829             page_start = (void *)page_address(page);
3830
3831             /* First, remove any write-protection. */
3832             os_protect(page_start, PAGE_BYTES, OS_VM_PROT_ALL);
3833             page_table[page].write_protected = 0;
3834
3835             os_invalidate(page_start,PAGE_BYTES);
3836             addr = os_validate(page_start,PAGE_BYTES);
3837             if (addr == NULL || addr != page_start) {
3838                 lose("gc_free_heap: page moved, 0x%08x ==> 0x%08x",
3839                      page_start,
3840                      addr);
3841             }
3842         } else if (gencgc_zero_check_during_free_heap) {
3843             /* Double-check that the page is zero filled. */
3844             int *page_start, i;
3845             gc_assert(page_table[page].allocated == FREE_PAGE_FLAG);
3846             gc_assert(page_table[page].bytes_used == 0);
3847             page_start = (int *)page_address(page);
3848             for (i=0; i<1024; i++) {
3849                 if (page_start[i] != 0) {
3850                     lose("free region not zero at %x", page_start + i);
3851                 }
3852             }
3853         }
3854     }
3855
3856     bytes_allocated = 0;
3857
3858     /* Initialize the generations. */
3859     for (page = 0; page < NUM_GENERATIONS; page++) {
3860         generations[page].alloc_start_page = 0;
3861         generations[page].alloc_unboxed_start_page = 0;
3862         generations[page].alloc_large_start_page = 0;
3863         generations[page].alloc_large_unboxed_start_page = 0;
3864         generations[page].bytes_allocated = 0;
3865         generations[page].gc_trigger = 2000000;
3866         generations[page].num_gc = 0;
3867         generations[page].cum_sum_bytes_allocated = 0;
3868     }
3869
3870     if (gencgc_verbose > 1)
3871         print_generation_stats(0);
3872
3873     /* Initialize gc_alloc(). */
3874     gc_alloc_generation = 0;
3875
3876     gc_set_region_empty(&boxed_region);
3877     gc_set_region_empty(&unboxed_region);
3878
3879     last_free_page = 0;
3880     SetSymbolValue(ALLOCATION_POINTER, (lispobj)((char *)heap_base),0);
3881
3882     if (verify_after_free_heap) {
3883         /* Check whether purify has left any bad pointers. */
3884         if (gencgc_verbose)
3885             SHOW("checking after free_heap\n");
3886         verify_gc();
3887     }
3888 }
3889 \f
3890 void
3891 gc_init(void)
3892 {
3893     int i;
3894
3895     gc_init_tables();
3896     scavtab[SIMPLE_VECTOR_WIDETAG] = scav_vector;
3897     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
3898     transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
3899
3900     heap_base = (void*)DYNAMIC_SPACE_START;
3901
3902     /* Initialize each page structure. */
3903     for (i = 0; i < NUM_PAGES; i++) {
3904         /* Initialize all pages as free. */
3905         page_table[i].allocated = FREE_PAGE_FLAG;
3906         page_table[i].bytes_used = 0;
3907
3908         /* Pages are not write-protected at startup. */
3909         page_table[i].write_protected = 0;
3910     }
3911
3912     bytes_allocated = 0;
3913
3914     /* Initialize the generations.
3915      *
3916      * FIXME: very similar to code in gc_free_heap(), should be shared */
3917     for (i = 0; i < NUM_GENERATIONS; i++) {
3918         generations[i].alloc_start_page = 0;
3919         generations[i].alloc_unboxed_start_page = 0;
3920         generations[i].alloc_large_start_page = 0;
3921         generations[i].alloc_large_unboxed_start_page = 0;
3922         generations[i].bytes_allocated = 0;
3923         generations[i].gc_trigger = 2000000;
3924         generations[i].num_gc = 0;
3925         generations[i].cum_sum_bytes_allocated = 0;
3926         /* the tune-able parameters */
3927         generations[i].bytes_consed_between_gc = 2000000;
3928         generations[i].trigger_age = 1;
3929         generations[i].min_av_mem_age = 0.75;
3930     }
3931
3932     /* Initialize gc_alloc. */
3933     gc_alloc_generation = 0;
3934     gc_set_region_empty(&boxed_region);
3935     gc_set_region_empty(&unboxed_region);
3936
3937     last_free_page = 0;
3938
3939 }
3940
3941 /*  Pick up the dynamic space from after a core load.
3942  *
3943  *  The ALLOCATION_POINTER points to the end of the dynamic space.
3944  */
3945
3946 static void
3947 gencgc_pickup_dynamic(void)
3948 {
3949     int page = 0;
3950     int alloc_ptr = SymbolValue(ALLOCATION_POINTER,0);
3951     lispobj *prev=(lispobj *)page_address(page);
3952
3953     do {
3954         lispobj *first,*ptr= (lispobj *)page_address(page);
3955         page_table[page].allocated = BOXED_PAGE_FLAG;
3956         page_table[page].gen = 0;
3957         page_table[page].bytes_used = PAGE_BYTES;
3958         page_table[page].large_object = 0;
3959
3960         first=search_space(prev,(ptr+2)-prev,ptr);
3961         if(ptr == first)  prev=ptr; 
3962         page_table[page].first_object_offset =
3963             (void *)prev - page_address(page);
3964         page++;
3965     } while (page_address(page) < alloc_ptr);
3966
3967     generations[0].bytes_allocated = PAGE_BYTES*page;
3968     bytes_allocated = PAGE_BYTES*page;
3969
3970 }
3971
3972
3973 void
3974 gc_initialize_pointers(void)
3975 {
3976     gencgc_pickup_dynamic();
3977 }
3978
3979
3980 \f
3981
3982 /* alloc(..) is the external interface for memory allocation. It
3983  * allocates to generation 0. It is not called from within the garbage
3984  * collector as it is only external uses that need the check for heap
3985  * size (GC trigger) and to disable the interrupts (interrupts are
3986  * always disabled during a GC).
3987  *
3988  * The vops that call alloc(..) assume that the returned space is zero-filled.
3989  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
3990  *
3991  * The check for a GC trigger is only performed when the current
3992  * region is full, so in most cases it's not needed. */
3993
3994 char *
3995 alloc(int nbytes)
3996 {
3997     struct thread *th=arch_os_get_current_thread();
3998     struct alloc_region *region=
3999 #ifdef LISP_FEATURE_SB_THREAD
4000         th ? &(th->alloc_region) : &boxed_region; 
4001 #else
4002         &boxed_region; 
4003 #endif
4004     void *new_obj;
4005     void *new_free_pointer;
4006
4007     /* Check for alignment allocation problems. */
4008     gc_assert((((unsigned)region->free_pointer & 0x7) == 0)
4009               && ((nbytes & 0x7) == 0));
4010     if(all_threads)
4011         /* there are a few places in the C code that allocate data in the
4012          * heap before Lisp starts.  This is before interrupts are enabled,
4013          * so we don't need to check for pseudo-atomic */
4014 #ifdef LISP_FEATURE_SB_THREAD
4015         if(!SymbolValue(PSEUDO_ATOMIC_ATOMIC,th)) {
4016             register u32 fs;
4017             fprintf(stderr, "fatal error in thread 0x%x, pid=%d\n",
4018                     th,getpid());
4019             __asm__("movl %fs,%0" : "=r" (fs)  : );
4020             fprintf(stderr, "fs is %x, th->tls_cookie=%x \n",
4021                     debug_get_fs(),th->tls_cookie);
4022             lose("If you see this message before 2004.01.31, mail details to sbcl-devel\n");
4023         }
4024 #else
4025     gc_assert(SymbolValue(PSEUDO_ATOMIC_ATOMIC,th));
4026 #endif
4027     
4028     /* maybe we can do this quickly ... */
4029     new_free_pointer = region->free_pointer + nbytes;
4030     if (new_free_pointer <= region->end_addr) {
4031         new_obj = (void*)(region->free_pointer);
4032         region->free_pointer = new_free_pointer;
4033         return(new_obj);        /* yup */
4034     }
4035     
4036     /* we have to go the long way around, it seems.  Check whether 
4037      * we should GC in the near future
4038      */
4039     if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
4040         /* set things up so that GC happens when we finish the PA
4041          * section.  We only do this if there wasn't a pending handler
4042          * already, in case it was a gc.  If it wasn't a GC, the next
4043          * allocation will get us back to this point anyway, so no harm done
4044          */
4045         struct interrupt_data *data=th->interrupt_data;
4046         if(!data->pending_handler) 
4047             maybe_defer_handler(interrupt_maybe_gc_int,data,0,0,0);
4048     }
4049     new_obj = gc_alloc_with_region(nbytes,0,region,0);
4050     return (new_obj);
4051 }
4052 \f
4053 /*
4054  * shared support for the OS-dependent signal handlers which
4055  * catch GENCGC-related write-protect violations
4056  */
4057
4058 void unhandled_sigmemoryfault(void);
4059
4060 /* Depending on which OS we're running under, different signals might
4061  * be raised for a violation of write protection in the heap. This
4062  * function factors out the common generational GC magic which needs
4063  * to invoked in this case, and should be called from whatever signal
4064  * handler is appropriate for the OS we're running under.
4065  *
4066  * Return true if this signal is a normal generational GC thing that
4067  * we were able to handle, or false if it was abnormal and control
4068  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
4069
4070 int
4071 gencgc_handle_wp_violation(void* fault_addr)
4072 {
4073     int  page_index = find_page_index(fault_addr);
4074
4075 #ifdef QSHOW_SIGNALS
4076     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4077            fault_addr, page_index));
4078 #endif
4079
4080     /* Check whether the fault is within the dynamic space. */
4081     if (page_index == (-1)) {
4082
4083         /* It can be helpful to be able to put a breakpoint on this
4084          * case to help diagnose low-level problems. */
4085         unhandled_sigmemoryfault();
4086
4087         /* not within the dynamic space -- not our responsibility */
4088         return 0;
4089
4090     } else {
4091         if (page_table[page_index].write_protected) {
4092             /* Unprotect the page. */
4093             os_protect(page_address(page_index), PAGE_BYTES, OS_VM_PROT_ALL);
4094             page_table[page_index].write_protected_cleared = 1;
4095             page_table[page_index].write_protected = 0;
4096         } else {  
4097             /* The only acceptable reason for this signal on a heap
4098              * access is that GENCGC write-protected the page.
4099              * However, if two CPUs hit a wp page near-simultaneously,
4100              * we had better not have the second one lose here if it
4101              * does this test after the first one has already set wp=0
4102              */
4103             if(page_table[page_index].write_protected_cleared != 1) 
4104                 lose("fault in heap page not marked as write-protected");
4105         }
4106         /* Don't worry, we can handle it. */
4107         return 1;
4108     }
4109 }
4110 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4111  * it's not just a case of the program hitting the write barrier, and
4112  * are about to let Lisp deal with it. It's basically just a
4113  * convenient place to set a gdb breakpoint. */
4114 void
4115 unhandled_sigmemoryfault()
4116 {}
4117
4118 void gc_alloc_update_all_page_tables(void)
4119 {
4120     /* Flush the alloc regions updating the tables. */
4121     struct thread *th;
4122     for_each_thread(th) 
4123         gc_alloc_update_page_tables(0, &th->alloc_region);
4124     gc_alloc_update_page_tables(1, &unboxed_region);
4125     gc_alloc_update_page_tables(0, &boxed_region);
4126 }
4127 void 
4128 gc_set_region_empty(struct alloc_region *region)
4129 {
4130     region->first_page = 0;
4131     region->last_page = -1;
4132     region->start_addr = page_address(0);
4133     region->free_pointer = page_address(0);
4134     region->end_addr = page_address(0);
4135 }
4136