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