2 * GENerational Conservative Garbage Collector for SBCL
6 * This software is part of the SBCL system. See the README file for
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.
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>
24 * <ftp://ftp.cs.utexas.edu/pub/garbage/bigsurv.ps>.
37 #include "interrupt.h"
42 #include "gc-internal.h"
44 #include "pseudo-atomic.h"
46 #include "genesis/vector.h"
47 #include "genesis/weak-pointer.h"
48 #include "genesis/fdefn.h"
49 #include "genesis/simple-fun.h"
51 #include "genesis/hash-table.h"
52 #include "genesis/instance.h"
53 #include "genesis/layout.h"
55 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
56 #include "genesis/cons.h"
59 /* forward declarations */
60 page_index_t gc_find_freeish_pages(page_index_t *restart_page_ptr, long nbytes,
68 /* Generations 0-5 are normal collected generations, 6 is only used as
69 * scratch space by the collector, and should never get collected.
72 SCRATCH_GENERATION = PSEUDO_STATIC_GENERATION+1,
76 /* Should we use page protection to help avoid the scavenging of pages
77 * that don't have pointers to younger generations? */
78 boolean enable_page_protection = 1;
80 /* the minimum size (in bytes) for a large object*/
81 #if (GENCGC_ALLOC_GRANULARITY >= PAGE_BYTES) && (GENCGC_ALLOC_GRANULARITY >= GENCGC_CARD_BYTES)
82 os_vm_size_t large_object_size = 4 * GENCGC_ALLOC_GRANULARITY;
83 #elif (GENCGC_CARD_BYTES >= PAGE_BYTES) && (GENCGC_CARD_BYTES >= GENCGC_ALLOC_GRANULARITY)
84 os_vm_size_t large_object_size = 4 * GENCGC_CARD_BYTES;
86 os_vm_size_t large_object_size = 4 * PAGE_BYTES;
89 /* Largest allocation seen since last GC. */
90 os_vm_size_t large_allocation = 0;
97 /* the verbosity level. All non-error messages are disabled at level 0;
98 * and only a few rare messages are printed at level 1. */
100 boolean gencgc_verbose = 1;
102 boolean gencgc_verbose = 0;
105 /* FIXME: At some point enable the various error-checking things below
106 * and see what they say. */
108 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
109 * Set verify_gens to HIGHEST_NORMAL_GENERATION + 1 to disable this kind of
111 generation_index_t verify_gens = HIGHEST_NORMAL_GENERATION + 1;
113 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
114 boolean pre_verify_gen_0 = 0;
116 /* Should we check for bad pointers after gc_free_heap is called
117 * from Lisp PURIFY? */
118 boolean verify_after_free_heap = 0;
120 /* Should we print a note when code objects are found in the dynamic space
121 * during a heap verify? */
122 boolean verify_dynamic_code_check = 0;
124 /* Should we check code objects for fixup errors after they are transported? */
125 boolean check_code_fixups = 0;
127 /* Should we check that newly allocated regions are zero filled? */
128 boolean gencgc_zero_check = 0;
130 /* Should we check that the free space is zero filled? */
131 boolean gencgc_enable_verify_zero_fill = 0;
133 /* Should we check that free pages are zero filled during gc_free_heap
134 * called after Lisp PURIFY? */
135 boolean gencgc_zero_check_during_free_heap = 0;
137 /* When loading a core, don't do a full scan of the memory for the
138 * memory region boundaries. (Set to true by coreparse.c if the core
139 * contained a pagetable entry).
141 boolean gencgc_partial_pickup = 0;
143 /* If defined, free pages are read-protected to ensure that nothing
147 /* #define READ_PROTECT_FREE_PAGES */
151 * GC structures and variables
154 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
155 os_vm_size_t bytes_allocated = 0;
156 os_vm_size_t auto_gc_trigger = 0;
158 /* the source and destination generations. These are set before a GC starts
160 generation_index_t from_space;
161 generation_index_t new_space;
163 /* Set to 1 when in GC */
164 boolean gc_active_p = 0;
166 /* should the GC be conservative on stack. If false (only right before
167 * saving a core), don't scan the stack / mark pages dont_move. */
168 static boolean conservative_stack = 1;
170 /* An array of page structures is allocated on gc initialization.
171 * This helps to quickly map between an address and its page structure.
172 * page_table_pages is set from the size of the dynamic space. */
173 page_index_t page_table_pages;
174 struct page *page_table;
176 static inline boolean page_allocated_p(page_index_t page) {
177 return (page_table[page].allocated != FREE_PAGE_FLAG);
180 static inline boolean page_no_region_p(page_index_t page) {
181 return !(page_table[page].allocated & OPEN_REGION_PAGE_FLAG);
184 static inline boolean page_allocated_no_region_p(page_index_t page) {
185 return ((page_table[page].allocated & (UNBOXED_PAGE_FLAG | BOXED_PAGE_FLAG))
186 && page_no_region_p(page));
189 static inline boolean page_free_p(page_index_t page) {
190 return (page_table[page].allocated == FREE_PAGE_FLAG);
193 static inline boolean page_boxed_p(page_index_t page) {
194 return (page_table[page].allocated & BOXED_PAGE_FLAG);
197 static inline boolean code_page_p(page_index_t page) {
198 return (page_table[page].allocated & CODE_PAGE_FLAG);
201 static inline boolean page_boxed_no_region_p(page_index_t page) {
202 return page_boxed_p(page) && page_no_region_p(page);
205 static inline boolean page_unboxed_p(page_index_t page) {
206 /* Both flags set == boxed code page */
207 return ((page_table[page].allocated & UNBOXED_PAGE_FLAG)
208 && !page_boxed_p(page));
211 static inline boolean protect_page_p(page_index_t page, generation_index_t generation) {
212 return (page_boxed_no_region_p(page)
213 && (page_table[page].bytes_used != 0)
214 && !page_table[page].dont_move
215 && (page_table[page].gen == generation));
218 /* To map addresses to page structures the address of the first page
220 static void *heap_base = NULL;
222 /* Calculate the start address for the given page number. */
224 page_address(page_index_t page_num)
226 return (heap_base + (page_num * GENCGC_CARD_BYTES));
229 /* Calculate the address where the allocation region associated with
230 * the page starts. */
232 page_region_start(page_index_t page_index)
234 return page_address(page_index)-page_table[page_index].region_start_offset;
237 /* Find the page index within the page_table for the given
238 * address. Return -1 on failure. */
240 find_page_index(void *addr)
242 if (addr >= heap_base) {
243 page_index_t index = ((pointer_sized_uint_t)addr -
244 (pointer_sized_uint_t)heap_base) / GENCGC_CARD_BYTES;
245 if (index < page_table_pages)
252 npage_bytes(page_index_t npages)
254 gc_assert(npages>=0);
255 return ((os_vm_size_t)npages)*GENCGC_CARD_BYTES;
258 /* Check that X is a higher address than Y and return offset from Y to
260 static inline os_vm_size_t
261 void_diff(void *x, void *y)
264 return (pointer_sized_uint_t)x - (pointer_sized_uint_t)y;
267 /* a structure to hold the state of a generation
269 * CAUTION: If you modify this, make sure to touch up the alien
270 * definition in src/code/gc.lisp accordingly. ...or better yes,
271 * deal with the FIXME there...
275 /* the first page that gc_alloc() checks on its next call */
276 page_index_t alloc_start_page;
278 /* the first page that gc_alloc_unboxed() checks on its next call */
279 page_index_t alloc_unboxed_start_page;
281 /* the first page that gc_alloc_large (boxed) considers on its next
282 * call. (Although it always allocates after the boxed_region.) */
283 page_index_t alloc_large_start_page;
285 /* the first page that gc_alloc_large (unboxed) considers on its
286 * next call. (Although it always allocates after the
287 * current_unboxed_region.) */
288 page_index_t alloc_large_unboxed_start_page;
290 /* the bytes allocated to this generation */
291 os_vm_size_t bytes_allocated;
293 /* the number of bytes at which to trigger a GC */
294 os_vm_size_t gc_trigger;
296 /* to calculate a new level for gc_trigger */
297 os_vm_size_t bytes_consed_between_gc;
299 /* the number of GCs since the last raise */
302 /* the number of GCs to run on the generations before raising objects to the
304 int number_of_gcs_before_promotion;
306 /* the cumulative sum of the bytes allocated to this generation. It is
307 * cleared after a GC on this generations, and update before new
308 * objects are added from a GC of a younger generation. Dividing by
309 * the bytes_allocated will give the average age of the memory in
310 * this generation since its last GC. */
311 os_vm_size_t cum_sum_bytes_allocated;
313 /* a minimum average memory age before a GC will occur helps
314 * prevent a GC when a large number of new live objects have been
315 * added, in which case a GC could be a waste of time */
316 double minimum_age_before_gc;
319 /* an array of generation structures. There needs to be one more
320 * generation structure than actual generations as the oldest
321 * generation is temporarily raised then lowered. */
322 struct generation generations[NUM_GENERATIONS];
324 /* the oldest generation that is will currently be GCed by default.
325 * Valid values are: 0, 1, ... HIGHEST_NORMAL_GENERATION
327 * The default of HIGHEST_NORMAL_GENERATION enables GC on all generations.
329 * Setting this to 0 effectively disables the generational nature of
330 * the GC. In some applications generational GC may not be useful
331 * because there are no long-lived objects.
333 * An intermediate value could be handy after moving long-lived data
334 * into an older generation so an unnecessary GC of this long-lived
335 * data can be avoided. */
336 generation_index_t gencgc_oldest_gen_to_gc = HIGHEST_NORMAL_GENERATION;
338 /* The maximum free page in the heap is maintained and used to update
339 * ALLOCATION_POINTER which is used by the room function to limit its
340 * search of the heap. XX Gencgc obviously needs to be better
341 * integrated with the Lisp code. */
342 page_index_t last_free_page;
344 #ifdef LISP_FEATURE_SB_THREAD
345 /* This lock is to prevent multiple threads from simultaneously
346 * allocating new regions which overlap each other. Note that the
347 * majority of GC is single-threaded, but alloc() may be called from
348 * >1 thread at a time and must be thread-safe. This lock must be
349 * seized before all accesses to generations[] or to parts of
350 * page_table[] that other threads may want to see */
351 static pthread_mutex_t free_pages_lock = PTHREAD_MUTEX_INITIALIZER;
352 /* This lock is used to protect non-thread-local allocation. */
353 static pthread_mutex_t allocation_lock = PTHREAD_MUTEX_INITIALIZER;
356 extern os_vm_size_t gencgc_release_granularity;
357 os_vm_size_t gencgc_release_granularity = GENCGC_RELEASE_GRANULARITY;
359 extern os_vm_size_t gencgc_alloc_granularity;
360 os_vm_size_t gencgc_alloc_granularity = GENCGC_ALLOC_GRANULARITY;
364 * miscellaneous heap functions
367 /* Count the number of pages which are write-protected within the
368 * given generation. */
370 count_write_protect_generation_pages(generation_index_t generation)
372 page_index_t i, count = 0;
374 for (i = 0; i < last_free_page; i++)
375 if (page_allocated_p(i)
376 && (page_table[i].gen == generation)
377 && (page_table[i].write_protected == 1))
382 /* Count the number of pages within the given generation. */
384 count_generation_pages(generation_index_t generation)
387 page_index_t count = 0;
389 for (i = 0; i < last_free_page; i++)
390 if (page_allocated_p(i)
391 && (page_table[i].gen == generation))
398 count_dont_move_pages(void)
401 page_index_t count = 0;
402 for (i = 0; i < last_free_page; i++) {
403 if (page_allocated_p(i)
404 && (page_table[i].dont_move != 0)) {
412 /* Work through the pages and add up the number of bytes used for the
413 * given generation. */
415 count_generation_bytes_allocated (generation_index_t gen)
418 os_vm_size_t result = 0;
419 for (i = 0; i < last_free_page; i++) {
420 if (page_allocated_p(i)
421 && (page_table[i].gen == gen))
422 result += page_table[i].bytes_used;
427 /* Return the average age of the memory in a generation. */
429 generation_average_age(generation_index_t gen)
431 if (generations[gen].bytes_allocated == 0)
435 ((double)generations[gen].cum_sum_bytes_allocated)
436 / ((double)generations[gen].bytes_allocated);
440 write_generation_stats(FILE *file)
442 generation_index_t i;
444 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
445 #define FPU_STATE_SIZE 27
446 int fpu_state[FPU_STATE_SIZE];
447 #elif defined(LISP_FEATURE_PPC)
448 #define FPU_STATE_SIZE 32
449 long long fpu_state[FPU_STATE_SIZE];
450 #elif defined(LISP_FEATURE_SPARC)
452 * 32 (single-precision) FP registers, and the FP state register.
453 * But Sparc V9 has 32 double-precision registers (equivalent to 64
454 * single-precision, but can't be accessed), so we leave enough room
457 #define FPU_STATE_SIZE (((32 + 32 + 1) + 1)/2)
458 long long fpu_state[FPU_STATE_SIZE];
461 /* This code uses the FP instructions which may be set up for Lisp
462 * so they need to be saved and reset for C. */
465 /* Print the heap stats. */
467 " Gen StaPg UbSta LaSta LUbSt Boxed Unboxed LB LUB !move Alloc Waste Trig WP GCs Mem-age\n");
469 for (i = 0; i < SCRATCH_GENERATION; i++) {
471 page_index_t boxed_cnt = 0;
472 page_index_t unboxed_cnt = 0;
473 page_index_t large_boxed_cnt = 0;
474 page_index_t large_unboxed_cnt = 0;
475 page_index_t pinned_cnt=0;
477 for (j = 0; j < last_free_page; j++)
478 if (page_table[j].gen == i) {
480 /* Count the number of boxed pages within the given
482 if (page_boxed_p(j)) {
483 if (page_table[j].large_object)
488 if(page_table[j].dont_move) pinned_cnt++;
489 /* Count the number of unboxed pages within the given
491 if (page_unboxed_p(j)) {
492 if (page_table[j].large_object)
499 gc_assert(generations[i].bytes_allocated
500 == count_generation_bytes_allocated(i));
502 " %1d: %5ld %5ld %5ld %5ld",
504 generations[i].alloc_start_page,
505 generations[i].alloc_unboxed_start_page,
506 generations[i].alloc_large_start_page,
507 generations[i].alloc_large_unboxed_start_page);
509 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT
510 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT,
511 boxed_cnt, unboxed_cnt, large_boxed_cnt,
512 large_unboxed_cnt, pinned_cnt);
517 " %4"PAGE_INDEX_FMT" %3d %7.4f\n",
518 generations[i].bytes_allocated,
519 (npage_bytes(count_generation_pages(i)) - generations[i].bytes_allocated),
520 generations[i].gc_trigger,
521 count_write_protect_generation_pages(i),
522 generations[i].num_gc,
523 generation_average_age(i));
525 fprintf(file," Total bytes allocated = %"OS_VM_SIZE_FMT"\n", bytes_allocated);
526 fprintf(file," Dynamic-space-size bytes = %"OS_VM_SIZE_FMT"\n", dynamic_space_size);
528 fpu_restore(fpu_state);
532 write_heap_exhaustion_report(FILE *file, long available, long requested,
533 struct thread *thread)
536 "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
537 gc_active_p ? "garbage collection" : "allocation",
540 write_generation_stats(file);
541 fprintf(file, "GC control variables:\n");
542 fprintf(file, " *GC-INHIBIT* = %s\n *GC-PENDING* = %s\n",
543 SymbolValue(GC_INHIBIT,thread)==NIL ? "false" : "true",
544 (SymbolValue(GC_PENDING, thread) == T) ?
545 "true" : ((SymbolValue(GC_PENDING, thread) == NIL) ?
546 "false" : "in progress"));
547 #ifdef LISP_FEATURE_SB_THREAD
548 fprintf(file, " *STOP-FOR-GC-PENDING* = %s\n",
549 SymbolValue(STOP_FOR_GC_PENDING,thread)==NIL ? "false" : "true");
554 print_generation_stats(void)
556 write_generation_stats(stderr);
559 extern char* gc_logfile;
560 char * gc_logfile = NULL;
563 log_generation_stats(char *logfile, char *header)
566 FILE * log = fopen(logfile, "a");
568 fprintf(log, "%s\n", header);
569 write_generation_stats(log);
572 fprintf(stderr, "Could not open gc logfile: %s\n", logfile);
579 report_heap_exhaustion(long available, long requested, struct thread *th)
582 FILE * log = fopen(gc_logfile, "a");
584 write_heap_exhaustion_report(log, available, requested, th);
587 fprintf(stderr, "Could not open gc logfile: %s\n", gc_logfile);
591 /* Always to stderr as well. */
592 write_heap_exhaustion_report(stderr, available, requested, th);
596 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
597 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
600 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
601 * if zeroing it ourselves, i.e. in practice give the memory back to the
602 * OS. Generally done after a large GC.
604 void zero_pages_with_mmap(page_index_t start, page_index_t end) {
606 void *addr = page_address(start), *new_addr;
607 os_vm_size_t length = npage_bytes(1+end-start);
612 gc_assert(length >= gencgc_release_granularity);
613 gc_assert((length % gencgc_release_granularity) == 0);
615 os_invalidate(addr, length);
616 new_addr = os_validate(addr, length);
617 if (new_addr == NULL || new_addr != addr) {
618 lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
622 for (i = start; i <= end; i++) {
623 page_table[i].need_to_zero = 0;
627 /* Zero the pages from START to END (inclusive). Generally done just after
628 * a new region has been allocated.
631 zero_pages(page_index_t start, page_index_t end) {
635 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
636 fast_bzero(page_address(start), npage_bytes(1+end-start));
638 bzero(page_address(start), npage_bytes(1+end-start));
644 zero_and_mark_pages(page_index_t start, page_index_t end) {
647 zero_pages(start, end);
648 for (i = start; i <= end; i++)
649 page_table[i].need_to_zero = 0;
652 /* Zero the pages from START to END (inclusive), except for those
653 * pages that are known to already zeroed. Mark all pages in the
654 * ranges as non-zeroed.
657 zero_dirty_pages(page_index_t start, page_index_t end) {
660 for (i = start; i <= end; i++) {
661 if (!page_table[i].need_to_zero) continue;
662 for (j = i+1; (j <= end) && (page_table[j].need_to_zero); j++);
667 for (i = start; i <= end; i++) {
668 page_table[i].need_to_zero = 1;
674 * To support quick and inline allocation, regions of memory can be
675 * allocated and then allocated from with just a free pointer and a
676 * check against an end address.
678 * Since objects can be allocated to spaces with different properties
679 * e.g. boxed/unboxed, generation, ages; there may need to be many
680 * allocation regions.
682 * Each allocation region may start within a partly used page. Many
683 * features of memory use are noted on a page wise basis, e.g. the
684 * generation; so if a region starts within an existing allocated page
685 * it must be consistent with this page.
687 * During the scavenging of the newspace, objects will be transported
688 * into an allocation region, and pointers updated to point to this
689 * allocation region. It is possible that these pointers will be
690 * scavenged again before the allocation region is closed, e.g. due to
691 * trans_list which jumps all over the place to cleanup the list. It
692 * is important to be able to determine properties of all objects
693 * pointed to when scavenging, e.g to detect pointers to the oldspace.
694 * Thus it's important that the allocation regions have the correct
695 * properties set when allocated, and not just set when closed. The
696 * region allocation routines return regions with the specified
697 * properties, and grab all the pages, setting their properties
698 * appropriately, except that the amount used is not known.
700 * These regions are used to support quicker allocation using just a
701 * free pointer. The actual space used by the region is not reflected
702 * in the pages tables until it is closed. It can't be scavenged until
705 * When finished with the region it should be closed, which will
706 * update the page tables for the actual space used returning unused
707 * space. Further it may be noted in the new regions which is
708 * necessary when scavenging the newspace.
710 * Large objects may be allocated directly without an allocation
711 * region, the page tables are updated immediately.
713 * Unboxed objects don't contain pointers to other objects and so
714 * don't need scavenging. Further they can't contain pointers to
715 * younger generations so WP is not needed. By allocating pages to
716 * unboxed objects the whole page never needs scavenging or
717 * write-protecting. */
719 /* We are only using two regions at present. Both are for the current
720 * newspace generation. */
721 struct alloc_region boxed_region;
722 struct alloc_region unboxed_region;
724 /* The generation currently being allocated to. */
725 static generation_index_t gc_alloc_generation;
727 static inline page_index_t
728 generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large)
731 if (UNBOXED_PAGE_FLAG == page_type_flag) {
732 return generations[generation].alloc_large_unboxed_start_page;
733 } else if (BOXED_PAGE_FLAG & page_type_flag) {
734 /* Both code and data. */
735 return generations[generation].alloc_large_start_page;
737 lose("bad page type flag: %d", page_type_flag);
740 if (UNBOXED_PAGE_FLAG == page_type_flag) {
741 return generations[generation].alloc_unboxed_start_page;
742 } else if (BOXED_PAGE_FLAG & page_type_flag) {
743 /* Both code and data. */
744 return generations[generation].alloc_start_page;
746 lose("bad page_type_flag: %d", page_type_flag);
752 set_generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large,
756 if (UNBOXED_PAGE_FLAG == page_type_flag) {
757 generations[generation].alloc_large_unboxed_start_page = page;
758 } else if (BOXED_PAGE_FLAG & page_type_flag) {
759 /* Both code and data. */
760 generations[generation].alloc_large_start_page = page;
762 lose("bad page type flag: %d", page_type_flag);
765 if (UNBOXED_PAGE_FLAG == page_type_flag) {
766 generations[generation].alloc_unboxed_start_page = page;
767 } else if (BOXED_PAGE_FLAG & page_type_flag) {
768 /* Both code and data. */
769 generations[generation].alloc_start_page = page;
771 lose("bad page type flag: %d", page_type_flag);
776 /* Find a new region with room for at least the given number of bytes.
778 * It starts looking at the current generation's alloc_start_page. So
779 * may pick up from the previous region if there is enough space. This
780 * keeps the allocation contiguous when scavenging the newspace.
782 * The alloc_region should have been closed by a call to
783 * gc_alloc_update_page_tables(), and will thus be in an empty state.
785 * To assist the scavenging functions write-protected pages are not
786 * used. Free pages should not be write-protected.
788 * It is critical to the conservative GC that the start of regions be
789 * known. To help achieve this only small regions are allocated at a
792 * During scavenging, pointers may be found to within the current
793 * region and the page generation must be set so that pointers to the
794 * from space can be recognized. Therefore the generation of pages in
795 * the region are set to gc_alloc_generation. To prevent another
796 * allocation call using the same pages, all the pages in the region
797 * are allocated, although they will initially be empty.
800 gc_alloc_new_region(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
802 page_index_t first_page;
803 page_index_t last_page;
804 os_vm_size_t bytes_found;
810 "/alloc_new_region for %d bytes from gen %d\n",
811 nbytes, gc_alloc_generation));
814 /* Check that the region is in a reset state. */
815 gc_assert((alloc_region->first_page == 0)
816 && (alloc_region->last_page == -1)
817 && (alloc_region->free_pointer == alloc_region->end_addr));
818 ret = thread_mutex_lock(&free_pages_lock);
820 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0);
821 last_page=gc_find_freeish_pages(&first_page, nbytes, page_type_flag);
822 bytes_found=(GENCGC_CARD_BYTES - page_table[first_page].bytes_used)
823 + npage_bytes(last_page-first_page);
825 /* Set up the alloc_region. */
826 alloc_region->first_page = first_page;
827 alloc_region->last_page = last_page;
828 alloc_region->start_addr = page_table[first_page].bytes_used
829 + page_address(first_page);
830 alloc_region->free_pointer = alloc_region->start_addr;
831 alloc_region->end_addr = alloc_region->start_addr + bytes_found;
833 /* Set up the pages. */
835 /* The first page may have already been in use. */
836 if (page_table[first_page].bytes_used == 0) {
837 page_table[first_page].allocated = page_type_flag;
838 page_table[first_page].gen = gc_alloc_generation;
839 page_table[first_page].large_object = 0;
840 page_table[first_page].region_start_offset = 0;
843 gc_assert(page_table[first_page].allocated == page_type_flag);
844 page_table[first_page].allocated |= OPEN_REGION_PAGE_FLAG;
846 gc_assert(page_table[first_page].gen == gc_alloc_generation);
847 gc_assert(page_table[first_page].large_object == 0);
849 for (i = first_page+1; i <= last_page; i++) {
850 page_table[i].allocated = page_type_flag;
851 page_table[i].gen = gc_alloc_generation;
852 page_table[i].large_object = 0;
853 /* This may not be necessary for unboxed regions (think it was
855 page_table[i].region_start_offset =
856 void_diff(page_address(i),alloc_region->start_addr);
857 page_table[i].allocated |= OPEN_REGION_PAGE_FLAG ;
859 /* Bump up last_free_page. */
860 if (last_page+1 > last_free_page) {
861 last_free_page = last_page+1;
862 /* do we only want to call this on special occasions? like for
864 set_alloc_pointer((lispobj)page_address(last_free_page));
866 ret = thread_mutex_unlock(&free_pages_lock);
869 #ifdef READ_PROTECT_FREE_PAGES
870 os_protect(page_address(first_page),
871 npage_bytes(1+last_page-first_page),
875 /* If the first page was only partial, don't check whether it's
876 * zeroed (it won't be) and don't zero it (since the parts that
877 * we're interested in are guaranteed to be zeroed).
879 if (page_table[first_page].bytes_used) {
883 zero_dirty_pages(first_page, last_page);
885 /* we can do this after releasing free_pages_lock */
886 if (gencgc_zero_check) {
888 for (p = (word_t *)alloc_region->start_addr;
889 p < (word_t *)alloc_region->end_addr; p++) {
891 lose("The new region is not zero at %p (start=%p, end=%p).\n",
892 p, alloc_region->start_addr, alloc_region->end_addr);
898 /* If the record_new_objects flag is 2 then all new regions created
901 * If it's 1 then then it is only recorded if the first page of the
902 * current region is <= new_areas_ignore_page. This helps avoid
903 * unnecessary recording when doing full scavenge pass.
905 * The new_object structure holds the page, byte offset, and size of
906 * new regions of objects. Each new area is placed in the array of
907 * these structures pointer to by new_areas. new_areas_index holds the
908 * offset into new_areas.
910 * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
911 * later code must detect this and handle it, probably by doing a full
912 * scavenge of a generation. */
913 #define NUM_NEW_AREAS 512
914 static int record_new_objects = 0;
915 static page_index_t new_areas_ignore_page;
921 static struct new_area (*new_areas)[];
922 static size_t new_areas_index;
923 size_t max_new_areas;
925 /* Add a new area to new_areas. */
927 add_new_area(page_index_t first_page, size_t offset, size_t size)
929 size_t new_area_start, c;
932 /* Ignore if full. */
933 if (new_areas_index >= NUM_NEW_AREAS)
936 switch (record_new_objects) {
940 if (first_page > new_areas_ignore_page)
949 new_area_start = npage_bytes(first_page) + offset;
951 /* Search backwards for a prior area that this follows from. If
952 found this will save adding a new area. */
953 for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
955 npage_bytes((*new_areas)[i].page)
956 + (*new_areas)[i].offset
957 + (*new_areas)[i].size;
959 "/add_new_area S1 %d %d %d %d\n",
960 i, c, new_area_start, area_end));*/
961 if (new_area_start == area_end) {
963 "/adding to [%d] %d %d %d with %d %d %d:\n",
965 (*new_areas)[i].page,
966 (*new_areas)[i].offset,
967 (*new_areas)[i].size,
971 (*new_areas)[i].size += size;
976 (*new_areas)[new_areas_index].page = first_page;
977 (*new_areas)[new_areas_index].offset = offset;
978 (*new_areas)[new_areas_index].size = size;
980 "/new_area %d page %d offset %d size %d\n",
981 new_areas_index, first_page, offset, size));*/
984 /* Note the max new_areas used. */
985 if (new_areas_index > max_new_areas)
986 max_new_areas = new_areas_index;
989 /* Update the tables for the alloc_region. The region may be added to
992 * When done the alloc_region is set up so that the next quick alloc
993 * will fail safely and thus a new region will be allocated. Further
994 * it is safe to try to re-update the page table of this reset
997 gc_alloc_update_page_tables(int page_type_flag, struct alloc_region *alloc_region)
1000 page_index_t first_page;
1001 page_index_t next_page;
1002 os_vm_size_t bytes_used;
1003 os_vm_size_t region_size;
1004 os_vm_size_t byte_cnt;
1005 page_bytes_t orig_first_page_bytes_used;
1009 first_page = alloc_region->first_page;
1011 /* Catch an unused alloc_region. */
1012 if ((first_page == 0) && (alloc_region->last_page == -1))
1015 next_page = first_page+1;
1017 ret = thread_mutex_lock(&free_pages_lock);
1018 gc_assert(ret == 0);
1019 if (alloc_region->free_pointer != alloc_region->start_addr) {
1020 /* some bytes were allocated in the region */
1021 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1023 gc_assert(alloc_region->start_addr ==
1024 (page_address(first_page)
1025 + page_table[first_page].bytes_used));
1027 /* All the pages used need to be updated */
1029 /* Update the first page. */
1031 /* If the page was free then set up the gen, and
1032 * region_start_offset. */
1033 if (page_table[first_page].bytes_used == 0)
1034 gc_assert(page_table[first_page].region_start_offset == 0);
1035 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1037 gc_assert(page_table[first_page].allocated & page_type_flag);
1038 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1039 gc_assert(page_table[first_page].large_object == 0);
1043 /* Calculate the number of bytes used in this page. This is not
1044 * always the number of new bytes, unless it was free. */
1046 if ((bytes_used = void_diff(alloc_region->free_pointer,
1047 page_address(first_page)))
1048 >GENCGC_CARD_BYTES) {
1049 bytes_used = GENCGC_CARD_BYTES;
1052 page_table[first_page].bytes_used = bytes_used;
1053 byte_cnt += bytes_used;
1056 /* All the rest of the pages should be free. We need to set
1057 * their region_start_offset pointer to the start of the
1058 * region, and set the bytes_used. */
1060 page_table[next_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1061 gc_assert(page_table[next_page].allocated & page_type_flag);
1062 gc_assert(page_table[next_page].bytes_used == 0);
1063 gc_assert(page_table[next_page].gen == gc_alloc_generation);
1064 gc_assert(page_table[next_page].large_object == 0);
1066 gc_assert(page_table[next_page].region_start_offset ==
1067 void_diff(page_address(next_page),
1068 alloc_region->start_addr));
1070 /* Calculate the number of bytes used in this page. */
1072 if ((bytes_used = void_diff(alloc_region->free_pointer,
1073 page_address(next_page)))>GENCGC_CARD_BYTES) {
1074 bytes_used = GENCGC_CARD_BYTES;
1077 page_table[next_page].bytes_used = bytes_used;
1078 byte_cnt += bytes_used;
1083 region_size = void_diff(alloc_region->free_pointer,
1084 alloc_region->start_addr);
1085 bytes_allocated += region_size;
1086 generations[gc_alloc_generation].bytes_allocated += region_size;
1088 gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
1090 /* Set the generations alloc restart page to the last page of
1092 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0, next_page-1);
1094 /* Add the region to the new_areas if requested. */
1095 if (BOXED_PAGE_FLAG & page_type_flag)
1096 add_new_area(first_page,orig_first_page_bytes_used, region_size);
1100 "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1102 gc_alloc_generation));
1105 /* There are no bytes allocated. Unallocate the first_page if
1106 * there are 0 bytes_used. */
1107 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1108 if (page_table[first_page].bytes_used == 0)
1109 page_table[first_page].allocated = FREE_PAGE_FLAG;
1112 /* Unallocate any unused pages. */
1113 while (next_page <= alloc_region->last_page) {
1114 gc_assert(page_table[next_page].bytes_used == 0);
1115 page_table[next_page].allocated = FREE_PAGE_FLAG;
1118 ret = thread_mutex_unlock(&free_pages_lock);
1119 gc_assert(ret == 0);
1121 /* alloc_region is per-thread, we're ok to do this unlocked */
1122 gc_set_region_empty(alloc_region);
1125 static inline void *gc_quick_alloc(long nbytes);
1127 /* Allocate a possibly large object. */
1129 gc_alloc_large(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
1132 page_index_t first_page, next_page, last_page;
1133 page_bytes_t orig_first_page_bytes_used;
1134 os_vm_size_t byte_cnt;
1135 os_vm_size_t bytes_used;
1138 ret = thread_mutex_lock(&free_pages_lock);
1139 gc_assert(ret == 0);
1141 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1);
1142 if (first_page <= alloc_region->last_page) {
1143 first_page = alloc_region->last_page+1;
1146 last_page=gc_find_freeish_pages(&first_page,nbytes, page_type_flag);
1148 gc_assert(first_page > alloc_region->last_page);
1150 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1, last_page);
1152 /* Set up the pages. */
1153 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1155 /* If the first page was free then set up the gen, and
1156 * region_start_offset. */
1157 if (page_table[first_page].bytes_used == 0) {
1158 page_table[first_page].allocated = page_type_flag;
1159 page_table[first_page].gen = gc_alloc_generation;
1160 page_table[first_page].region_start_offset = 0;
1161 page_table[first_page].large_object = 1;
1164 gc_assert(page_table[first_page].allocated == page_type_flag);
1165 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1166 gc_assert(page_table[first_page].large_object == 1);
1170 /* Calc. the number of bytes used in this page. This is not
1171 * always the number of new bytes, unless it was free. */
1173 if ((bytes_used = nbytes+orig_first_page_bytes_used) > GENCGC_CARD_BYTES) {
1174 bytes_used = GENCGC_CARD_BYTES;
1177 page_table[first_page].bytes_used = bytes_used;
1178 byte_cnt += bytes_used;
1180 next_page = first_page+1;
1182 /* All the rest of the pages should be free. We need to set their
1183 * region_start_offset pointer to the start of the region, and set
1184 * the bytes_used. */
1186 gc_assert(page_free_p(next_page));
1187 gc_assert(page_table[next_page].bytes_used == 0);
1188 page_table[next_page].allocated = page_type_flag;
1189 page_table[next_page].gen = gc_alloc_generation;
1190 page_table[next_page].large_object = 1;
1192 page_table[next_page].region_start_offset =
1193 npage_bytes(next_page-first_page) - orig_first_page_bytes_used;
1195 /* Calculate the number of bytes used in this page. */
1197 bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt;
1198 if (bytes_used > GENCGC_CARD_BYTES) {
1199 bytes_used = GENCGC_CARD_BYTES;
1202 page_table[next_page].bytes_used = bytes_used;
1203 page_table[next_page].write_protected=0;
1204 page_table[next_page].dont_move=0;
1205 byte_cnt += bytes_used;
1209 gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
1211 bytes_allocated += nbytes;
1212 generations[gc_alloc_generation].bytes_allocated += nbytes;
1214 /* Add the region to the new_areas if requested. */
1215 if (BOXED_PAGE_FLAG & page_type_flag)
1216 add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1218 /* Bump up last_free_page */
1219 if (last_page+1 > last_free_page) {
1220 last_free_page = last_page+1;
1221 set_alloc_pointer((lispobj)(page_address(last_free_page)));
1223 ret = thread_mutex_unlock(&free_pages_lock);
1224 gc_assert(ret == 0);
1226 #ifdef READ_PROTECT_FREE_PAGES
1227 os_protect(page_address(first_page),
1228 npage_bytes(1+last_page-first_page),
1232 zero_dirty_pages(first_page, last_page);
1234 return page_address(first_page);
1237 static page_index_t gencgc_alloc_start_page = -1;
1240 gc_heap_exhausted_error_or_lose (long available, long requested)
1242 struct thread *thread = arch_os_get_current_thread();
1243 /* Write basic information before doing anything else: if we don't
1244 * call to lisp this is a must, and even if we do there is always
1245 * the danger that we bounce back here before the error has been
1246 * handled, or indeed even printed.
1248 report_heap_exhaustion(available, requested, thread);
1249 if (gc_active_p || (available == 0)) {
1250 /* If we are in GC, or totally out of memory there is no way
1251 * to sanely transfer control to the lisp-side of things.
1253 lose("Heap exhausted, game over.");
1256 /* FIXME: assert free_pages_lock held */
1257 (void)thread_mutex_unlock(&free_pages_lock);
1258 gc_assert(get_pseudo_atomic_atomic(thread));
1259 clear_pseudo_atomic_atomic(thread);
1260 if (get_pseudo_atomic_interrupted(thread))
1261 do_pending_interrupt();
1262 /* Another issue is that signalling HEAP-EXHAUSTED error leads
1263 * to running user code at arbitrary places, even in a
1264 * WITHOUT-INTERRUPTS which may lead to a deadlock without
1265 * running out of the heap. So at this point all bets are
1267 if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
1268 corruption_warning_and_maybe_lose
1269 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1270 funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR),
1271 alloc_number(available), alloc_number(requested));
1272 lose("HEAP-EXHAUSTED-ERROR fell through");
1277 gc_find_freeish_pages(page_index_t *restart_page_ptr, long bytes,
1280 page_index_t most_bytes_found_from = 0, most_bytes_found_to = 0;
1281 page_index_t first_page, last_page, restart_page = *restart_page_ptr;
1282 os_vm_size_t nbytes = bytes;
1283 os_vm_size_t nbytes_goal = nbytes;
1284 os_vm_size_t bytes_found = 0;
1285 os_vm_size_t most_bytes_found = 0;
1286 boolean small_object = nbytes < GENCGC_CARD_BYTES;
1287 /* FIXME: assert(free_pages_lock is held); */
1289 if (nbytes_goal < gencgc_alloc_granularity)
1290 nbytes_goal = gencgc_alloc_granularity;
1292 /* Toggled by gc_and_save for heap compaction, normally -1. */
1293 if (gencgc_alloc_start_page != -1) {
1294 restart_page = gencgc_alloc_start_page;
1297 /* FIXME: This is on bytes instead of nbytes pending cleanup of
1298 * long from the interface. */
1299 gc_assert(bytes>=0);
1300 /* Search for a page with at least nbytes of space. We prefer
1301 * not to split small objects on multiple pages, to reduce the
1302 * number of contiguous allocation regions spaning multiple
1303 * pages: this helps avoid excessive conservativism.
1305 * For other objects, we guarantee that they start on their own
1308 first_page = restart_page;
1309 while (first_page < page_table_pages) {
1311 if (page_free_p(first_page)) {
1312 gc_assert(0 == page_table[first_page].bytes_used);
1313 bytes_found = GENCGC_CARD_BYTES;
1314 } else if (small_object &&
1315 (page_table[first_page].allocated == page_type_flag) &&
1316 (page_table[first_page].large_object == 0) &&
1317 (page_table[first_page].gen == gc_alloc_generation) &&
1318 (page_table[first_page].write_protected == 0) &&
1319 (page_table[first_page].dont_move == 0)) {
1320 bytes_found = GENCGC_CARD_BYTES - page_table[first_page].bytes_used;
1321 if (bytes_found < nbytes) {
1322 if (bytes_found > most_bytes_found)
1323 most_bytes_found = bytes_found;
1332 gc_assert(page_table[first_page].write_protected == 0);
1333 for (last_page = first_page+1;
1334 ((last_page < page_table_pages) &&
1335 page_free_p(last_page) &&
1336 (bytes_found < nbytes_goal));
1338 bytes_found += GENCGC_CARD_BYTES;
1339 gc_assert(0 == page_table[last_page].bytes_used);
1340 gc_assert(0 == page_table[last_page].write_protected);
1343 if (bytes_found > most_bytes_found) {
1344 most_bytes_found = bytes_found;
1345 most_bytes_found_from = first_page;
1346 most_bytes_found_to = last_page;
1348 if (bytes_found >= nbytes_goal)
1351 first_page = last_page;
1354 bytes_found = most_bytes_found;
1355 restart_page = first_page + 1;
1357 /* Check for a failure */
1358 if (bytes_found < nbytes) {
1359 gc_assert(restart_page >= page_table_pages);
1360 gc_heap_exhausted_error_or_lose(most_bytes_found, nbytes);
1363 gc_assert(most_bytes_found_to);
1364 *restart_page_ptr = most_bytes_found_from;
1365 return most_bytes_found_to-1;
1368 /* Allocate bytes. All the rest of the special-purpose allocation
1369 * functions will eventually call this */
1372 gc_alloc_with_region(long nbytes,int page_type_flag, struct alloc_region *my_region,
1375 void *new_free_pointer;
1377 if (nbytes>=large_object_size)
1378 return gc_alloc_large(nbytes, page_type_flag, my_region);
1380 /* Check whether there is room in the current alloc region. */
1381 new_free_pointer = my_region->free_pointer + nbytes;
1383 /* fprintf(stderr, "alloc %d bytes from %p to %p\n", nbytes,
1384 my_region->free_pointer, new_free_pointer); */
1386 if (new_free_pointer <= my_region->end_addr) {
1387 /* If so then allocate from the current alloc region. */
1388 void *new_obj = my_region->free_pointer;
1389 my_region->free_pointer = new_free_pointer;
1391 /* Unless a `quick' alloc was requested, check whether the
1392 alloc region is almost empty. */
1394 void_diff(my_region->end_addr,my_region->free_pointer) <= 32) {
1395 /* If so, finished with the current region. */
1396 gc_alloc_update_page_tables(page_type_flag, my_region);
1397 /* Set up a new region. */
1398 gc_alloc_new_region(32 /*bytes*/, page_type_flag, my_region);
1401 return((void *)new_obj);
1404 /* Else not enough free space in the current region: retry with a
1407 gc_alloc_update_page_tables(page_type_flag, my_region);
1408 gc_alloc_new_region(nbytes, page_type_flag, my_region);
1409 return gc_alloc_with_region(nbytes, page_type_flag, my_region,0);
1412 /* these are only used during GC: all allocation from the mutator calls
1413 * alloc() -> gc_alloc_with_region() with the appropriate per-thread
1416 static inline void *
1417 gc_quick_alloc(long nbytes)
1419 return gc_general_alloc(nbytes, BOXED_PAGE_FLAG, ALLOC_QUICK);
1422 static inline void *
1423 gc_alloc_unboxed(long nbytes)
1425 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, 0);
1428 static inline void *
1429 gc_quick_alloc_unboxed(long nbytes)
1431 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, ALLOC_QUICK);
1434 /* Copy a large object. If the object is in a large object region then
1435 * it is simply promoted, else it is copied. If it's large enough then
1436 * it's copied to a large object region.
1438 * Bignums and vectors may have shrunk. If the object is not copied
1439 * the space needs to be reclaimed, and the page_tables corrected. */
1441 general_copy_large_object(lispobj object, long nwords, boolean boxedp)
1445 page_index_t first_page;
1447 gc_assert(is_lisp_pointer(object));
1448 gc_assert(from_space_p(object));
1449 gc_assert((nwords & 0x01) == 0);
1451 if ((nwords > 1024*1024) && gencgc_verbose) {
1452 FSHOW((stderr, "/general_copy_large_object: %d bytes\n",
1453 nwords*N_WORD_BYTES));
1456 /* Check whether it's a large object. */
1457 first_page = find_page_index((void *)object);
1458 gc_assert(first_page >= 0);
1460 if (page_table[first_page].large_object) {
1461 /* Promote the object. Note: Unboxed objects may have been
1462 * allocated to a BOXED region so it may be necessary to
1463 * change the region to UNBOXED. */
1464 os_vm_size_t remaining_bytes;
1465 os_vm_size_t bytes_freed;
1466 page_index_t next_page;
1467 page_bytes_t old_bytes_used;
1469 /* FIXME: This comment is somewhat stale.
1471 * Note: Any page write-protection must be removed, else a
1472 * later scavenge_newspace may incorrectly not scavenge these
1473 * pages. This would not be necessary if they are added to the
1474 * new areas, but let's do it for them all (they'll probably
1475 * be written anyway?). */
1477 gc_assert(page_table[first_page].region_start_offset == 0);
1478 next_page = first_page;
1479 remaining_bytes = nwords*N_WORD_BYTES;
1481 while (remaining_bytes > GENCGC_CARD_BYTES) {
1482 gc_assert(page_table[next_page].gen == from_space);
1483 gc_assert(page_table[next_page].large_object);
1484 gc_assert(page_table[next_page].region_start_offset ==
1485 npage_bytes(next_page-first_page));
1486 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
1487 /* Should have been unprotected by unprotect_oldspace()
1488 * for boxed objects, and after promotion unboxed ones
1489 * should not be on protected pages at all. */
1490 gc_assert(!page_table[next_page].write_protected);
1493 gc_assert(page_boxed_p(next_page));
1495 gc_assert(page_allocated_no_region_p(next_page));
1496 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1498 page_table[next_page].gen = new_space;
1500 remaining_bytes -= GENCGC_CARD_BYTES;
1504 /* Now only one page remains, but the object may have shrunk so
1505 * there may be more unused pages which will be freed. */
1507 /* Object may have shrunk but shouldn't have grown - check. */
1508 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1510 page_table[next_page].gen = new_space;
1513 gc_assert(page_boxed_p(next_page));
1515 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1517 /* Adjust the bytes_used. */
1518 old_bytes_used = page_table[next_page].bytes_used;
1519 page_table[next_page].bytes_used = remaining_bytes;
1521 bytes_freed = old_bytes_used - remaining_bytes;
1523 /* Free any remaining pages; needs care. */
1525 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
1526 (page_table[next_page].gen == from_space) &&
1527 /* FIXME: It is not obvious to me why this is necessary
1528 * as a loop condition: it seems to me that the
1529 * region_start_offset test should be sufficient, but
1530 * experimentally that is not the case. --NS
1533 page_boxed_p(next_page) :
1534 page_allocated_no_region_p(next_page)) &&
1535 page_table[next_page].large_object &&
1536 (page_table[next_page].region_start_offset ==
1537 npage_bytes(next_page - first_page))) {
1538 /* Checks out OK, free the page. Don't need to both zeroing
1539 * pages as this should have been done before shrinking the
1540 * object. These pages shouldn't be write-protected, even if
1541 * boxed they should be zero filled. */
1542 gc_assert(page_table[next_page].write_protected == 0);
1544 old_bytes_used = page_table[next_page].bytes_used;
1545 page_table[next_page].allocated = FREE_PAGE_FLAG;
1546 page_table[next_page].bytes_used = 0;
1547 bytes_freed += old_bytes_used;
1551 if ((bytes_freed > 0) && gencgc_verbose) {
1553 "/general_copy_large_object bytes_freed=%"OS_VM_SIZE_FMT"\n",
1557 generations[from_space].bytes_allocated -= nwords*N_WORD_BYTES
1559 generations[new_space].bytes_allocated += nwords*N_WORD_BYTES;
1560 bytes_allocated -= bytes_freed;
1562 /* Add the region to the new_areas if requested. */
1564 add_new_area(first_page,0,nwords*N_WORD_BYTES);
1569 /* Get tag of object. */
1570 tag = lowtag_of(object);
1572 /* Allocate space. */
1573 new = gc_general_alloc(nwords*N_WORD_BYTES,
1574 (boxedp ? BOXED_PAGE_FLAG : UNBOXED_PAGE_FLAG),
1577 /* Copy the object. */
1578 memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1580 /* Return Lisp pointer of new object. */
1581 return ((lispobj) new) | tag;
1586 copy_large_object(lispobj object, long nwords)
1588 return general_copy_large_object(object, nwords, 1);
1592 copy_large_unboxed_object(lispobj object, long nwords)
1594 return general_copy_large_object(object, nwords, 0);
1597 /* to copy unboxed objects */
1599 copy_unboxed_object(lispobj object, long nwords)
1601 return gc_general_copy_object(object, nwords, UNBOXED_PAGE_FLAG);
1606 * code and code-related objects
1609 static lispobj trans_fun_header(lispobj object);
1610 static lispobj trans_boxed(lispobj object);
1613 /* Scan a x86 compiled code object, looking for possible fixups that
1614 * have been missed after a move.
1616 * Two types of fixups are needed:
1617 * 1. Absolute fixups to within the code object.
1618 * 2. Relative fixups to outside the code object.
1620 * Currently only absolute fixups to the constant vector, or to the
1621 * code area are checked. */
1623 sniff_code_object(struct code *code, os_vm_size_t displacement)
1625 #ifdef LISP_FEATURE_X86
1626 long nheader_words, ncode_words, nwords;
1627 os_vm_address_t constants_start_addr = NULL, constants_end_addr, p;
1628 os_vm_address_t code_start_addr, code_end_addr;
1629 os_vm_address_t code_addr = (os_vm_address_t)code;
1630 int fixup_found = 0;
1632 if (!check_code_fixups)
1635 FSHOW((stderr, "/sniffing code: %p, %lu\n", code, displacement));
1637 ncode_words = fixnum_value(code->code_size);
1638 nheader_words = HeaderValue(*(lispobj *)code);
1639 nwords = ncode_words + nheader_words;
1641 constants_start_addr = code_addr + 5*N_WORD_BYTES;
1642 constants_end_addr = code_addr + nheader_words*N_WORD_BYTES;
1643 code_start_addr = code_addr + nheader_words*N_WORD_BYTES;
1644 code_end_addr = code_addr + nwords*N_WORD_BYTES;
1646 /* Work through the unboxed code. */
1647 for (p = code_start_addr; p < code_end_addr; p++) {
1648 void *data = *(void **)p;
1649 unsigned d1 = *((unsigned char *)p - 1);
1650 unsigned d2 = *((unsigned char *)p - 2);
1651 unsigned d3 = *((unsigned char *)p - 3);
1652 unsigned d4 = *((unsigned char *)p - 4);
1654 unsigned d5 = *((unsigned char *)p - 5);
1655 unsigned d6 = *((unsigned char *)p - 6);
1658 /* Check for code references. */
1659 /* Check for a 32 bit word that looks like an absolute
1660 reference to within the code adea of the code object. */
1661 if ((data >= (void*)(code_start_addr-displacement))
1662 && (data < (void*)(code_end_addr-displacement))) {
1663 /* function header */
1665 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) ==
1667 /* Skip the function header */
1671 /* the case of PUSH imm32 */
1675 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1676 p, d6, d5, d4, d3, d2, d1, data));
1677 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1679 /* the case of MOV [reg-8],imm32 */
1681 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1682 || d2==0x45 || d2==0x46 || d2==0x47)
1686 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1687 p, d6, d5, d4, d3, d2, d1, data));
1688 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1690 /* the case of LEA reg,[disp32] */
1691 if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1694 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1695 p, d6, d5, d4, d3, d2, d1, data));
1696 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1700 /* Check for constant references. */
1701 /* Check for a 32 bit word that looks like an absolute
1702 reference to within the constant vector. Constant references
1704 if ((data >= (void*)(constants_start_addr-displacement))
1705 && (data < (void*)(constants_end_addr-displacement))
1706 && (((unsigned)data & 0x3) == 0)) {
1711 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1712 p, d6, d5, d4, d3, d2, d1, data));
1713 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1716 /* the case of MOV m32,EAX */
1720 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1721 p, d6, d5, d4, d3, d2, d1, data));
1722 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1725 /* the case of CMP m32,imm32 */
1726 if ((d1 == 0x3d) && (d2 == 0x81)) {
1729 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1730 p, d6, d5, d4, d3, d2, d1, data));
1732 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1735 /* Check for a mod=00, r/m=101 byte. */
1736 if ((d1 & 0xc7) == 5) {
1741 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1742 p, d6, d5, d4, d3, d2, d1, data));
1743 FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1745 /* the case of CMP reg32,m32 */
1749 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1750 p, d6, d5, d4, d3, d2, d1, data));
1751 FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1753 /* the case of MOV m32,reg32 */
1757 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1758 p, d6, d5, d4, d3, d2, d1, data));
1759 FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1761 /* the case of MOV reg32,m32 */
1765 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1766 p, d6, d5, d4, d3, d2, d1, data));
1767 FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1769 /* the case of LEA reg32,m32 */
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, "/LEA reg32,0x%.8x\n", data));
1781 /* If anything was found, print some information on the code
1785 "/compiled code object at %x: header words = %d, code words = %d\n",
1786 code, nheader_words, ncode_words));
1788 "/const start = %x, end = %x\n",
1789 constants_start_addr, constants_end_addr));
1791 "/code start = %x, end = %x\n",
1792 code_start_addr, code_end_addr));
1798 gencgc_apply_code_fixups(struct code *old_code, struct code *new_code)
1800 /* x86-64 uses pc-relative addressing instead of this kludge */
1801 #ifndef LISP_FEATURE_X86_64
1802 long nheader_words, ncode_words, nwords;
1803 os_vm_address_t constants_start_addr, constants_end_addr;
1804 os_vm_address_t code_start_addr, code_end_addr;
1805 os_vm_address_t code_addr = (os_vm_address_t)new_code;
1806 os_vm_address_t old_addr = (os_vm_address_t)old_code;
1807 os_vm_size_t displacement = code_addr - old_addr;
1808 lispobj fixups = NIL;
1809 struct vector *fixups_vector;
1811 ncode_words = fixnum_value(new_code->code_size);
1812 nheader_words = HeaderValue(*(lispobj *)new_code);
1813 nwords = ncode_words + nheader_words;
1815 "/compiled code object at %x: header words = %d, code words = %d\n",
1816 new_code, nheader_words, ncode_words)); */
1817 constants_start_addr = code_addr + 5*N_WORD_BYTES;
1818 constants_end_addr = code_addr + nheader_words*N_WORD_BYTES;
1819 code_start_addr = code_addr + nheader_words*N_WORD_BYTES;
1820 code_end_addr = code_addr + nwords*N_WORD_BYTES;
1823 "/const start = %x, end = %x\n",
1824 constants_start_addr,constants_end_addr));
1826 "/code start = %x; end = %x\n",
1827 code_start_addr,code_end_addr));
1830 /* The first constant should be a pointer to the fixups for this
1831 code objects. Check. */
1832 fixups = new_code->constants[0];
1834 /* It will be 0 or the unbound-marker if there are no fixups (as
1835 * will be the case if the code object has been purified, for
1836 * example) and will be an other pointer if it is valid. */
1837 if ((fixups == 0) || (fixups == UNBOUND_MARKER_WIDETAG) ||
1838 !is_lisp_pointer(fixups)) {
1839 /* Check for possible errors. */
1840 if (check_code_fixups)
1841 sniff_code_object(new_code, displacement);
1846 fixups_vector = (struct vector *)native_pointer(fixups);
1848 /* Could be pointing to a forwarding pointer. */
1849 /* FIXME is this always in from_space? if so, could replace this code with
1850 * forwarding_pointer_p/forwarding_pointer_value */
1851 if (is_lisp_pointer(fixups) &&
1852 (find_page_index((void*)fixups_vector) != -1) &&
1853 (fixups_vector->header == 0x01)) {
1854 /* If so, then follow it. */
1855 /*SHOW("following pointer to a forwarding pointer");*/
1857 (struct vector *)native_pointer((lispobj)fixups_vector->length);
1860 /*SHOW("got fixups");*/
1862 if (widetag_of(fixups_vector->header) == SIMPLE_ARRAY_WORD_WIDETAG) {
1863 /* Got the fixups for the code block. Now work through the vector,
1864 and apply a fixup at each address. */
1865 long length = fixnum_value(fixups_vector->length);
1867 for (i = 0; i < length; i++) {
1868 long offset = fixups_vector->data[i];
1869 /* Now check the current value of offset. */
1870 os_vm_address_t old_value = *(os_vm_address_t *)(code_start_addr + offset);
1872 /* If it's within the old_code object then it must be an
1873 * absolute fixup (relative ones are not saved) */
1874 if ((old_value >= old_addr)
1875 && (old_value < (old_addr + nwords*N_WORD_BYTES)))
1876 /* So add the dispacement. */
1877 *(os_vm_address_t *)(code_start_addr + offset) =
1878 old_value + displacement;
1880 /* It is outside the old code object so it must be a
1881 * relative fixup (absolute fixups are not saved). So
1882 * subtract the displacement. */
1883 *(os_vm_address_t *)(code_start_addr + offset) =
1884 old_value - displacement;
1887 /* This used to just print a note to stderr, but a bogus fixup seems to
1888 * indicate real heap corruption, so a hard hailure is in order. */
1889 lose("fixup vector %p has a bad widetag: %d\n",
1890 fixups_vector, widetag_of(fixups_vector->header));
1893 /* Check for possible errors. */
1894 if (check_code_fixups) {
1895 sniff_code_object(new_code,displacement);
1902 trans_boxed_large(lispobj object)
1905 unsigned long length;
1907 gc_assert(is_lisp_pointer(object));
1909 header = *((lispobj *) native_pointer(object));
1910 length = HeaderValue(header) + 1;
1911 length = CEILING(length, 2);
1913 return copy_large_object(object, length);
1916 /* Doesn't seem to be used, delete it after the grace period. */
1919 trans_unboxed_large(lispobj object)
1922 unsigned long length;
1924 gc_assert(is_lisp_pointer(object));
1926 header = *((lispobj *) native_pointer(object));
1927 length = HeaderValue(header) + 1;
1928 length = CEILING(length, 2);
1930 return copy_large_unboxed_object(object, length);
1938 /* XX This is a hack adapted from cgc.c. These don't work too
1939 * efficiently with the gencgc as a list of the weak pointers is
1940 * maintained within the objects which causes writes to the pages. A
1941 * limited attempt is made to avoid unnecessary writes, but this needs
1943 #define WEAK_POINTER_NWORDS \
1944 CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
1947 scav_weak_pointer(lispobj *where, lispobj object)
1949 /* Since we overwrite the 'next' field, we have to make
1950 * sure not to do so for pointers already in the list.
1951 * Instead of searching the list of weak_pointers each
1952 * time, we ensure that next is always NULL when the weak
1953 * pointer isn't in the list, and not NULL otherwise.
1954 * Since we can't use NULL to denote end of list, we
1955 * use a pointer back to the same weak_pointer.
1957 struct weak_pointer * wp = (struct weak_pointer*)where;
1959 if (NULL == wp->next) {
1960 wp->next = weak_pointers;
1962 if (NULL == wp->next)
1966 /* Do not let GC scavenge the value slot of the weak pointer.
1967 * (That is why it is a weak pointer.) */
1969 return WEAK_POINTER_NWORDS;
1974 search_read_only_space(void *pointer)
1976 lispobj *start = (lispobj *) READ_ONLY_SPACE_START;
1977 lispobj *end = (lispobj *) SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
1978 if ((pointer < (void *)start) || (pointer >= (void *)end))
1980 return (gc_search_space(start,
1981 (((lispobj *)pointer)+2)-start,
1982 (lispobj *) pointer));
1986 search_static_space(void *pointer)
1988 lispobj *start = (lispobj *)STATIC_SPACE_START;
1989 lispobj *end = (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
1990 if ((pointer < (void *)start) || (pointer >= (void *)end))
1992 return (gc_search_space(start,
1993 (((lispobj *)pointer)+2)-start,
1994 (lispobj *) pointer));
1997 /* a faster version for searching the dynamic space. This will work even
1998 * if the object is in a current allocation region. */
2000 search_dynamic_space(void *pointer)
2002 page_index_t page_index = find_page_index(pointer);
2005 /* The address may be invalid, so do some checks. */
2006 if ((page_index == -1) || page_free_p(page_index))
2008 start = (lispobj *)page_region_start(page_index);
2009 return (gc_search_space(start,
2010 (((lispobj *)pointer)+2)-start,
2011 (lispobj *)pointer));
2014 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2016 /* Is there any possibility that pointer is a valid Lisp object
2017 * reference, and/or something else (e.g. subroutine call return
2018 * address) which should prevent us from moving the referred-to thing?
2019 * This is called from preserve_pointers() */
2021 possibly_valid_dynamic_space_pointer(lispobj *pointer)
2023 lispobj *start_addr;
2025 /* Find the object start address. */
2026 if ((start_addr = search_dynamic_space(pointer)) == NULL) {
2030 return looks_like_valid_lisp_pointer_p(pointer, start_addr);
2033 #endif // defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2035 /* Adjust large bignum and vector objects. This will adjust the
2036 * allocated region if the size has shrunk, and move unboxed objects
2037 * into unboxed pages. The pages are not promoted here, and the
2038 * promoted region is not added to the new_regions; this is really
2039 * only designed to be called from preserve_pointer(). Shouldn't fail
2040 * if this is missed, just may delay the moving of objects to unboxed
2041 * pages, and the freeing of pages. */
2043 maybe_adjust_large_object(lispobj *where)
2045 page_index_t first_page;
2046 page_index_t next_page;
2049 unsigned long remaining_bytes;
2050 unsigned long bytes_freed;
2051 unsigned long old_bytes_used;
2055 /* Check whether it's a vector or bignum object. */
2056 switch (widetag_of(where[0])) {
2057 case SIMPLE_VECTOR_WIDETAG:
2058 boxed = BOXED_PAGE_FLAG;
2060 case BIGNUM_WIDETAG:
2061 case SIMPLE_BASE_STRING_WIDETAG:
2062 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2063 case SIMPLE_CHARACTER_STRING_WIDETAG:
2065 case SIMPLE_BIT_VECTOR_WIDETAG:
2066 case SIMPLE_ARRAY_NIL_WIDETAG:
2067 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2068 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2069 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2070 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2071 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2072 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2074 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
2076 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2077 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2078 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2079 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2081 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2082 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2084 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2085 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2087 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2088 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2091 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
2093 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2094 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2096 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2097 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2099 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2100 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2101 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2102 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2104 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2105 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2107 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2108 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2110 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2111 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2113 boxed = UNBOXED_PAGE_FLAG;
2119 /* Find its current size. */
2120 nwords = (sizetab[widetag_of(where[0])])(where);
2122 first_page = find_page_index((void *)where);
2123 gc_assert(first_page >= 0);
2125 /* Note: Any page write-protection must be removed, else a later
2126 * scavenge_newspace may incorrectly not scavenge these pages.
2127 * This would not be necessary if they are added to the new areas,
2128 * but lets do it for them all (they'll probably be written
2131 gc_assert(page_table[first_page].region_start_offset == 0);
2133 next_page = first_page;
2134 remaining_bytes = nwords*N_WORD_BYTES;
2135 while (remaining_bytes > GENCGC_CARD_BYTES) {
2136 gc_assert(page_table[next_page].gen == from_space);
2137 gc_assert(page_allocated_no_region_p(next_page));
2138 gc_assert(page_table[next_page].large_object);
2139 gc_assert(page_table[next_page].region_start_offset ==
2140 npage_bytes(next_page-first_page));
2141 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
2143 page_table[next_page].allocated = boxed;
2145 /* Shouldn't be write-protected at this stage. Essential that the
2147 gc_assert(!page_table[next_page].write_protected);
2148 remaining_bytes -= GENCGC_CARD_BYTES;
2152 /* Now only one page remains, but the object may have shrunk so
2153 * there may be more unused pages which will be freed. */
2155 /* Object may have shrunk but shouldn't have grown - check. */
2156 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2158 page_table[next_page].allocated = boxed;
2159 gc_assert(page_table[next_page].allocated ==
2160 page_table[first_page].allocated);
2162 /* Adjust the bytes_used. */
2163 old_bytes_used = page_table[next_page].bytes_used;
2164 page_table[next_page].bytes_used = remaining_bytes;
2166 bytes_freed = old_bytes_used - remaining_bytes;
2168 /* Free any remaining pages; needs care. */
2170 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
2171 (page_table[next_page].gen == from_space) &&
2172 page_allocated_no_region_p(next_page) &&
2173 page_table[next_page].large_object &&
2174 (page_table[next_page].region_start_offset ==
2175 npage_bytes(next_page - first_page))) {
2176 /* It checks out OK, free the page. We don't need to both zeroing
2177 * pages as this should have been done before shrinking the
2178 * object. These pages shouldn't be write protected as they
2179 * should be zero filled. */
2180 gc_assert(page_table[next_page].write_protected == 0);
2182 old_bytes_used = page_table[next_page].bytes_used;
2183 page_table[next_page].allocated = FREE_PAGE_FLAG;
2184 page_table[next_page].bytes_used = 0;
2185 bytes_freed += old_bytes_used;
2189 if ((bytes_freed > 0) && gencgc_verbose) {
2191 "/maybe_adjust_large_object() freed %d\n",
2195 generations[from_space].bytes_allocated -= bytes_freed;
2196 bytes_allocated -= bytes_freed;
2201 /* Take a possible pointer to a Lisp object and mark its page in the
2202 * page_table so that it will not be relocated during a GC.
2204 * This involves locating the page it points to, then backing up to
2205 * the start of its region, then marking all pages dont_move from there
2206 * up to the first page that's not full or has a different generation
2208 * It is assumed that all the page static flags have been cleared at
2209 * the start of a GC.
2211 * It is also assumed that the current gc_alloc() region has been
2212 * flushed and the tables updated. */
2215 preserve_pointer(void *addr)
2217 page_index_t addr_page_index = find_page_index(addr);
2218 page_index_t first_page;
2220 unsigned int region_allocation;
2222 /* quick check 1: Address is quite likely to have been invalid. */
2223 if ((addr_page_index == -1)
2224 || page_free_p(addr_page_index)
2225 || (page_table[addr_page_index].bytes_used == 0)
2226 || (page_table[addr_page_index].gen != from_space)
2227 /* Skip if already marked dont_move. */
2228 || (page_table[addr_page_index].dont_move != 0))
2230 gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2231 /* (Now that we know that addr_page_index is in range, it's
2232 * safe to index into page_table[] with it.) */
2233 region_allocation = page_table[addr_page_index].allocated;
2235 /* quick check 2: Check the offset within the page.
2238 if (((unsigned long)addr & (GENCGC_CARD_BYTES - 1)) >
2239 page_table[addr_page_index].bytes_used)
2242 /* Filter out anything which can't be a pointer to a Lisp object
2243 * (or, as a special case which also requires dont_move, a return
2244 * address referring to something in a CodeObject). This is
2245 * expensive but important, since it vastly reduces the
2246 * probability that random garbage will be bogusly interpreted as
2247 * a pointer which prevents a page from moving.
2249 * This only needs to happen on x86oids, where this is used for
2250 * conservative roots. Non-x86oid systems only ever call this
2251 * function on known-valid lisp objects. */
2252 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2253 if (!(code_page_p(addr_page_index)
2254 || (is_lisp_pointer((lispobj)addr) &&
2255 possibly_valid_dynamic_space_pointer(addr))))
2259 /* Find the beginning of the region. Note that there may be
2260 * objects in the region preceding the one that we were passed a
2261 * pointer to: if this is the case, we will write-protect all the
2262 * previous objects' pages too. */
2265 /* I think this'd work just as well, but without the assertions.
2266 * -dan 2004.01.01 */
2267 first_page = find_page_index(page_region_start(addr_page_index))
2269 first_page = addr_page_index;
2270 while (page_table[first_page].region_start_offset != 0) {
2272 /* Do some checks. */
2273 gc_assert(page_table[first_page].bytes_used == GENCGC_CARD_BYTES);
2274 gc_assert(page_table[first_page].gen == from_space);
2275 gc_assert(page_table[first_page].allocated == region_allocation);
2279 /* Adjust any large objects before promotion as they won't be
2280 * copied after promotion. */
2281 if (page_table[first_page].large_object) {
2282 maybe_adjust_large_object(page_address(first_page));
2283 /* If a large object has shrunk then addr may now point to a
2284 * free area in which case it's ignored here. Note it gets
2285 * through the valid pointer test above because the tail looks
2287 if (page_free_p(addr_page_index)
2288 || (page_table[addr_page_index].bytes_used == 0)
2289 /* Check the offset within the page. */
2290 || (((unsigned long)addr & (GENCGC_CARD_BYTES - 1))
2291 > page_table[addr_page_index].bytes_used)) {
2293 "weird? ignore ptr 0x%x to freed area of large object\n",
2297 /* It may have moved to unboxed pages. */
2298 region_allocation = page_table[first_page].allocated;
2301 /* Now work forward until the end of this contiguous area is found,
2302 * marking all pages as dont_move. */
2303 for (i = first_page; ;i++) {
2304 gc_assert(page_table[i].allocated == region_allocation);
2306 /* Mark the page static. */
2307 page_table[i].dont_move = 1;
2309 /* Move the page to the new_space. XX I'd rather not do this
2310 * but the GC logic is not quite able to copy with the static
2311 * pages remaining in the from space. This also requires the
2312 * generation bytes_allocated counters be updated. */
2313 page_table[i].gen = new_space;
2314 generations[new_space].bytes_allocated += page_table[i].bytes_used;
2315 generations[from_space].bytes_allocated -= page_table[i].bytes_used;
2317 /* It is essential that the pages are not write protected as
2318 * they may have pointers into the old-space which need
2319 * scavenging. They shouldn't be write protected at this
2321 gc_assert(!page_table[i].write_protected);
2323 /* Check whether this is the last page in this contiguous block.. */
2324 if ((page_table[i].bytes_used < GENCGC_CARD_BYTES)
2325 /* ..or it is CARD_BYTES and is the last in the block */
2327 || (page_table[i+1].bytes_used == 0) /* next page free */
2328 || (page_table[i+1].gen != from_space) /* diff. gen */
2329 || (page_table[i+1].region_start_offset == 0))
2333 /* Check that the page is now static. */
2334 gc_assert(page_table[addr_page_index].dont_move != 0);
2337 /* If the given page is not write-protected, then scan it for pointers
2338 * to younger generations or the top temp. generation, if no
2339 * suspicious pointers are found then the page is write-protected.
2341 * Care is taken to check for pointers to the current gc_alloc()
2342 * region if it is a younger generation or the temp. generation. This
2343 * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2344 * the gc_alloc_generation does not need to be checked as this is only
2345 * called from scavenge_generation() when the gc_alloc generation is
2346 * younger, so it just checks if there is a pointer to the current
2349 * We return 1 if the page was write-protected, else 0. */
2351 update_page_write_prot(page_index_t page)
2353 generation_index_t gen = page_table[page].gen;
2356 void **page_addr = (void **)page_address(page);
2357 long num_words = page_table[page].bytes_used / N_WORD_BYTES;
2359 /* Shouldn't be a free page. */
2360 gc_assert(page_allocated_p(page));
2361 gc_assert(page_table[page].bytes_used != 0);
2363 /* Skip if it's already write-protected, pinned, or unboxed */
2364 if (page_table[page].write_protected
2365 /* FIXME: What's the reason for not write-protecting pinned pages? */
2366 || page_table[page].dont_move
2367 || page_unboxed_p(page))
2370 /* Scan the page for pointers to younger generations or the
2371 * top temp. generation. */
2373 for (j = 0; j < num_words; j++) {
2374 void *ptr = *(page_addr+j);
2375 page_index_t index = find_page_index(ptr);
2377 /* Check that it's in the dynamic space */
2379 if (/* Does it point to a younger or the temp. generation? */
2380 (page_allocated_p(index)
2381 && (page_table[index].bytes_used != 0)
2382 && ((page_table[index].gen < gen)
2383 || (page_table[index].gen == SCRATCH_GENERATION)))
2385 /* Or does it point within a current gc_alloc() region? */
2386 || ((boxed_region.start_addr <= ptr)
2387 && (ptr <= boxed_region.free_pointer))
2388 || ((unboxed_region.start_addr <= ptr)
2389 && (ptr <= unboxed_region.free_pointer))) {
2396 /* Write-protect the page. */
2397 /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2399 os_protect((void *)page_addr,
2401 OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2403 /* Note the page as protected in the page tables. */
2404 page_table[page].write_protected = 1;
2410 /* Scavenge all generations from FROM to TO, inclusive, except for
2411 * new_space which needs special handling, as new objects may be
2412 * added which are not checked here - use scavenge_newspace generation.
2414 * Write-protected pages should not have any pointers to the
2415 * from_space so do need scavenging; thus write-protected pages are
2416 * not always scavenged. There is some code to check that these pages
2417 * are not written; but to check fully the write-protected pages need
2418 * to be scavenged by disabling the code to skip them.
2420 * Under the current scheme when a generation is GCed the younger
2421 * generations will be empty. So, when a generation is being GCed it
2422 * is only necessary to scavenge the older generations for pointers
2423 * not the younger. So a page that does not have pointers to younger
2424 * generations does not need to be scavenged.
2426 * The write-protection can be used to note pages that don't have
2427 * pointers to younger pages. But pages can be written without having
2428 * pointers to younger generations. After the pages are scavenged here
2429 * they can be scanned for pointers to younger generations and if
2430 * there are none the page can be write-protected.
2432 * One complication is when the newspace is the top temp. generation.
2434 * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2435 * that none were written, which they shouldn't be as they should have
2436 * no pointers to younger generations. This breaks down for weak
2437 * pointers as the objects contain a link to the next and are written
2438 * if a weak pointer is scavenged. Still it's a useful check. */
2440 scavenge_generations(generation_index_t from, generation_index_t to)
2443 page_index_t num_wp = 0;
2447 /* Clear the write_protected_cleared flags on all pages. */
2448 for (i = 0; i < page_table_pages; i++)
2449 page_table[i].write_protected_cleared = 0;
2452 for (i = 0; i < last_free_page; i++) {
2453 generation_index_t generation = page_table[i].gen;
2455 && (page_table[i].bytes_used != 0)
2456 && (generation != new_space)
2457 && (generation >= from)
2458 && (generation <= to)) {
2459 page_index_t last_page,j;
2460 int write_protected=1;
2462 /* This should be the start of a region */
2463 gc_assert(page_table[i].region_start_offset == 0);
2465 /* Now work forward until the end of the region */
2466 for (last_page = i; ; last_page++) {
2468 write_protected && page_table[last_page].write_protected;
2469 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
2470 /* Or it is CARD_BYTES and is the last in the block */
2471 || (!page_boxed_p(last_page+1))
2472 || (page_table[last_page+1].bytes_used == 0)
2473 || (page_table[last_page+1].gen != generation)
2474 || (page_table[last_page+1].region_start_offset == 0))
2477 if (!write_protected) {
2478 scavenge(page_address(i),
2479 ((unsigned long)(page_table[last_page].bytes_used
2480 + npage_bytes(last_page-i)))
2483 /* Now scan the pages and write protect those that
2484 * don't have pointers to younger generations. */
2485 if (enable_page_protection) {
2486 for (j = i; j <= last_page; j++) {
2487 num_wp += update_page_write_prot(j);
2490 if ((gencgc_verbose > 1) && (num_wp != 0)) {
2492 "/write protected %d pages within generation %d\n",
2493 num_wp, generation));
2501 /* Check that none of the write_protected pages in this generation
2502 * have been written to. */
2503 for (i = 0; i < page_table_pages; i++) {
2504 if (page_allocated_p(i)
2505 && (page_table[i].bytes_used != 0)
2506 && (page_table[i].gen == generation)
2507 && (page_table[i].write_protected_cleared != 0)) {
2508 FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2510 "/page bytes_used=%d region_start_offset=%lu dont_move=%d\n",
2511 page_table[i].bytes_used,
2512 page_table[i].region_start_offset,
2513 page_table[i].dont_move));
2514 lose("write to protected page %d in scavenge_generation()\n", i);
2521 /* Scavenge a newspace generation. As it is scavenged new objects may
2522 * be allocated to it; these will also need to be scavenged. This
2523 * repeats until there are no more objects unscavenged in the
2524 * newspace generation.
2526 * To help improve the efficiency, areas written are recorded by
2527 * gc_alloc() and only these scavenged. Sometimes a little more will be
2528 * scavenged, but this causes no harm. An easy check is done that the
2529 * scavenged bytes equals the number allocated in the previous
2532 * Write-protected pages are not scanned except if they are marked
2533 * dont_move in which case they may have been promoted and still have
2534 * pointers to the from space.
2536 * Write-protected pages could potentially be written by alloc however
2537 * to avoid having to handle re-scavenging of write-protected pages
2538 * gc_alloc() does not write to write-protected pages.
2540 * New areas of objects allocated are recorded alternatively in the two
2541 * new_areas arrays below. */
2542 static struct new_area new_areas_1[NUM_NEW_AREAS];
2543 static struct new_area new_areas_2[NUM_NEW_AREAS];
2545 /* Do one full scan of the new space generation. This is not enough to
2546 * complete the job as new objects may be added to the generation in
2547 * the process which are not scavenged. */
2549 scavenge_newspace_generation_one_scan(generation_index_t generation)
2554 "/starting one full scan of newspace generation %d\n",
2556 for (i = 0; i < last_free_page; i++) {
2557 /* Note that this skips over open regions when it encounters them. */
2559 && (page_table[i].bytes_used != 0)
2560 && (page_table[i].gen == generation)
2561 && ((page_table[i].write_protected == 0)
2562 /* (This may be redundant as write_protected is now
2563 * cleared before promotion.) */
2564 || (page_table[i].dont_move == 1))) {
2565 page_index_t last_page;
2568 /* The scavenge will start at the region_start_offset of
2571 * We need to find the full extent of this contiguous
2572 * block in case objects span pages.
2574 * Now work forward until the end of this contiguous area
2575 * is found. A small area is preferred as there is a
2576 * better chance of its pages being write-protected. */
2577 for (last_page = i; ;last_page++) {
2578 /* If all pages are write-protected and movable,
2579 * then no need to scavenge */
2580 all_wp=all_wp && page_table[last_page].write_protected &&
2581 !page_table[last_page].dont_move;
2583 /* Check whether this is the last page in this
2584 * contiguous block */
2585 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
2586 /* Or it is CARD_BYTES and is the last in the block */
2587 || (!page_boxed_p(last_page+1))
2588 || (page_table[last_page+1].bytes_used == 0)
2589 || (page_table[last_page+1].gen != generation)
2590 || (page_table[last_page+1].region_start_offset == 0))
2594 /* Do a limited check for write-protected pages. */
2596 long nwords = (((unsigned long)
2597 (page_table[last_page].bytes_used
2598 + npage_bytes(last_page-i)
2599 + page_table[i].region_start_offset))
2601 new_areas_ignore_page = last_page;
2603 scavenge(page_region_start(i), nwords);
2610 "/done with one full scan of newspace generation %d\n",
2614 /* Do a complete scavenge of the newspace generation. */
2616 scavenge_newspace_generation(generation_index_t generation)
2620 /* the new_areas array currently being written to by gc_alloc() */
2621 struct new_area (*current_new_areas)[] = &new_areas_1;
2622 size_t current_new_areas_index;
2624 /* the new_areas created by the previous scavenge cycle */
2625 struct new_area (*previous_new_areas)[] = NULL;
2626 size_t previous_new_areas_index;
2628 /* Flush the current regions updating the tables. */
2629 gc_alloc_update_all_page_tables();
2631 /* Turn on the recording of new areas by gc_alloc(). */
2632 new_areas = current_new_areas;
2633 new_areas_index = 0;
2635 /* Don't need to record new areas that get scavenged anyway during
2636 * scavenge_newspace_generation_one_scan. */
2637 record_new_objects = 1;
2639 /* Start with a full scavenge. */
2640 scavenge_newspace_generation_one_scan(generation);
2642 /* Record all new areas now. */
2643 record_new_objects = 2;
2645 /* Give a chance to weak hash tables to make other objects live.
2646 * FIXME: The algorithm implemented here for weak hash table gcing
2647 * is O(W^2+N) as Bruno Haible warns in
2648 * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
2649 * see "Implementation 2". */
2650 scav_weak_hash_tables();
2652 /* Flush the current regions updating the tables. */
2653 gc_alloc_update_all_page_tables();
2655 /* Grab new_areas_index. */
2656 current_new_areas_index = new_areas_index;
2659 "The first scan is finished; current_new_areas_index=%d.\n",
2660 current_new_areas_index));*/
2662 while (current_new_areas_index > 0) {
2663 /* Move the current to the previous new areas */
2664 previous_new_areas = current_new_areas;
2665 previous_new_areas_index = current_new_areas_index;
2667 /* Scavenge all the areas in previous new areas. Any new areas
2668 * allocated are saved in current_new_areas. */
2670 /* Allocate an array for current_new_areas; alternating between
2671 * new_areas_1 and 2 */
2672 if (previous_new_areas == &new_areas_1)
2673 current_new_areas = &new_areas_2;
2675 current_new_areas = &new_areas_1;
2677 /* Set up for gc_alloc(). */
2678 new_areas = current_new_areas;
2679 new_areas_index = 0;
2681 /* Check whether previous_new_areas had overflowed. */
2682 if (previous_new_areas_index >= NUM_NEW_AREAS) {
2684 /* New areas of objects allocated have been lost so need to do a
2685 * full scan to be sure! If this becomes a problem try
2686 * increasing NUM_NEW_AREAS. */
2687 if (gencgc_verbose) {
2688 SHOW("new_areas overflow, doing full scavenge");
2691 /* Don't need to record new areas that get scavenged
2692 * anyway during scavenge_newspace_generation_one_scan. */
2693 record_new_objects = 1;
2695 scavenge_newspace_generation_one_scan(generation);
2697 /* Record all new areas now. */
2698 record_new_objects = 2;
2700 scav_weak_hash_tables();
2702 /* Flush the current regions updating the tables. */
2703 gc_alloc_update_all_page_tables();
2707 /* Work through previous_new_areas. */
2708 for (i = 0; i < previous_new_areas_index; i++) {
2709 page_index_t page = (*previous_new_areas)[i].page;
2710 size_t offset = (*previous_new_areas)[i].offset;
2711 size_t size = (*previous_new_areas)[i].size / N_WORD_BYTES;
2712 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
2713 scavenge(page_address(page)+offset, size);
2716 scav_weak_hash_tables();
2718 /* Flush the current regions updating the tables. */
2719 gc_alloc_update_all_page_tables();
2722 current_new_areas_index = new_areas_index;
2725 "The re-scan has finished; current_new_areas_index=%d.\n",
2726 current_new_areas_index));*/
2729 /* Turn off recording of areas allocated by gc_alloc(). */
2730 record_new_objects = 0;
2735 /* Check that none of the write_protected pages in this generation
2736 * have been written to. */
2737 for (i = 0; i < page_table_pages; i++) {
2738 if (page_allocated_p(i)
2739 && (page_table[i].bytes_used != 0)
2740 && (page_table[i].gen == generation)
2741 && (page_table[i].write_protected_cleared != 0)
2742 && (page_table[i].dont_move == 0)) {
2743 lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
2744 i, generation, page_table[i].dont_move);
2751 /* Un-write-protect all the pages in from_space. This is done at the
2752 * start of a GC else there may be many page faults while scavenging
2753 * the newspace (I've seen drive the system time to 99%). These pages
2754 * would need to be unprotected anyway before unmapping in
2755 * free_oldspace; not sure what effect this has on paging.. */
2757 unprotect_oldspace(void)
2760 void *region_addr = 0;
2761 void *page_addr = 0;
2762 unsigned long region_bytes = 0;
2764 for (i = 0; i < last_free_page; i++) {
2765 if (page_allocated_p(i)
2766 && (page_table[i].bytes_used != 0)
2767 && (page_table[i].gen == from_space)) {
2769 /* Remove any write-protection. We should be able to rely
2770 * on the write-protect flag to avoid redundant calls. */
2771 if (page_table[i].write_protected) {
2772 page_table[i].write_protected = 0;
2773 page_addr = page_address(i);
2776 region_addr = page_addr;
2777 region_bytes = GENCGC_CARD_BYTES;
2778 } else if (region_addr + region_bytes == page_addr) {
2779 /* Region continue. */
2780 region_bytes += GENCGC_CARD_BYTES;
2782 /* Unprotect previous region. */
2783 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2784 /* First page in new region. */
2785 region_addr = page_addr;
2786 region_bytes = GENCGC_CARD_BYTES;
2792 /* Unprotect last region. */
2793 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2797 /* Work through all the pages and free any in from_space. This
2798 * assumes that all objects have been copied or promoted to an older
2799 * generation. Bytes_allocated and the generation bytes_allocated
2800 * counter are updated. The number of bytes freed is returned. */
2801 static unsigned long
2804 unsigned long bytes_freed = 0;
2805 page_index_t first_page, last_page;
2810 /* Find a first page for the next region of pages. */
2811 while ((first_page < last_free_page)
2812 && (page_free_p(first_page)
2813 || (page_table[first_page].bytes_used == 0)
2814 || (page_table[first_page].gen != from_space)))
2817 if (first_page >= last_free_page)
2820 /* Find the last page of this region. */
2821 last_page = first_page;
2824 /* Free the page. */
2825 bytes_freed += page_table[last_page].bytes_used;
2826 generations[page_table[last_page].gen].bytes_allocated -=
2827 page_table[last_page].bytes_used;
2828 page_table[last_page].allocated = FREE_PAGE_FLAG;
2829 page_table[last_page].bytes_used = 0;
2830 /* Should already be unprotected by unprotect_oldspace(). */
2831 gc_assert(!page_table[last_page].write_protected);
2834 while ((last_page < last_free_page)
2835 && page_allocated_p(last_page)
2836 && (page_table[last_page].bytes_used != 0)
2837 && (page_table[last_page].gen == from_space));
2839 #ifdef READ_PROTECT_FREE_PAGES
2840 os_protect(page_address(first_page),
2841 npage_bytes(last_page-first_page),
2844 first_page = last_page;
2845 } while (first_page < last_free_page);
2847 bytes_allocated -= bytes_freed;
2852 /* Print some information about a pointer at the given address. */
2854 print_ptr(lispobj *addr)
2856 /* If addr is in the dynamic space then out the page information. */
2857 page_index_t pi1 = find_page_index((void*)addr);
2860 fprintf(stderr," %p: page %d alloc %d gen %d bytes_used %d offset %lu dont_move %d\n",
2863 page_table[pi1].allocated,
2864 page_table[pi1].gen,
2865 page_table[pi1].bytes_used,
2866 page_table[pi1].region_start_offset,
2867 page_table[pi1].dont_move);
2868 fprintf(stderr," %x %x %x %x (%x) %x %x %x %x\n",
2882 is_in_stack_space(lispobj ptr)
2884 /* For space verification: Pointers can be valid if they point
2885 * to a thread stack space. This would be faster if the thread
2886 * structures had page-table entries as if they were part of
2887 * the heap space. */
2889 for_each_thread(th) {
2890 if ((th->control_stack_start <= (lispobj *)ptr) &&
2891 (th->control_stack_end >= (lispobj *)ptr)) {
2899 verify_space(lispobj *start, size_t words)
2901 int is_in_dynamic_space = (find_page_index((void*)start) != -1);
2902 int is_in_readonly_space =
2903 (READ_ONLY_SPACE_START <= (unsigned long)start &&
2904 (unsigned long)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
2908 lispobj thing = *(lispobj*)start;
2910 if (is_lisp_pointer(thing)) {
2911 page_index_t page_index = find_page_index((void*)thing);
2912 long to_readonly_space =
2913 (READ_ONLY_SPACE_START <= thing &&
2914 thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
2915 long to_static_space =
2916 (STATIC_SPACE_START <= thing &&
2917 thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
2919 /* Does it point to the dynamic space? */
2920 if (page_index != -1) {
2921 /* If it's within the dynamic space it should point to a used
2922 * page. XX Could check the offset too. */
2923 if (page_allocated_p(page_index)
2924 && (page_table[page_index].bytes_used == 0))
2925 lose ("Ptr %p @ %p sees free page.\n", thing, start);
2926 /* Check that it doesn't point to a forwarding pointer! */
2927 if (*((lispobj *)native_pointer(thing)) == 0x01) {
2928 lose("Ptr %p @ %p sees forwarding ptr.\n", thing, start);
2930 /* Check that its not in the RO space as it would then be a
2931 * pointer from the RO to the dynamic space. */
2932 if (is_in_readonly_space) {
2933 lose("ptr to dynamic space %p from RO space %x\n",
2936 /* Does it point to a plausible object? This check slows
2937 * it down a lot (so it's commented out).
2939 * "a lot" is serious: it ate 50 minutes cpu time on
2940 * my duron 950 before I came back from lunch and
2943 * FIXME: Add a variable to enable this
2946 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
2947 lose("ptr %p to invalid object %p\n", thing, start);
2951 extern void funcallable_instance_tramp;
2952 /* Verify that it points to another valid space. */
2953 if (!to_readonly_space && !to_static_space
2954 && (thing != (lispobj)&funcallable_instance_tramp)
2955 && !is_in_stack_space(thing)) {
2956 lose("Ptr %p @ %p sees junk.\n", thing, start);
2960 if (!(fixnump(thing))) {
2962 switch(widetag_of(*start)) {
2965 case SIMPLE_VECTOR_WIDETAG:
2967 case COMPLEX_WIDETAG:
2968 case SIMPLE_ARRAY_WIDETAG:
2969 case COMPLEX_BASE_STRING_WIDETAG:
2970 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
2971 case COMPLEX_CHARACTER_STRING_WIDETAG:
2973 case COMPLEX_VECTOR_NIL_WIDETAG:
2974 case COMPLEX_BIT_VECTOR_WIDETAG:
2975 case COMPLEX_VECTOR_WIDETAG:
2976 case COMPLEX_ARRAY_WIDETAG:
2977 case CLOSURE_HEADER_WIDETAG:
2978 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2979 case VALUE_CELL_HEADER_WIDETAG:
2980 case SYMBOL_HEADER_WIDETAG:
2981 case CHARACTER_WIDETAG:
2982 #if N_WORD_BITS == 64
2983 case SINGLE_FLOAT_WIDETAG:
2985 case UNBOUND_MARKER_WIDETAG:
2990 case INSTANCE_HEADER_WIDETAG:
2993 long ntotal = HeaderValue(thing);
2994 lispobj layout = ((struct instance *)start)->slots[0];
2999 nuntagged = ((struct layout *)
3000 native_pointer(layout))->n_untagged_slots;
3001 verify_space(start + 1,
3002 ntotal - fixnum_value(nuntagged));
3006 case CODE_HEADER_WIDETAG:
3008 lispobj object = *start;
3010 long nheader_words, ncode_words, nwords;
3012 struct simple_fun *fheaderp;
3014 code = (struct code *) start;
3016 /* Check that it's not in the dynamic space.
3017 * FIXME: Isn't is supposed to be OK for code
3018 * objects to be in the dynamic space these days? */
3019 if (is_in_dynamic_space
3020 /* It's ok if it's byte compiled code. The trace
3021 * table offset will be a fixnum if it's x86
3022 * compiled code - check.
3024 * FIXME: #^#@@! lack of abstraction here..
3025 * This line can probably go away now that
3026 * there's no byte compiler, but I've got
3027 * too much to worry about right now to try
3028 * to make sure. -- WHN 2001-10-06 */
3029 && fixnump(code->trace_table_offset)
3030 /* Only when enabled */
3031 && verify_dynamic_code_check) {
3033 "/code object at %p in the dynamic space\n",
3037 ncode_words = fixnum_value(code->code_size);
3038 nheader_words = HeaderValue(object);
3039 nwords = ncode_words + nheader_words;
3040 nwords = CEILING(nwords, 2);
3041 /* Scavenge the boxed section of the code data block */
3042 verify_space(start + 1, nheader_words - 1);
3044 /* Scavenge the boxed section of each function
3045 * object in the code data block. */
3046 fheaderl = code->entry_points;
3047 while (fheaderl != NIL) {
3049 (struct simple_fun *) native_pointer(fheaderl);
3050 gc_assert(widetag_of(fheaderp->header) ==
3051 SIMPLE_FUN_HEADER_WIDETAG);
3052 verify_space(&fheaderp->name, 1);
3053 verify_space(&fheaderp->arglist, 1);
3054 verify_space(&fheaderp->type, 1);
3055 fheaderl = fheaderp->next;
3061 /* unboxed objects */
3062 case BIGNUM_WIDETAG:
3063 #if N_WORD_BITS != 64
3064 case SINGLE_FLOAT_WIDETAG:
3066 case DOUBLE_FLOAT_WIDETAG:
3067 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3068 case LONG_FLOAT_WIDETAG:
3070 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3071 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3073 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3074 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3076 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3077 case COMPLEX_LONG_FLOAT_WIDETAG:
3079 case SIMPLE_BASE_STRING_WIDETAG:
3080 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3081 case SIMPLE_CHARACTER_STRING_WIDETAG:
3083 case SIMPLE_BIT_VECTOR_WIDETAG:
3084 case SIMPLE_ARRAY_NIL_WIDETAG:
3085 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3086 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3087 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3088 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3089 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3090 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3092 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
3094 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3095 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3096 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3097 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3099 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3100 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3102 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3103 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3105 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3106 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3109 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
3111 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3112 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3114 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3115 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3117 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3118 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3119 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3120 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3122 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3123 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3125 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3126 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3128 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3129 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3132 case WEAK_POINTER_WIDETAG:
3133 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3134 case NO_TLS_VALUE_MARKER_WIDETAG:
3136 count = (sizetab[widetag_of(*start)])(start);
3140 lose("Unhandled widetag %p at %p\n",
3141 widetag_of(*start), start);
3153 /* FIXME: It would be nice to make names consistent so that
3154 * foo_size meant size *in* *bytes* instead of size in some
3155 * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3156 * Some counts of lispobjs are called foo_count; it might be good
3157 * to grep for all foo_size and rename the appropriate ones to
3159 long read_only_space_size =
3160 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3161 - (lispobj*)READ_ONLY_SPACE_START;
3162 long static_space_size =
3163 (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3164 - (lispobj*)STATIC_SPACE_START;
3166 for_each_thread(th) {
3167 long binding_stack_size =
3168 (lispobj*)get_binding_stack_pointer(th)
3169 - (lispobj*)th->binding_stack_start;
3170 verify_space(th->binding_stack_start, binding_stack_size);
3172 verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3173 verify_space((lispobj*)STATIC_SPACE_START , static_space_size);
3177 verify_generation(generation_index_t generation)
3181 for (i = 0; i < last_free_page; i++) {
3182 if (page_allocated_p(i)
3183 && (page_table[i].bytes_used != 0)
3184 && (page_table[i].gen == generation)) {
3185 page_index_t last_page;
3186 int region_allocation = page_table[i].allocated;
3188 /* This should be the start of a contiguous block */
3189 gc_assert(page_table[i].region_start_offset == 0);
3191 /* Need to find the full extent of this contiguous block in case
3192 objects span pages. */
3194 /* Now work forward until the end of this contiguous area is
3196 for (last_page = i; ;last_page++)
3197 /* Check whether this is the last page in this contiguous
3199 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
3200 /* Or it is CARD_BYTES and is the last in the block */
3201 || (page_table[last_page+1].allocated != region_allocation)
3202 || (page_table[last_page+1].bytes_used == 0)
3203 || (page_table[last_page+1].gen != generation)
3204 || (page_table[last_page+1].region_start_offset == 0))
3207 verify_space(page_address(i),
3209 (page_table[last_page].bytes_used
3210 + npage_bytes(last_page-i)))
3217 /* Check that all the free space is zero filled. */
3219 verify_zero_fill(void)
3223 for (page = 0; page < last_free_page; page++) {
3224 if (page_free_p(page)) {
3225 /* The whole page should be zero filled. */
3226 long *start_addr = (long *)page_address(page);
3229 for (i = 0; i < size; i++) {
3230 if (start_addr[i] != 0) {
3231 lose("free page not zero at %x\n", start_addr + i);
3235 long free_bytes = GENCGC_CARD_BYTES - page_table[page].bytes_used;
3236 if (free_bytes > 0) {
3237 long *start_addr = (long *)((unsigned long)page_address(page)
3238 + page_table[page].bytes_used);
3239 long size = free_bytes / N_WORD_BYTES;
3241 for (i = 0; i < size; i++) {
3242 if (start_addr[i] != 0) {
3243 lose("free region not zero at %x\n", start_addr + i);
3251 /* External entry point for verify_zero_fill */
3253 gencgc_verify_zero_fill(void)
3255 /* Flush the alloc regions updating the tables. */
3256 gc_alloc_update_all_page_tables();
3257 SHOW("verifying zero fill");
3262 verify_dynamic_space(void)
3264 generation_index_t i;
3266 for (i = 0; i <= HIGHEST_NORMAL_GENERATION; i++)
3267 verify_generation(i);
3269 if (gencgc_enable_verify_zero_fill)
3273 /* Write-protect all the dynamic boxed pages in the given generation. */
3275 write_protect_generation_pages(generation_index_t generation)
3279 gc_assert(generation < SCRATCH_GENERATION);
3281 for (start = 0; start < last_free_page; start++) {
3282 if (protect_page_p(start, generation)) {
3286 /* Note the page as protected in the page tables. */
3287 page_table[start].write_protected = 1;
3289 for (last = start + 1; last < last_free_page; last++) {
3290 if (!protect_page_p(last, generation))
3292 page_table[last].write_protected = 1;
3295 page_start = (void *)page_address(start);
3297 os_protect(page_start,
3298 npage_bytes(last - start),
3299 OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3305 if (gencgc_verbose > 1) {
3307 "/write protected %d of %d pages in generation %d\n",
3308 count_write_protect_generation_pages(generation),
3309 count_generation_pages(generation),
3314 #if defined(LISP_FEATURE_SB_THREAD) && (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
3316 preserve_context_registers (os_context_t *c)
3319 /* On Darwin the signal context isn't a contiguous block of memory,
3320 * so just preserve_pointering its contents won't be sufficient.
3322 #if defined(LISP_FEATURE_DARWIN)
3323 #if defined LISP_FEATURE_X86
3324 preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3325 preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3326 preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3327 preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3328 preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3329 preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3330 preserve_pointer((void*)*os_context_pc_addr(c));
3331 #elif defined LISP_FEATURE_X86_64
3332 preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3333 preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3334 preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3335 preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3336 preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3337 preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3338 preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3339 preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3340 preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3341 preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3342 preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3343 preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3344 preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3345 preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3346 preserve_pointer((void*)*os_context_pc_addr(c));
3348 #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3351 for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3352 preserve_pointer(*ptr);
3357 /* Garbage collect a generation. If raise is 0 then the remains of the
3358 * generation are not raised to the next generation. */
3360 garbage_collect_generation(generation_index_t generation, int raise)
3362 unsigned long bytes_freed;
3364 unsigned long static_space_size;
3367 gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3369 /* The oldest generation can't be raised. */
3370 gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
3372 /* Check if weak hash tables were processed in the previous GC. */
3373 gc_assert(weak_hash_tables == NULL);
3375 /* Initialize the weak pointer list. */
3376 weak_pointers = NULL;
3378 /* When a generation is not being raised it is transported to a
3379 * temporary generation (NUM_GENERATIONS), and lowered when
3380 * done. Set up this new generation. There should be no pages
3381 * allocated to it yet. */
3383 gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
3386 /* Set the global src and dest. generations */
3387 from_space = generation;
3389 new_space = generation+1;
3391 new_space = SCRATCH_GENERATION;
3393 /* Change to a new space for allocation, resetting the alloc_start_page */
3394 gc_alloc_generation = new_space;
3395 generations[new_space].alloc_start_page = 0;
3396 generations[new_space].alloc_unboxed_start_page = 0;
3397 generations[new_space].alloc_large_start_page = 0;
3398 generations[new_space].alloc_large_unboxed_start_page = 0;
3400 /* Before any pointers are preserved, the dont_move flags on the
3401 * pages need to be cleared. */
3402 for (i = 0; i < last_free_page; i++)
3403 if(page_table[i].gen==from_space)
3404 page_table[i].dont_move = 0;
3406 /* Un-write-protect the old-space pages. This is essential for the
3407 * promoted pages as they may contain pointers into the old-space
3408 * which need to be scavenged. It also helps avoid unnecessary page
3409 * faults as forwarding pointers are written into them. They need to
3410 * be un-protected anyway before unmapping later. */
3411 unprotect_oldspace();
3413 /* Scavenge the stacks' conservative roots. */
3415 /* there are potentially two stacks for each thread: the main
3416 * stack, which may contain Lisp pointers, and the alternate stack.
3417 * We don't ever run Lisp code on the altstack, but it may
3418 * host a sigcontext with lisp objects in it */
3420 /* what we need to do: (1) find the stack pointer for the main
3421 * stack; scavenge it (2) find the interrupt context on the
3422 * alternate stack that might contain lisp values, and scavenge
3425 /* we assume that none of the preceding applies to the thread that
3426 * initiates GC. If you ever call GC from inside an altstack
3427 * handler, you will lose. */
3429 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3430 /* And if we're saving a core, there's no point in being conservative. */
3431 if (conservative_stack) {
3432 for_each_thread(th) {
3434 void **esp=(void **)-1;
3435 if (th->state == STATE_DEAD)
3437 # if defined(LISP_FEATURE_SB_SAFEPOINT)
3438 /* Conservative collect_garbage is always invoked with a
3439 * foreign C call or an interrupt handler on top of every
3440 * existing thread, so the stored SP in each thread
3441 * structure is valid, no matter which thread we are looking
3442 * at. For threads that were running Lisp code, the pitstop
3443 * and edge functions maintain this value within the
3444 * interrupt or exception handler. */
3445 esp = os_get_csp(th);
3446 assert_on_stack(th, esp);
3448 /* In addition to pointers on the stack, also preserve the
3449 * return PC, the only value from the context that we need
3450 * in addition to the SP. The return PC gets saved by the
3451 * foreign call wrapper, and removed from the control stack
3452 * into a register. */
3453 preserve_pointer(th->pc_around_foreign_call);
3455 /* And on platforms with interrupts: scavenge ctx registers. */
3457 /* Disabled on Windows, because it does not have an explicit
3458 * stack of `interrupt_contexts'. The reported CSP has been
3459 * chosen so that the current context on the stack is
3460 * covered by the stack scan. See also set_csp_from_context(). */
3461 # ifndef LISP_FEATURE_WIN32
3462 if (th != arch_os_get_current_thread()) {
3463 long k = fixnum_value(
3464 SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3466 preserve_context_registers(th->interrupt_contexts[--k]);
3469 # elif defined(LISP_FEATURE_SB_THREAD)
3471 if(th==arch_os_get_current_thread()) {
3472 /* Somebody is going to burn in hell for this, but casting
3473 * it in two steps shuts gcc up about strict aliasing. */
3474 esp = (void **)((void *)&raise);
3477 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3478 for(i=free-1;i>=0;i--) {
3479 os_context_t *c=th->interrupt_contexts[i];
3480 esp1 = (void **) *os_context_register_addr(c,reg_SP);
3481 if (esp1>=(void **)th->control_stack_start &&
3482 esp1<(void **)th->control_stack_end) {
3483 if(esp1<esp) esp=esp1;
3484 preserve_context_registers(c);
3489 esp = (void **)((void *)&raise);
3491 if (!esp || esp == (void*) -1)
3492 lose("garbage_collect: no SP known for thread %x (OS %x)",
3494 for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp; ptr--) {
3495 preserve_pointer(*ptr);
3500 /* Non-x86oid systems don't have "conservative roots" as such, but
3501 * the same mechanism is used for objects pinned for use by alien
3503 for_each_thread(th) {
3504 lispobj pin_list = SymbolTlValue(PINNED_OBJECTS,th);
3505 while (pin_list != NIL) {
3506 struct cons *list_entry =
3507 (struct cons *)native_pointer(pin_list);
3508 preserve_pointer(list_entry->car);
3509 pin_list = list_entry->cdr;
3515 if (gencgc_verbose > 1) {
3516 long num_dont_move_pages = count_dont_move_pages();
3518 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3519 num_dont_move_pages,
3520 npage_bytes(num_dont_move_pages));
3524 /* Scavenge all the rest of the roots. */
3526 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3528 * If not x86, we need to scavenge the interrupt context(s) and the
3533 for_each_thread(th) {
3534 scavenge_interrupt_contexts(th);
3535 scavenge_control_stack(th);
3538 /* Scrub the unscavenged control stack space, so that we can't run
3539 * into any stale pointers in a later GC (this is done by the
3540 * stop-for-gc handler in the other threads). */
3541 scrub_control_stack();
3545 /* Scavenge the Lisp functions of the interrupt handlers, taking
3546 * care to avoid SIG_DFL and SIG_IGN. */
3547 for (i = 0; i < NSIG; i++) {
3548 union interrupt_handler handler = interrupt_handlers[i];
3549 if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3550 !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3551 scavenge((lispobj *)(interrupt_handlers + i), 1);
3554 /* Scavenge the binding stacks. */
3557 for_each_thread(th) {
3558 long len= (lispobj *)get_binding_stack_pointer(th) -
3559 th->binding_stack_start;
3560 scavenge((lispobj *) th->binding_stack_start,len);
3561 #ifdef LISP_FEATURE_SB_THREAD
3562 /* do the tls as well */
3563 len=(SymbolValue(FREE_TLS_INDEX,0) >> WORD_SHIFT) -
3564 (sizeof (struct thread))/(sizeof (lispobj));
3565 scavenge((lispobj *) (th+1),len);
3570 /* The original CMU CL code had scavenge-read-only-space code
3571 * controlled by the Lisp-level variable
3572 * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3573 * wasn't documented under what circumstances it was useful or
3574 * safe to turn it on, so it's been turned off in SBCL. If you
3575 * want/need this functionality, and can test and document it,
3576 * please submit a patch. */
3578 if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3579 unsigned long read_only_space_size =
3580 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3581 (lispobj*)READ_ONLY_SPACE_START;
3583 "/scavenge read only space: %d bytes\n",
3584 read_only_space_size * sizeof(lispobj)));
3585 scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3589 /* Scavenge static space. */
3591 (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3592 (lispobj *)STATIC_SPACE_START;
3593 if (gencgc_verbose > 1) {
3595 "/scavenge static space: %d bytes\n",
3596 static_space_size * sizeof(lispobj)));
3598 scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3600 /* All generations but the generation being GCed need to be
3601 * scavenged. The new_space generation needs special handling as
3602 * objects may be moved in - it is handled separately below. */
3603 scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
3605 /* Finally scavenge the new_space generation. Keep going until no
3606 * more objects are moved into the new generation */
3607 scavenge_newspace_generation(new_space);
3609 /* FIXME: I tried reenabling this check when debugging unrelated
3610 * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3611 * Since the current GC code seems to work well, I'm guessing that
3612 * this debugging code is just stale, but I haven't tried to
3613 * figure it out. It should be figured out and then either made to
3614 * work or just deleted. */
3615 #define RESCAN_CHECK 0
3617 /* As a check re-scavenge the newspace once; no new objects should
3620 os_vm_size_t old_bytes_allocated = bytes_allocated;
3621 os_vm_size_t bytes_allocated;
3623 /* Start with a full scavenge. */
3624 scavenge_newspace_generation_one_scan(new_space);
3626 /* Flush the current regions, updating the tables. */
3627 gc_alloc_update_all_page_tables();
3629 bytes_allocated = bytes_allocated - old_bytes_allocated;
3631 if (bytes_allocated != 0) {
3632 lose("Rescan of new_space allocated %d more bytes.\n",
3638 scan_weak_hash_tables();
3639 scan_weak_pointers();
3641 /* Flush the current regions, updating the tables. */
3642 gc_alloc_update_all_page_tables();
3644 /* Free the pages in oldspace, but not those marked dont_move. */
3645 bytes_freed = free_oldspace();
3647 /* If the GC is not raising the age then lower the generation back
3648 * to its normal generation number */
3650 for (i = 0; i < last_free_page; i++)
3651 if ((page_table[i].bytes_used != 0)
3652 && (page_table[i].gen == SCRATCH_GENERATION))
3653 page_table[i].gen = generation;
3654 gc_assert(generations[generation].bytes_allocated == 0);
3655 generations[generation].bytes_allocated =
3656 generations[SCRATCH_GENERATION].bytes_allocated;
3657 generations[SCRATCH_GENERATION].bytes_allocated = 0;
3660 /* Reset the alloc_start_page for generation. */
3661 generations[generation].alloc_start_page = 0;
3662 generations[generation].alloc_unboxed_start_page = 0;
3663 generations[generation].alloc_large_start_page = 0;
3664 generations[generation].alloc_large_unboxed_start_page = 0;
3666 if (generation >= verify_gens) {
3667 if (gencgc_verbose) {
3671 verify_dynamic_space();
3674 /* Set the new gc trigger for the GCed generation. */
3675 generations[generation].gc_trigger =
3676 generations[generation].bytes_allocated
3677 + generations[generation].bytes_consed_between_gc;
3680 generations[generation].num_gc = 0;
3682 ++generations[generation].num_gc;
3686 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3688 update_dynamic_space_free_pointer(void)
3690 page_index_t last_page = -1, i;
3692 for (i = 0; i < last_free_page; i++)
3693 if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
3696 last_free_page = last_page+1;
3698 set_alloc_pointer((lispobj)(page_address(last_free_page)));
3699 return 0; /* dummy value: return something ... */
3703 remap_page_range (page_index_t from, page_index_t to)
3705 /* There's a mysterious Solaris/x86 problem with using mmap
3706 * tricks for memory zeroing. See sbcl-devel thread
3707 * "Re: patch: standalone executable redux".
3709 #if defined(LISP_FEATURE_SUNOS)
3710 zero_and_mark_pages(from, to);
3713 release_granularity = gencgc_release_granularity/GENCGC_CARD_BYTES,
3714 release_mask = release_granularity-1,
3716 aligned_from = (from+release_mask)&~release_mask,
3717 aligned_end = (end&~release_mask);
3719 if (aligned_from < aligned_end) {
3720 zero_pages_with_mmap(aligned_from, aligned_end-1);
3721 if (aligned_from != from)
3722 zero_and_mark_pages(from, aligned_from-1);
3723 if (aligned_end != end)
3724 zero_and_mark_pages(aligned_end, end-1);
3726 zero_and_mark_pages(from, to);
3732 remap_free_pages (page_index_t from, page_index_t to, int forcibly)
3734 page_index_t first_page, last_page;
3737 return remap_page_range(from, to);
3739 for (first_page = from; first_page <= to; first_page++) {
3740 if (page_allocated_p(first_page) ||
3741 (page_table[first_page].need_to_zero == 0))
3744 last_page = first_page + 1;
3745 while (page_free_p(last_page) &&
3746 (last_page <= to) &&
3747 (page_table[last_page].need_to_zero == 1))
3750 remap_page_range(first_page, last_page-1);
3752 first_page = last_page;
3756 generation_index_t small_generation_limit = 1;
3758 /* GC all generations newer than last_gen, raising the objects in each
3759 * to the next older generation - we finish when all generations below
3760 * last_gen are empty. Then if last_gen is due for a GC, or if
3761 * last_gen==NUM_GENERATIONS (the scratch generation? eh?) we GC that
3762 * too. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3764 * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3765 * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3767 collect_garbage(generation_index_t last_gen)
3769 generation_index_t gen = 0, i;
3770 int raise, more = 0;
3772 /* The largest value of last_free_page seen since the time
3773 * remap_free_pages was called. */
3774 static page_index_t high_water_mark = 0;
3776 FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
3777 log_generation_stats(gc_logfile, "=== GC Start ===");
3781 if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
3783 "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3788 /* Flush the alloc regions updating the tables. */
3789 gc_alloc_update_all_page_tables();
3791 /* Verify the new objects created by Lisp code. */
3792 if (pre_verify_gen_0) {
3793 FSHOW((stderr, "pre-checking generation 0\n"));
3794 verify_generation(0);
3797 if (gencgc_verbose > 1)
3798 print_generation_stats();
3801 /* Collect the generation. */
3803 if (more || (gen >= gencgc_oldest_gen_to_gc)) {
3804 /* Never raise the oldest generation. Never raise the extra generation
3805 * collected due to more-flag. */
3811 || (generations[gen].num_gc >= generations[gen].number_of_gcs_before_promotion);
3812 /* If we would not normally raise this one, but we're
3813 * running low on space in comparison to the object-sizes
3814 * we've been seeing, raise it and collect the next one
3816 if (!raise && gen == last_gen) {
3817 more = (2*large_allocation) >= (dynamic_space_size - bytes_allocated);
3822 if (gencgc_verbose > 1) {
3824 "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3827 generations[gen].bytes_allocated,
3828 generations[gen].gc_trigger,
3829 generations[gen].num_gc));
3832 /* If an older generation is being filled, then update its
3835 generations[gen+1].cum_sum_bytes_allocated +=
3836 generations[gen+1].bytes_allocated;
3839 garbage_collect_generation(gen, raise);
3841 /* Reset the memory age cum_sum. */
3842 generations[gen].cum_sum_bytes_allocated = 0;
3844 if (gencgc_verbose > 1) {
3845 FSHOW((stderr, "GC of generation %d finished:\n", gen));
3846 print_generation_stats();
3850 } while ((gen <= gencgc_oldest_gen_to_gc)
3851 && ((gen < last_gen)
3854 && (generations[gen].bytes_allocated
3855 > generations[gen].gc_trigger)
3856 && (generation_average_age(gen)
3857 > generations[gen].minimum_age_before_gc))));
3859 /* Now if gen-1 was raised all generations before gen are empty.
3860 * If it wasn't raised then all generations before gen-1 are empty.
3862 * Now objects within this gen's pages cannot point to younger
3863 * generations unless they are written to. This can be exploited
3864 * by write-protecting the pages of gen; then when younger
3865 * generations are GCed only the pages which have been written
3870 gen_to_wp = gen - 1;
3872 /* There's not much point in WPing pages in generation 0 as it is
3873 * never scavenged (except promoted pages). */
3874 if ((gen_to_wp > 0) && enable_page_protection) {
3875 /* Check that they are all empty. */
3876 for (i = 0; i < gen_to_wp; i++) {
3877 if (generations[i].bytes_allocated)
3878 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
3881 write_protect_generation_pages(gen_to_wp);
3884 /* Set gc_alloc() back to generation 0. The current regions should
3885 * be flushed after the above GCs. */
3886 gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
3887 gc_alloc_generation = 0;
3889 /* Save the high-water mark before updating last_free_page */
3890 if (last_free_page > high_water_mark)
3891 high_water_mark = last_free_page;
3893 update_dynamic_space_free_pointer();
3895 /* Update auto_gc_trigger. Make sure we trigger the next GC before
3896 * running out of heap! */
3897 if (bytes_consed_between_gcs <= (dynamic_space_size - bytes_allocated))
3898 auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
3900 auto_gc_trigger = bytes_allocated + (dynamic_space_size - bytes_allocated)/2;
3903 fprintf(stderr,"Next gc when %"OS_VM_SIZE_FMT" bytes have been consed\n",
3906 /* If we did a big GC (arbitrarily defined as gen > 1), release memory
3909 if (gen > small_generation_limit) {
3910 if (last_free_page > high_water_mark)
3911 high_water_mark = last_free_page;
3912 remap_free_pages(0, high_water_mark, 0);
3913 high_water_mark = 0;
3917 large_allocation = 0;
3919 log_generation_stats(gc_logfile, "=== GC End ===");
3920 SHOW("returning from collect_garbage");
3923 /* This is called by Lisp PURIFY when it is finished. All live objects
3924 * will have been moved to the RO and Static heaps. The dynamic space
3925 * will need a full re-initialization. We don't bother having Lisp
3926 * PURIFY flush the current gc_alloc() region, as the page_tables are
3927 * re-initialized, and every page is zeroed to be sure. */
3931 page_index_t page, last_page;
3933 if (gencgc_verbose > 1) {
3934 SHOW("entering gc_free_heap");
3937 for (page = 0; page < page_table_pages; page++) {
3938 /* Skip free pages which should already be zero filled. */
3939 if (page_allocated_p(page)) {
3941 for (last_page = page;
3942 (last_page < page_table_pages) && page_allocated_p(last_page);
3944 /* Mark the page free. The other slots are assumed invalid
3945 * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
3946 * should not be write-protected -- except that the
3947 * generation is used for the current region but it sets
3949 page_table[page].allocated = FREE_PAGE_FLAG;
3950 page_table[page].bytes_used = 0;
3951 page_table[page].write_protected = 0;
3954 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
3955 * about this change. */
3956 page_start = (void *)page_address(page);
3957 os_protect(page_start, npage_bytes(last_page-page), OS_VM_PROT_ALL);
3958 remap_free_pages(page, last_page-1, 1);
3961 } else if (gencgc_zero_check_during_free_heap) {
3962 /* Double-check that the page is zero filled. */
3965 gc_assert(page_free_p(page));
3966 gc_assert(page_table[page].bytes_used == 0);
3967 page_start = (long *)page_address(page);
3968 for (i=0; i<GENCGC_CARD_BYTES/sizeof(long); i++) {
3969 if (page_start[i] != 0) {
3970 lose("free region not zero at %x\n", page_start + i);
3976 bytes_allocated = 0;
3978 /* Initialize the generations. */
3979 for (page = 0; page < NUM_GENERATIONS; page++) {
3980 generations[page].alloc_start_page = 0;
3981 generations[page].alloc_unboxed_start_page = 0;
3982 generations[page].alloc_large_start_page = 0;
3983 generations[page].alloc_large_unboxed_start_page = 0;
3984 generations[page].bytes_allocated = 0;
3985 generations[page].gc_trigger = 2000000;
3986 generations[page].num_gc = 0;
3987 generations[page].cum_sum_bytes_allocated = 0;
3990 if (gencgc_verbose > 1)
3991 print_generation_stats();
3993 /* Initialize gc_alloc(). */
3994 gc_alloc_generation = 0;
3996 gc_set_region_empty(&boxed_region);
3997 gc_set_region_empty(&unboxed_region);
4000 set_alloc_pointer((lispobj)((char *)heap_base));
4002 if (verify_after_free_heap) {
4003 /* Check whether purify has left any bad pointers. */
4004 FSHOW((stderr, "checking after free_heap\n"));
4014 /* Compute the number of pages needed for the dynamic space.
4015 * Dynamic space size should be aligned on page size. */
4016 page_table_pages = dynamic_space_size/GENCGC_CARD_BYTES;
4017 gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4019 /* Default nursery size to 5% of the total dynamic space size,
4021 bytes_consed_between_gcs = dynamic_space_size/(os_vm_size_t)20;
4022 if (bytes_consed_between_gcs < (1024*1024))
4023 bytes_consed_between_gcs = 1024*1024;
4025 /* The page_table must be allocated using "calloc" to initialize
4026 * the page structures correctly. There used to be a separate
4027 * initialization loop (now commented out; see below) but that was
4028 * unnecessary and did hurt startup time. */
4029 page_table = calloc(page_table_pages, sizeof(struct page));
4030 gc_assert(page_table);
4033 scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4034 transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4036 heap_base = (void*)DYNAMIC_SPACE_START;
4038 /* The page structures are initialized implicitly when page_table
4039 * is allocated with "calloc" above. Formerly we had the following
4040 * explicit initialization here (comments converted to C99 style
4041 * for readability as C's block comments don't nest):
4043 * // Initialize each page structure.
4044 * for (i = 0; i < page_table_pages; i++) {
4045 * // Initialize all pages as free.
4046 * page_table[i].allocated = FREE_PAGE_FLAG;
4047 * page_table[i].bytes_used = 0;
4049 * // Pages are not write-protected at startup.
4050 * page_table[i].write_protected = 0;
4053 * Without this loop the image starts up much faster when dynamic
4054 * space is large -- which it is on 64-bit platforms already by
4055 * default -- and when "calloc" for large arrays is implemented
4056 * using copy-on-write of a page of zeroes -- which it is at least
4057 * on Linux. In this case the pages that page_table_pages is stored
4058 * in are mapped and cleared not before the corresponding part of
4059 * dynamic space is used. For example, this saves clearing 16 MB of
4060 * memory at startup if the page size is 4 KB and the size of
4061 * dynamic space is 4 GB.
4062 * FREE_PAGE_FLAG must be 0 for this to work correctly which is
4063 * asserted below: */
4065 /* Compile time assertion: If triggered, declares an array
4066 * of dimension -1 forcing a syntax error. The intent of the
4067 * assignment is to avoid an "unused variable" warning. */
4068 char assert_free_page_flag_0[(FREE_PAGE_FLAG) ? -1 : 1];
4069 assert_free_page_flag_0[0] = assert_free_page_flag_0[0];
4072 bytes_allocated = 0;
4074 /* Initialize the generations.
4076 * FIXME: very similar to code in gc_free_heap(), should be shared */
4077 for (i = 0; i < NUM_GENERATIONS; i++) {
4078 generations[i].alloc_start_page = 0;
4079 generations[i].alloc_unboxed_start_page = 0;
4080 generations[i].alloc_large_start_page = 0;
4081 generations[i].alloc_large_unboxed_start_page = 0;
4082 generations[i].bytes_allocated = 0;
4083 generations[i].gc_trigger = 2000000;
4084 generations[i].num_gc = 0;
4085 generations[i].cum_sum_bytes_allocated = 0;
4086 /* the tune-able parameters */
4087 generations[i].bytes_consed_between_gc
4088 = bytes_consed_between_gcs/(os_vm_size_t)HIGHEST_NORMAL_GENERATION;
4089 generations[i].number_of_gcs_before_promotion = 1;
4090 generations[i].minimum_age_before_gc = 0.75;
4093 /* Initialize gc_alloc. */
4094 gc_alloc_generation = 0;
4095 gc_set_region_empty(&boxed_region);
4096 gc_set_region_empty(&unboxed_region);
4101 /* Pick up the dynamic space from after a core load.
4103 * The ALLOCATION_POINTER points to the end of the dynamic space.
4107 gencgc_pickup_dynamic(void)
4109 page_index_t page = 0;
4110 void *alloc_ptr = (void *)get_alloc_pointer();
4111 lispobj *prev=(lispobj *)page_address(page);
4112 generation_index_t gen = PSEUDO_STATIC_GENERATION;
4114 lispobj *first,*ptr= (lispobj *)page_address(page);
4116 if (!gencgc_partial_pickup || page_allocated_p(page)) {
4117 /* It is possible, though rare, for the saved page table
4118 * to contain free pages below alloc_ptr. */
4119 page_table[page].gen = gen;
4120 page_table[page].bytes_used = GENCGC_CARD_BYTES;
4121 page_table[page].large_object = 0;
4122 page_table[page].write_protected = 0;
4123 page_table[page].write_protected_cleared = 0;
4124 page_table[page].dont_move = 0;
4125 page_table[page].need_to_zero = 1;
4128 if (!gencgc_partial_pickup) {
4129 page_table[page].allocated = BOXED_PAGE_FLAG;
4130 first=gc_search_space(prev,(ptr+2)-prev,ptr);
4133 page_table[page].region_start_offset =
4134 page_address(page) - (void *)prev;
4137 } while (page_address(page) < alloc_ptr);
4139 last_free_page = page;
4141 generations[gen].bytes_allocated = npage_bytes(page);
4142 bytes_allocated = npage_bytes(page);
4144 gc_alloc_update_all_page_tables();
4145 write_protect_generation_pages(gen);
4149 gc_initialize_pointers(void)
4151 gencgc_pickup_dynamic();
4155 /* alloc(..) is the external interface for memory allocation. It
4156 * allocates to generation 0. It is not called from within the garbage
4157 * collector as it is only external uses that need the check for heap
4158 * size (GC trigger) and to disable the interrupts (interrupts are
4159 * always disabled during a GC).
4161 * The vops that call alloc(..) assume that the returned space is zero-filled.
4162 * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4164 * The check for a GC trigger is only performed when the current
4165 * region is full, so in most cases it's not needed. */
4167 static inline lispobj *
4168 general_alloc_internal(long nbytes, int page_type_flag, struct alloc_region *region,
4169 struct thread *thread)
4171 #ifndef LISP_FEATURE_WIN32
4172 lispobj alloc_signal;
4175 void *new_free_pointer;
4176 os_vm_size_t trigger_bytes = 0;
4178 gc_assert(nbytes>0);
4180 /* Check for alignment allocation problems. */
4181 gc_assert((((unsigned long)region->free_pointer & LOWTAG_MASK) == 0)
4182 && ((nbytes & LOWTAG_MASK) == 0));
4184 /* Must be inside a PA section. */
4185 gc_assert(get_pseudo_atomic_atomic(thread));
4187 if (nbytes > large_allocation)
4188 large_allocation = nbytes;
4190 /* maybe we can do this quickly ... */
4191 new_free_pointer = region->free_pointer + nbytes;
4192 if (new_free_pointer <= region->end_addr) {
4193 new_obj = (void*)(region->free_pointer);
4194 region->free_pointer = new_free_pointer;
4195 return(new_obj); /* yup */
4198 /* We don't want to count nbytes against auto_gc_trigger unless we
4199 * have to: it speeds up the tenuring of objects and slows down
4200 * allocation. However, unless we do so when allocating _very_
4201 * large objects we are in danger of exhausting the heap without
4202 * running sufficient GCs.
4204 if (nbytes >= bytes_consed_between_gcs)
4205 trigger_bytes = nbytes;
4207 /* we have to go the long way around, it seems. Check whether we
4208 * should GC in the near future
4210 if (auto_gc_trigger && (bytes_allocated+trigger_bytes > auto_gc_trigger)) {
4211 /* Don't flood the system with interrupts if the need to gc is
4212 * already noted. This can happen for example when SUB-GC
4213 * allocates or after a gc triggered in a WITHOUT-GCING. */
4214 if (SymbolValue(GC_PENDING,thread) == NIL) {
4215 /* set things up so that GC happens when we finish the PA
4217 SetSymbolValue(GC_PENDING,T,thread);
4218 if (SymbolValue(GC_INHIBIT,thread) == NIL) {
4219 #ifdef LISP_FEATURE_SB_SAFEPOINT
4220 thread_register_gc_trigger();
4222 set_pseudo_atomic_interrupted(thread);
4223 #ifdef GENCGC_IS_PRECISE
4224 /* PPC calls alloc() from a trap or from pa_alloc(),
4225 * look up the most context if it's from a trap. */
4227 os_context_t *context =
4228 thread->interrupt_data->allocation_trap_context;
4229 maybe_save_gc_mask_and_block_deferrables
4230 (context ? os_context_sigmask_addr(context) : NULL);
4233 maybe_save_gc_mask_and_block_deferrables(NULL);
4239 new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4241 #ifndef LISP_FEATURE_WIN32
4242 /* for sb-prof, and not supported on Windows yet */
4243 alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4244 if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4245 if ((signed long) alloc_signal <= 0) {
4246 SetSymbolValue(ALLOC_SIGNAL, T, thread);
4249 SetSymbolValue(ALLOC_SIGNAL,
4250 alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4260 general_alloc(long nbytes, int page_type_flag)
4262 struct thread *thread = arch_os_get_current_thread();
4263 /* Select correct region, and call general_alloc_internal with it.
4264 * For other then boxed allocation we must lock first, since the
4265 * region is shared. */
4266 if (BOXED_PAGE_FLAG & page_type_flag) {
4267 #ifdef LISP_FEATURE_SB_THREAD
4268 struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4270 struct alloc_region *region = &boxed_region;
4272 return general_alloc_internal(nbytes, page_type_flag, region, thread);
4273 } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4275 gc_assert(0 == thread_mutex_lock(&allocation_lock));
4276 obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4277 gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4280 lose("bad page type flag: %d", page_type_flag);
4287 gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4288 return general_alloc(nbytes, BOXED_PAGE_FLAG);
4292 * shared support for the OS-dependent signal handlers which
4293 * catch GENCGC-related write-protect violations
4295 void unhandled_sigmemoryfault(void* addr);
4297 /* Depending on which OS we're running under, different signals might
4298 * be raised for a violation of write protection in the heap. This
4299 * function factors out the common generational GC magic which needs
4300 * to invoked in this case, and should be called from whatever signal
4301 * handler is appropriate for the OS we're running under.
4303 * Return true if this signal is a normal generational GC thing that
4304 * we were able to handle, or false if it was abnormal and control
4305 * should fall through to the general SIGSEGV/SIGBUS/whatever logic.
4307 * We have two control flags for this: one causes us to ignore faults
4308 * on unprotected pages completely, and the second complains to stderr
4309 * but allows us to continue without losing.
4311 extern boolean ignore_memoryfaults_on_unprotected_pages;
4312 boolean ignore_memoryfaults_on_unprotected_pages = 0;
4314 extern boolean continue_after_memoryfault_on_unprotected_pages;
4315 boolean continue_after_memoryfault_on_unprotected_pages = 0;
4318 gencgc_handle_wp_violation(void* fault_addr)
4320 page_index_t page_index = find_page_index(fault_addr);
4323 FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4324 fault_addr, page_index));
4327 /* Check whether the fault is within the dynamic space. */
4328 if (page_index == (-1)) {
4330 /* It can be helpful to be able to put a breakpoint on this
4331 * case to help diagnose low-level problems. */
4332 unhandled_sigmemoryfault(fault_addr);
4334 /* not within the dynamic space -- not our responsibility */
4339 ret = thread_mutex_lock(&free_pages_lock);
4340 gc_assert(ret == 0);
4341 if (page_table[page_index].write_protected) {
4342 /* Unprotect the page. */
4343 os_protect(page_address(page_index), GENCGC_CARD_BYTES, OS_VM_PROT_ALL);
4344 page_table[page_index].write_protected_cleared = 1;
4345 page_table[page_index].write_protected = 0;
4346 } else if (!ignore_memoryfaults_on_unprotected_pages) {
4347 /* The only acceptable reason for this signal on a heap
4348 * access is that GENCGC write-protected the page.
4349 * However, if two CPUs hit a wp page near-simultaneously,
4350 * we had better not have the second one lose here if it
4351 * does this test after the first one has already set wp=0
4353 if(page_table[page_index].write_protected_cleared != 1) {
4354 void lisp_backtrace(int frames);
4357 "Fault @ %p, page %"PAGE_INDEX_FMT" not marked as write-protected:\n"
4358 " boxed_region.first_page: %"PAGE_INDEX_FMT","
4359 " boxed_region.last_page %"PAGE_INDEX_FMT"\n"
4360 " page.region_start_offset: %"OS_VM_SIZE_FMT"\n"
4361 " page.bytes_used: %"PAGE_BYTES_FMT"\n"
4362 " page.allocated: %d\n"
4363 " page.write_protected: %d\n"
4364 " page.write_protected_cleared: %d\n"
4365 " page.generation: %d\n",
4368 boxed_region.first_page,
4369 boxed_region.last_page,
4370 page_table[page_index].region_start_offset,
4371 page_table[page_index].bytes_used,
4372 page_table[page_index].allocated,
4373 page_table[page_index].write_protected,
4374 page_table[page_index].write_protected_cleared,
4375 page_table[page_index].gen);
4376 if (!continue_after_memoryfault_on_unprotected_pages)
4380 ret = thread_mutex_unlock(&free_pages_lock);
4381 gc_assert(ret == 0);
4382 /* Don't worry, we can handle it. */
4386 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4387 * it's not just a case of the program hitting the write barrier, and
4388 * are about to let Lisp deal with it. It's basically just a
4389 * convenient place to set a gdb breakpoint. */
4391 unhandled_sigmemoryfault(void *addr)
4394 void gc_alloc_update_all_page_tables(void)
4396 /* Flush the alloc regions updating the tables. */
4399 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4400 gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4401 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4405 gc_set_region_empty(struct alloc_region *region)
4407 region->first_page = 0;
4408 region->last_page = -1;
4409 region->start_addr = page_address(0);
4410 region->free_pointer = page_address(0);
4411 region->end_addr = page_address(0);
4415 zero_all_free_pages()
4419 for (i = 0; i < last_free_page; i++) {
4420 if (page_free_p(i)) {
4421 #ifdef READ_PROTECT_FREE_PAGES
4422 os_protect(page_address(i),
4431 /* Things to do before doing a final GC before saving a core (without
4434 * + Pages in large_object pages aren't moved by the GC, so we need to
4435 * unset that flag from all pages.
4436 * + The pseudo-static generation isn't normally collected, but it seems
4437 * reasonable to collect it at least when saving a core. So move the
4438 * pages to a normal generation.
4441 prepare_for_final_gc ()
4444 for (i = 0; i < last_free_page; i++) {
4445 page_table[i].large_object = 0;
4446 if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4447 int used = page_table[i].bytes_used;
4448 page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4449 generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4450 generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4456 /* Do a non-conservative GC, and then save a core with the initial
4457 * function being set to the value of the static symbol
4458 * SB!VM:RESTART-LISP-FUNCTION */
4460 gc_and_save(char *filename, boolean prepend_runtime,
4461 boolean save_runtime_options,
4462 boolean compressed, int compression_level)
4465 void *runtime_bytes = NULL;
4466 size_t runtime_size;
4468 file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4473 conservative_stack = 0;
4475 /* The filename might come from Lisp, and be moved by the now
4476 * non-conservative GC. */
4477 filename = strdup(filename);
4479 /* Collect twice: once into relatively high memory, and then back
4480 * into low memory. This compacts the retained data into the lower
4481 * pages, minimizing the size of the core file.
4483 prepare_for_final_gc();
4484 gencgc_alloc_start_page = last_free_page;
4485 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4487 prepare_for_final_gc();
4488 gencgc_alloc_start_page = -1;
4489 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4491 if (prepend_runtime)
4492 save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
4494 /* The dumper doesn't know that pages need to be zeroed before use. */
4495 zero_all_free_pages();
4496 save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4497 prepend_runtime, save_runtime_options,
4498 compressed ? compression_level : COMPRESSION_LEVEL_NONE);
4499 /* Oops. Save still managed to fail. Since we've mangled the stack
4500 * beyond hope, there's not much we can do.
4501 * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4502 * going to be rather unsatisfactory too... */
4503 lose("Attempt to save core after non-conservative GC failed.\n");