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