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