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 long large_object_size = 4 * GENCGC_ALLOC_GRANULARITY;
83 #elif (GENCGC_CARD_BYTES >= PAGE_BYTES) && (GENCGC_CARD_BYTES >= GENCGC_ALLOC_GRANULARITY)
84 long large_object_size = 4 * GENCGC_CARD_BYTES;
86 long large_object_size = 4 * PAGE_BYTES;
94 /* the verbosity level. All non-error messages are disabled at level 0;
95 * and only a few rare messages are printed at level 1. */
97 boolean gencgc_verbose = 1;
99 boolean gencgc_verbose = 0;
102 /* FIXME: At some point enable the various error-checking things below
103 * and see what they say. */
105 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
106 * Set verify_gens to HIGHEST_NORMAL_GENERATION + 1 to disable this kind of
108 generation_index_t verify_gens = HIGHEST_NORMAL_GENERATION + 1;
110 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
111 boolean pre_verify_gen_0 = 0;
113 /* Should we check for bad pointers after gc_free_heap is called
114 * from Lisp PURIFY? */
115 boolean verify_after_free_heap = 0;
117 /* Should we print a note when code objects are found in the dynamic space
118 * during a heap verify? */
119 boolean verify_dynamic_code_check = 0;
121 /* Should we check code objects for fixup errors after they are transported? */
122 boolean check_code_fixups = 0;
124 /* Should we check that newly allocated regions are zero filled? */
125 boolean gencgc_zero_check = 0;
127 /* Should we check that the free space is zero filled? */
128 boolean gencgc_enable_verify_zero_fill = 0;
130 /* Should we check that free pages are zero filled during gc_free_heap
131 * called after Lisp PURIFY? */
132 boolean gencgc_zero_check_during_free_heap = 0;
134 /* When loading a core, don't do a full scan of the memory for the
135 * memory region boundaries. (Set to true by coreparse.c if the core
136 * contained a pagetable entry).
138 boolean gencgc_partial_pickup = 0;
140 /* If defined, free pages are read-protected to ensure that nothing
144 /* #define READ_PROTECT_FREE_PAGES */
148 * GC structures and variables
151 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
152 os_vm_size_t bytes_allocated = 0;
153 os_vm_size_t auto_gc_trigger = 0;
155 /* the source and destination generations. These are set before a GC starts
157 generation_index_t from_space;
158 generation_index_t new_space;
160 /* Set to 1 when in GC */
161 boolean gc_active_p = 0;
163 /* should the GC be conservative on stack. If false (only right before
164 * saving a core), don't scan the stack / mark pages dont_move. */
165 static boolean conservative_stack = 1;
167 /* An array of page structures is allocated on gc initialization.
168 * This helps quickly map between an address its page structure.
169 * page_table_pages is set from the size of the dynamic space. */
170 page_index_t page_table_pages;
171 struct page *page_table;
173 static inline boolean page_allocated_p(page_index_t page) {
174 return (page_table[page].allocated != FREE_PAGE_FLAG);
177 static inline boolean page_no_region_p(page_index_t page) {
178 return !(page_table[page].allocated & OPEN_REGION_PAGE_FLAG);
181 static inline boolean page_allocated_no_region_p(page_index_t page) {
182 return ((page_table[page].allocated & (UNBOXED_PAGE_FLAG | BOXED_PAGE_FLAG))
183 && page_no_region_p(page));
186 static inline boolean page_free_p(page_index_t page) {
187 return (page_table[page].allocated == FREE_PAGE_FLAG);
190 static inline boolean page_boxed_p(page_index_t page) {
191 return (page_table[page].allocated & BOXED_PAGE_FLAG);
194 static inline boolean code_page_p(page_index_t page) {
195 return (page_table[page].allocated & CODE_PAGE_FLAG);
198 static inline boolean page_boxed_no_region_p(page_index_t page) {
199 return page_boxed_p(page) && page_no_region_p(page);
202 static inline boolean page_unboxed_p(page_index_t page) {
203 /* Both flags set == boxed code page */
204 return ((page_table[page].allocated & UNBOXED_PAGE_FLAG)
205 && !page_boxed_p(page));
208 static inline boolean protect_page_p(page_index_t page, generation_index_t generation) {
209 return (page_boxed_no_region_p(page)
210 && (page_table[page].bytes_used != 0)
211 && !page_table[page].dont_move
212 && (page_table[page].gen == generation));
215 /* To map addresses to page structures the address of the first page
217 static void *heap_base = NULL;
219 /* Calculate the start address for the given page number. */
221 page_address(page_index_t page_num)
223 return (heap_base + (page_num * GENCGC_CARD_BYTES));
226 /* Calculate the address where the allocation region associated with
227 * the page starts. */
229 page_region_start(page_index_t page_index)
231 return page_address(page_index)-page_table[page_index].region_start_offset;
234 /* Find the page index within the page_table for the given
235 * address. Return -1 on failure. */
237 find_page_index(void *addr)
239 if (addr >= heap_base) {
240 page_index_t index = ((pointer_sized_uint_t)addr -
241 (pointer_sized_uint_t)heap_base) / GENCGC_CARD_BYTES;
242 if (index < page_table_pages)
249 npage_bytes(page_index_t npages)
251 gc_assert(npages>=0);
252 return ((os_vm_size_t)npages)*GENCGC_CARD_BYTES;
255 /* Check that X is a higher address than Y and return offset from Y to
258 size_t void_diff(void *x, void *y)
261 return (pointer_sized_uint_t)x - (pointer_sized_uint_t)y;
264 /* a structure to hold the state of a generation
266 * CAUTION: If you modify this, make sure to touch up the alien
267 * definition in src/code/gc.lisp accordingly. ...or better yes,
268 * deal with the FIXME there...
272 /* the first page that gc_alloc() checks on its next call */
273 page_index_t alloc_start_page;
275 /* the first page that gc_alloc_unboxed() checks on its next call */
276 page_index_t alloc_unboxed_start_page;
278 /* the first page that gc_alloc_large (boxed) considers on its next
279 * call. (Although it always allocates after the boxed_region.) */
280 page_index_t alloc_large_start_page;
282 /* the first page that gc_alloc_large (unboxed) considers on its
283 * next call. (Although it always allocates after the
284 * current_unboxed_region.) */
285 page_index_t alloc_large_unboxed_start_page;
287 /* the bytes allocated to this generation */
288 os_vm_size_t bytes_allocated;
290 /* the number of bytes at which to trigger a GC */
291 os_vm_size_t gc_trigger;
293 /* to calculate a new level for gc_trigger */
294 os_vm_size_t bytes_consed_between_gc;
296 /* the number of GCs since the last raise */
299 /* the number of GCs to run on the generations before raising objects to the
301 int number_of_gcs_before_promotion;
303 /* the cumulative sum of the bytes allocated to this generation. It is
304 * cleared after a GC on this generations, and update before new
305 * objects are added from a GC of a younger generation. Dividing by
306 * the bytes_allocated will give the average age of the memory in
307 * this generation since its last GC. */
308 os_vm_size_t cum_sum_bytes_allocated;
310 /* a minimum average memory age before a GC will occur helps
311 * prevent a GC when a large number of new live objects have been
312 * added, in which case a GC could be a waste of time */
313 double minimum_age_before_gc;
316 /* an array of generation structures. There needs to be one more
317 * generation structure than actual generations as the oldest
318 * generation is temporarily raised then lowered. */
319 struct generation generations[NUM_GENERATIONS];
321 /* the oldest generation that is will currently be GCed by default.
322 * Valid values are: 0, 1, ... HIGHEST_NORMAL_GENERATION
324 * The default of HIGHEST_NORMAL_GENERATION enables GC on all generations.
326 * Setting this to 0 effectively disables the generational nature of
327 * the GC. In some applications generational GC may not be useful
328 * because there are no long-lived objects.
330 * An intermediate value could be handy after moving long-lived data
331 * into an older generation so an unnecessary GC of this long-lived
332 * data can be avoided. */
333 generation_index_t gencgc_oldest_gen_to_gc = HIGHEST_NORMAL_GENERATION;
335 /* The maximum free page in the heap is maintained and used to update
336 * ALLOCATION_POINTER which is used by the room function to limit its
337 * search of the heap. XX Gencgc obviously needs to be better
338 * integrated with the Lisp code. */
339 page_index_t last_free_page;
341 #ifdef LISP_FEATURE_SB_THREAD
342 /* This lock is to prevent multiple threads from simultaneously
343 * allocating new regions which overlap each other. Note that the
344 * majority of GC is single-threaded, but alloc() may be called from
345 * >1 thread at a time and must be thread-safe. This lock must be
346 * seized before all accesses to generations[] or to parts of
347 * page_table[] that other threads may want to see */
348 static pthread_mutex_t free_pages_lock = PTHREAD_MUTEX_INITIALIZER;
349 /* This lock is used to protect non-thread-local allocation. */
350 static pthread_mutex_t allocation_lock = PTHREAD_MUTEX_INITIALIZER;
353 extern os_vm_size_t gencgc_release_granularity;
354 os_vm_size_t gencgc_release_granularity = GENCGC_RELEASE_GRANULARITY;
356 extern os_vm_size_t gencgc_alloc_granularity;
357 os_vm_size_t gencgc_alloc_granularity = GENCGC_ALLOC_GRANULARITY;
361 * miscellaneous heap functions
364 /* Count the number of pages which are write-protected within the
365 * given generation. */
367 count_write_protect_generation_pages(generation_index_t generation)
369 page_index_t i, count = 0;
371 for (i = 0; i < last_free_page; i++)
372 if (page_allocated_p(i)
373 && (page_table[i].gen == generation)
374 && (page_table[i].write_protected == 1))
379 /* Count the number of pages within the given generation. */
381 count_generation_pages(generation_index_t generation)
384 page_index_t count = 0;
386 for (i = 0; i < last_free_page; i++)
387 if (page_allocated_p(i)
388 && (page_table[i].gen == generation))
395 count_dont_move_pages(void)
398 page_index_t count = 0;
399 for (i = 0; i < last_free_page; i++) {
400 if (page_allocated_p(i)
401 && (page_table[i].dont_move != 0)) {
409 /* Work through the pages and add up the number of bytes used for the
410 * given generation. */
412 count_generation_bytes_allocated (generation_index_t gen)
415 os_vm_size_t result = 0;
416 for (i = 0; i < last_free_page; i++) {
417 if (page_allocated_p(i)
418 && (page_table[i].gen == gen))
419 result += page_table[i].bytes_used;
424 /* Return the average age of the memory in a generation. */
426 generation_average_age(generation_index_t gen)
428 if (generations[gen].bytes_allocated == 0)
432 ((double)generations[gen].cum_sum_bytes_allocated)
433 / ((double)generations[gen].bytes_allocated);
437 write_generation_stats(FILE *file)
439 generation_index_t i;
441 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
442 #define FPU_STATE_SIZE 27
443 int fpu_state[FPU_STATE_SIZE];
444 #elif defined(LISP_FEATURE_PPC)
445 #define FPU_STATE_SIZE 32
446 long long fpu_state[FPU_STATE_SIZE];
449 /* This code uses the FP instructions which may be set up for Lisp
450 * so they need to be saved and reset for C. */
453 /* Print the heap stats. */
455 " Gen StaPg UbSta LaSta LUbSt Boxed Unboxed LB LUB !move Alloc Waste Trig WP GCs Mem-age\n");
457 for (i = 0; i < SCRATCH_GENERATION; i++) {
459 page_index_t boxed_cnt = 0;
460 page_index_t unboxed_cnt = 0;
461 page_index_t large_boxed_cnt = 0;
462 page_index_t large_unboxed_cnt = 0;
463 page_index_t pinned_cnt=0;
465 for (j = 0; j < last_free_page; j++)
466 if (page_table[j].gen == i) {
468 /* Count the number of boxed pages within the given
470 if (page_boxed_p(j)) {
471 if (page_table[j].large_object)
476 if(page_table[j].dont_move) pinned_cnt++;
477 /* Count the number of unboxed pages within the given
479 if (page_unboxed_p(j)) {
480 if (page_table[j].large_object)
487 gc_assert(generations[i].bytes_allocated
488 == count_generation_bytes_allocated(i));
490 " %1d: %5ld %5ld %5ld %5ld",
492 generations[i].alloc_start_page,
493 generations[i].alloc_unboxed_start_page,
494 generations[i].alloc_large_start_page,
495 generations[i].alloc_large_unboxed_start_page);
497 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT
498 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT,
499 boxed_cnt, unboxed_cnt, large_boxed_cnt,
500 large_unboxed_cnt, pinned_cnt);
502 " %8ld %5ld %8ld %4ld %3d %7.4f\n",
503 generations[i].bytes_allocated,
504 (npage_bytes(count_generation_pages(i))
505 - generations[i].bytes_allocated),
506 generations[i].gc_trigger,
507 count_write_protect_generation_pages(i),
508 generations[i].num_gc,
509 generation_average_age(i));
511 fprintf(file," Total bytes allocated = %lu\n", (unsigned long)bytes_allocated);
512 fprintf(file," Dynamic-space-size bytes = %lu\n", (unsigned long)dynamic_space_size);
514 fpu_restore(fpu_state);
518 write_heap_exhaustion_report(FILE *file, long available, long requested,
519 struct thread *thread)
522 "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
523 gc_active_p ? "garbage collection" : "allocation",
526 write_generation_stats(file);
527 fprintf(file, "GC control variables:\n");
528 fprintf(file, " *GC-INHIBIT* = %s\n *GC-PENDING* = %s\n",
529 SymbolValue(GC_INHIBIT,thread)==NIL ? "false" : "true",
530 (SymbolValue(GC_PENDING, thread) == T) ?
531 "true" : ((SymbolValue(GC_PENDING, thread) == NIL) ?
532 "false" : "in progress"));
533 #ifdef LISP_FEATURE_SB_THREAD
534 fprintf(file, " *STOP-FOR-GC-PENDING* = %s\n",
535 SymbolValue(STOP_FOR_GC_PENDING,thread)==NIL ? "false" : "true");
540 print_generation_stats(void)
542 write_generation_stats(stderr);
545 extern char* gc_logfile;
546 char * gc_logfile = NULL;
549 log_generation_stats(char *logfile, char *header)
552 FILE * log = fopen(logfile, "a");
554 fprintf(log, "%s\n", header);
555 write_generation_stats(log);
558 fprintf(stderr, "Could not open gc logfile: %s\n", logfile);
565 report_heap_exhaustion(long available, long requested, struct thread *th)
568 FILE * log = fopen(gc_logfile, "a");
570 write_heap_exhaustion_report(log, available, requested, th);
573 fprintf(stderr, "Could not open gc logfile: %s\n", gc_logfile);
577 /* Always to stderr as well. */
578 write_heap_exhaustion_report(stderr, available, requested, th);
582 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
583 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
586 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
587 * if zeroing it ourselves, i.e. in practice give the memory back to the
588 * OS. Generally done after a large GC.
590 void zero_pages_with_mmap(page_index_t start, page_index_t end) {
592 void *addr = page_address(start), *new_addr;
593 os_vm_size_t length = npage_bytes(1+end-start);
598 gc_assert(length >= gencgc_release_granularity);
599 gc_assert((length % gencgc_release_granularity) == 0);
601 os_invalidate(addr, length);
602 new_addr = os_validate(addr, length);
603 if (new_addr == NULL || new_addr != addr) {
604 lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
608 for (i = start; i <= end; i++) {
609 page_table[i].need_to_zero = 0;
613 /* Zero the pages from START to END (inclusive). Generally done just after
614 * a new region has been allocated.
617 zero_pages(page_index_t start, page_index_t end) {
621 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
622 fast_bzero(page_address(start), npage_bytes(1+end-start));
624 bzero(page_address(start), npage_bytes(1+end-start));
630 zero_and_mark_pages(page_index_t start, page_index_t end) {
633 zero_pages(start, end);
634 for (i = start; i <= end; i++)
635 page_table[i].need_to_zero = 0;
638 /* Zero the pages from START to END (inclusive), except for those
639 * pages that are known to already zeroed. Mark all pages in the
640 * ranges as non-zeroed.
643 zero_dirty_pages(page_index_t start, page_index_t end) {
646 for (i = start; i <= end; i++) {
647 if (!page_table[i].need_to_zero) continue;
648 for (j = i+1; (j <= end) && (page_table[j].need_to_zero); j++);
653 for (i = start; i <= end; i++) {
654 page_table[i].need_to_zero = 1;
660 * To support quick and inline allocation, regions of memory can be
661 * allocated and then allocated from with just a free pointer and a
662 * check against an end address.
664 * Since objects can be allocated to spaces with different properties
665 * e.g. boxed/unboxed, generation, ages; there may need to be many
666 * allocation regions.
668 * Each allocation region may start within a partly used page. Many
669 * features of memory use are noted on a page wise basis, e.g. the
670 * generation; so if a region starts within an existing allocated page
671 * it must be consistent with this page.
673 * During the scavenging of the newspace, objects will be transported
674 * into an allocation region, and pointers updated to point to this
675 * allocation region. It is possible that these pointers will be
676 * scavenged again before the allocation region is closed, e.g. due to
677 * trans_list which jumps all over the place to cleanup the list. It
678 * is important to be able to determine properties of all objects
679 * pointed to when scavenging, e.g to detect pointers to the oldspace.
680 * Thus it's important that the allocation regions have the correct
681 * properties set when allocated, and not just set when closed. The
682 * region allocation routines return regions with the specified
683 * properties, and grab all the pages, setting their properties
684 * appropriately, except that the amount used is not known.
686 * These regions are used to support quicker allocation using just a
687 * free pointer. The actual space used by the region is not reflected
688 * in the pages tables until it is closed. It can't be scavenged until
691 * When finished with the region it should be closed, which will
692 * update the page tables for the actual space used returning unused
693 * space. Further it may be noted in the new regions which is
694 * necessary when scavenging the newspace.
696 * Large objects may be allocated directly without an allocation
697 * region, the page tables are updated immediately.
699 * Unboxed objects don't contain pointers to other objects and so
700 * don't need scavenging. Further they can't contain pointers to
701 * younger generations so WP is not needed. By allocating pages to
702 * unboxed objects the whole page never needs scavenging or
703 * write-protecting. */
705 /* We are only using two regions at present. Both are for the current
706 * newspace generation. */
707 struct alloc_region boxed_region;
708 struct alloc_region unboxed_region;
710 /* The generation currently being allocated to. */
711 static generation_index_t gc_alloc_generation;
713 static inline page_index_t
714 generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large)
717 if (UNBOXED_PAGE_FLAG == page_type_flag) {
718 return generations[generation].alloc_large_unboxed_start_page;
719 } else if (BOXED_PAGE_FLAG & page_type_flag) {
720 /* Both code and data. */
721 return generations[generation].alloc_large_start_page;
723 lose("bad page type flag: %d", page_type_flag);
726 if (UNBOXED_PAGE_FLAG == page_type_flag) {
727 return generations[generation].alloc_unboxed_start_page;
728 } else if (BOXED_PAGE_FLAG & page_type_flag) {
729 /* Both code and data. */
730 return generations[generation].alloc_start_page;
732 lose("bad page_type_flag: %d", page_type_flag);
738 set_generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large,
742 if (UNBOXED_PAGE_FLAG == page_type_flag) {
743 generations[generation].alloc_large_unboxed_start_page = page;
744 } else if (BOXED_PAGE_FLAG & page_type_flag) {
745 /* Both code and data. */
746 generations[generation].alloc_large_start_page = page;
748 lose("bad page type flag: %d", page_type_flag);
751 if (UNBOXED_PAGE_FLAG == page_type_flag) {
752 generations[generation].alloc_unboxed_start_page = page;
753 } else if (BOXED_PAGE_FLAG & page_type_flag) {
754 /* Both code and data. */
755 generations[generation].alloc_start_page = page;
757 lose("bad page type flag: %d", page_type_flag);
762 /* Find a new region with room for at least the given number of bytes.
764 * It starts looking at the current generation's alloc_start_page. So
765 * may pick up from the previous region if there is enough space. This
766 * keeps the allocation contiguous when scavenging the newspace.
768 * The alloc_region should have been closed by a call to
769 * gc_alloc_update_page_tables(), and will thus be in an empty state.
771 * To assist the scavenging functions write-protected pages are not
772 * used. Free pages should not be write-protected.
774 * It is critical to the conservative GC that the start of regions be
775 * known. To help achieve this only small regions are allocated at a
778 * During scavenging, pointers may be found to within the current
779 * region and the page generation must be set so that pointers to the
780 * from space can be recognized. Therefore the generation of pages in
781 * the region are set to gc_alloc_generation. To prevent another
782 * allocation call using the same pages, all the pages in the region
783 * are allocated, although they will initially be empty.
786 gc_alloc_new_region(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
788 page_index_t first_page;
789 page_index_t last_page;
790 unsigned long bytes_found;
796 "/alloc_new_region for %d bytes from gen %d\n",
797 nbytes, gc_alloc_generation));
800 /* Check that the region is in a reset state. */
801 gc_assert((alloc_region->first_page == 0)
802 && (alloc_region->last_page == -1)
803 && (alloc_region->free_pointer == alloc_region->end_addr));
804 ret = thread_mutex_lock(&free_pages_lock);
806 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0);
807 last_page=gc_find_freeish_pages(&first_page, nbytes, page_type_flag);
808 bytes_found=(GENCGC_CARD_BYTES - page_table[first_page].bytes_used)
809 + npage_bytes(last_page-first_page);
811 /* Set up the alloc_region. */
812 alloc_region->first_page = first_page;
813 alloc_region->last_page = last_page;
814 alloc_region->start_addr = page_table[first_page].bytes_used
815 + page_address(first_page);
816 alloc_region->free_pointer = alloc_region->start_addr;
817 alloc_region->end_addr = alloc_region->start_addr + bytes_found;
819 /* Set up the pages. */
821 /* The first page may have already been in use. */
822 if (page_table[first_page].bytes_used == 0) {
823 page_table[first_page].allocated = page_type_flag;
824 page_table[first_page].gen = gc_alloc_generation;
825 page_table[first_page].large_object = 0;
826 page_table[first_page].region_start_offset = 0;
829 gc_assert(page_table[first_page].allocated == page_type_flag);
830 page_table[first_page].allocated |= OPEN_REGION_PAGE_FLAG;
832 gc_assert(page_table[first_page].gen == gc_alloc_generation);
833 gc_assert(page_table[first_page].large_object == 0);
835 for (i = first_page+1; i <= last_page; i++) {
836 page_table[i].allocated = page_type_flag;
837 page_table[i].gen = gc_alloc_generation;
838 page_table[i].large_object = 0;
839 /* This may not be necessary for unboxed regions (think it was
841 page_table[i].region_start_offset =
842 void_diff(page_address(i),alloc_region->start_addr);
843 page_table[i].allocated |= OPEN_REGION_PAGE_FLAG ;
845 /* Bump up last_free_page. */
846 if (last_page+1 > last_free_page) {
847 last_free_page = last_page+1;
848 /* do we only want to call this on special occasions? like for
850 set_alloc_pointer((lispobj)page_address(last_free_page));
852 ret = thread_mutex_unlock(&free_pages_lock);
855 #ifdef READ_PROTECT_FREE_PAGES
856 os_protect(page_address(first_page),
857 npage_bytes(1+last_page-first_page),
861 /* If the first page was only partial, don't check whether it's
862 * zeroed (it won't be) and don't zero it (since the parts that
863 * we're interested in are guaranteed to be zeroed).
865 if (page_table[first_page].bytes_used) {
869 zero_dirty_pages(first_page, last_page);
871 /* we can do this after releasing free_pages_lock */
872 if (gencgc_zero_check) {
874 for (p = (long *)alloc_region->start_addr;
875 p < (long *)alloc_region->end_addr; p++) {
877 /* KLUDGE: It would be nice to use %lx and explicit casts
878 * (long) in code like this, so that it is less likely to
879 * break randomly when running on a machine with different
880 * word sizes. -- WHN 19991129 */
881 lose("The new region at %x is not zero (start=%p, end=%p).\n",
882 p, alloc_region->start_addr, alloc_region->end_addr);
888 /* If the record_new_objects flag is 2 then all new regions created
891 * If it's 1 then then it is only recorded if the first page of the
892 * current region is <= new_areas_ignore_page. This helps avoid
893 * unnecessary recording when doing full scavenge pass.
895 * The new_object structure holds the page, byte offset, and size of
896 * new regions of objects. Each new area is placed in the array of
897 * these structures pointer to by new_areas. new_areas_index holds the
898 * offset into new_areas.
900 * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
901 * later code must detect this and handle it, probably by doing a full
902 * scavenge of a generation. */
903 #define NUM_NEW_AREAS 512
904 static int record_new_objects = 0;
905 static page_index_t new_areas_ignore_page;
911 static struct new_area (*new_areas)[];
912 static long new_areas_index;
915 /* Add a new area to new_areas. */
917 add_new_area(page_index_t first_page, size_t offset, size_t size)
919 unsigned long new_area_start,c;
922 /* Ignore if full. */
923 if (new_areas_index >= NUM_NEW_AREAS)
926 switch (record_new_objects) {
930 if (first_page > new_areas_ignore_page)
939 new_area_start = npage_bytes(first_page) + offset;
941 /* Search backwards for a prior area that this follows from. If
942 found this will save adding a new area. */
943 for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
944 unsigned long area_end =
945 npage_bytes((*new_areas)[i].page)
946 + (*new_areas)[i].offset
947 + (*new_areas)[i].size;
949 "/add_new_area S1 %d %d %d %d\n",
950 i, c, new_area_start, area_end));*/
951 if (new_area_start == area_end) {
953 "/adding to [%d] %d %d %d with %d %d %d:\n",
955 (*new_areas)[i].page,
956 (*new_areas)[i].offset,
957 (*new_areas)[i].size,
961 (*new_areas)[i].size += size;
966 (*new_areas)[new_areas_index].page = first_page;
967 (*new_areas)[new_areas_index].offset = offset;
968 (*new_areas)[new_areas_index].size = size;
970 "/new_area %d page %d offset %d size %d\n",
971 new_areas_index, first_page, offset, size));*/
974 /* Note the max new_areas used. */
975 if (new_areas_index > max_new_areas)
976 max_new_areas = new_areas_index;
979 /* Update the tables for the alloc_region. The region may be added to
982 * When done the alloc_region is set up so that the next quick alloc
983 * will fail safely and thus a new region will be allocated. Further
984 * it is safe to try to re-update the page table of this reset
987 gc_alloc_update_page_tables(int page_type_flag, struct alloc_region *alloc_region)
990 page_index_t first_page;
991 page_index_t next_page;
992 unsigned long bytes_used;
993 unsigned long orig_first_page_bytes_used;
994 unsigned long region_size;
995 unsigned long byte_cnt;
999 first_page = alloc_region->first_page;
1001 /* Catch an unused alloc_region. */
1002 if ((first_page == 0) && (alloc_region->last_page == -1))
1005 next_page = first_page+1;
1007 ret = thread_mutex_lock(&free_pages_lock);
1008 gc_assert(ret == 0);
1009 if (alloc_region->free_pointer != alloc_region->start_addr) {
1010 /* some bytes were allocated in the region */
1011 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1013 gc_assert(alloc_region->start_addr ==
1014 (page_address(first_page)
1015 + page_table[first_page].bytes_used));
1017 /* All the pages used need to be updated */
1019 /* Update the first page. */
1021 /* If the page was free then set up the gen, and
1022 * region_start_offset. */
1023 if (page_table[first_page].bytes_used == 0)
1024 gc_assert(page_table[first_page].region_start_offset == 0);
1025 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1027 gc_assert(page_table[first_page].allocated & page_type_flag);
1028 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1029 gc_assert(page_table[first_page].large_object == 0);
1033 /* Calculate the number of bytes used in this page. This is not
1034 * always the number of new bytes, unless it was free. */
1036 if ((bytes_used = void_diff(alloc_region->free_pointer,
1037 page_address(first_page)))
1038 >GENCGC_CARD_BYTES) {
1039 bytes_used = GENCGC_CARD_BYTES;
1042 page_table[first_page].bytes_used = bytes_used;
1043 byte_cnt += bytes_used;
1046 /* All the rest of the pages should be free. We need to set
1047 * their region_start_offset pointer to the start of the
1048 * region, and set the bytes_used. */
1050 page_table[next_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1051 gc_assert(page_table[next_page].allocated & page_type_flag);
1052 gc_assert(page_table[next_page].bytes_used == 0);
1053 gc_assert(page_table[next_page].gen == gc_alloc_generation);
1054 gc_assert(page_table[next_page].large_object == 0);
1056 gc_assert(page_table[next_page].region_start_offset ==
1057 void_diff(page_address(next_page),
1058 alloc_region->start_addr));
1060 /* Calculate the number of bytes used in this page. */
1062 if ((bytes_used = void_diff(alloc_region->free_pointer,
1063 page_address(next_page)))>GENCGC_CARD_BYTES) {
1064 bytes_used = GENCGC_CARD_BYTES;
1067 page_table[next_page].bytes_used = bytes_used;
1068 byte_cnt += bytes_used;
1073 region_size = void_diff(alloc_region->free_pointer,
1074 alloc_region->start_addr);
1075 bytes_allocated += region_size;
1076 generations[gc_alloc_generation].bytes_allocated += region_size;
1078 gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
1080 /* Set the generations alloc restart page to the last page of
1082 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0, next_page-1);
1084 /* Add the region to the new_areas if requested. */
1085 if (BOXED_PAGE_FLAG & page_type_flag)
1086 add_new_area(first_page,orig_first_page_bytes_used, region_size);
1090 "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1092 gc_alloc_generation));
1095 /* There are no bytes allocated. Unallocate the first_page if
1096 * there are 0 bytes_used. */
1097 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1098 if (page_table[first_page].bytes_used == 0)
1099 page_table[first_page].allocated = FREE_PAGE_FLAG;
1102 /* Unallocate any unused pages. */
1103 while (next_page <= alloc_region->last_page) {
1104 gc_assert(page_table[next_page].bytes_used == 0);
1105 page_table[next_page].allocated = FREE_PAGE_FLAG;
1108 ret = thread_mutex_unlock(&free_pages_lock);
1109 gc_assert(ret == 0);
1111 /* alloc_region is per-thread, we're ok to do this unlocked */
1112 gc_set_region_empty(alloc_region);
1115 static inline void *gc_quick_alloc(long nbytes);
1117 /* Allocate a possibly large object. */
1119 gc_alloc_large(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
1121 page_index_t first_page;
1122 page_index_t last_page;
1123 int orig_first_page_bytes_used;
1126 unsigned long bytes_used;
1127 page_index_t next_page;
1130 ret = thread_mutex_lock(&free_pages_lock);
1131 gc_assert(ret == 0);
1133 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1);
1134 if (first_page <= alloc_region->last_page) {
1135 first_page = alloc_region->last_page+1;
1138 last_page=gc_find_freeish_pages(&first_page,nbytes, page_type_flag);
1140 gc_assert(first_page > alloc_region->last_page);
1142 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1, last_page);
1144 /* Set up the pages. */
1145 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1147 /* If the first page was free then set up the gen, and
1148 * region_start_offset. */
1149 if (page_table[first_page].bytes_used == 0) {
1150 page_table[first_page].allocated = page_type_flag;
1151 page_table[first_page].gen = gc_alloc_generation;
1152 page_table[first_page].region_start_offset = 0;
1153 page_table[first_page].large_object = 1;
1156 gc_assert(page_table[first_page].allocated == page_type_flag);
1157 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1158 gc_assert(page_table[first_page].large_object == 1);
1162 /* Calc. the number of bytes used in this page. This is not
1163 * always the number of new bytes, unless it was free. */
1165 if ((bytes_used = nbytes+orig_first_page_bytes_used) > GENCGC_CARD_BYTES) {
1166 bytes_used = GENCGC_CARD_BYTES;
1169 page_table[first_page].bytes_used = bytes_used;
1170 byte_cnt += bytes_used;
1172 next_page = first_page+1;
1174 /* All the rest of the pages should be free. We need to set their
1175 * region_start_offset pointer to the start of the region, and set
1176 * the bytes_used. */
1178 gc_assert(page_free_p(next_page));
1179 gc_assert(page_table[next_page].bytes_used == 0);
1180 page_table[next_page].allocated = page_type_flag;
1181 page_table[next_page].gen = gc_alloc_generation;
1182 page_table[next_page].large_object = 1;
1184 page_table[next_page].region_start_offset =
1185 npage_bytes(next_page-first_page) - orig_first_page_bytes_used;
1187 /* Calculate the number of bytes used in this page. */
1189 bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt;
1190 if (bytes_used > GENCGC_CARD_BYTES) {
1191 bytes_used = GENCGC_CARD_BYTES;
1194 page_table[next_page].bytes_used = bytes_used;
1195 page_table[next_page].write_protected=0;
1196 page_table[next_page].dont_move=0;
1197 byte_cnt += bytes_used;
1201 gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
1203 bytes_allocated += nbytes;
1204 generations[gc_alloc_generation].bytes_allocated += nbytes;
1206 /* Add the region to the new_areas if requested. */
1207 if (BOXED_PAGE_FLAG & page_type_flag)
1208 add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1210 /* Bump up last_free_page */
1211 if (last_page+1 > last_free_page) {
1212 last_free_page = last_page+1;
1213 set_alloc_pointer((lispobj)(page_address(last_free_page)));
1215 ret = thread_mutex_unlock(&free_pages_lock);
1216 gc_assert(ret == 0);
1218 #ifdef READ_PROTECT_FREE_PAGES
1219 os_protect(page_address(first_page),
1220 npage_bytes(1+last_page-first_page),
1224 zero_dirty_pages(first_page, last_page);
1226 return page_address(first_page);
1229 static page_index_t gencgc_alloc_start_page = -1;
1232 gc_heap_exhausted_error_or_lose (long available, long requested)
1234 struct thread *thread = arch_os_get_current_thread();
1235 /* Write basic information before doing anything else: if we don't
1236 * call to lisp this is a must, and even if we do there is always
1237 * the danger that we bounce back here before the error has been
1238 * handled, or indeed even printed.
1240 report_heap_exhaustion(available, requested, thread);
1241 if (gc_active_p || (available == 0)) {
1242 /* If we are in GC, or totally out of memory there is no way
1243 * to sanely transfer control to the lisp-side of things.
1245 lose("Heap exhausted, game over.");
1248 /* FIXME: assert free_pages_lock held */
1249 (void)thread_mutex_unlock(&free_pages_lock);
1250 gc_assert(get_pseudo_atomic_atomic(thread));
1251 clear_pseudo_atomic_atomic(thread);
1252 if (get_pseudo_atomic_interrupted(thread))
1253 do_pending_interrupt();
1254 /* Another issue is that signalling HEAP-EXHAUSTED error leads
1255 * to running user code at arbitrary places, even in a
1256 * WITHOUT-INTERRUPTS which may lead to a deadlock without
1257 * running out of the heap. So at this point all bets are
1259 if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
1260 corruption_warning_and_maybe_lose
1261 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1262 funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR),
1263 alloc_number(available), alloc_number(requested));
1264 lose("HEAP-EXHAUSTED-ERROR fell through");
1269 gc_find_freeish_pages(page_index_t *restart_page_ptr, long bytes,
1272 page_index_t most_bytes_found_from = 0, most_bytes_found_to = 0;
1273 page_index_t first_page, last_page, restart_page = *restart_page_ptr;
1274 os_vm_size_t nbytes = bytes;
1275 os_vm_size_t nbytes_goal = nbytes;
1276 os_vm_size_t bytes_found = 0;
1277 os_vm_size_t most_bytes_found = 0;
1278 boolean small_object = nbytes < GENCGC_CARD_BYTES;
1279 /* FIXME: assert(free_pages_lock is held); */
1281 if (nbytes_goal < gencgc_alloc_granularity)
1282 nbytes_goal = gencgc_alloc_granularity;
1284 /* Toggled by gc_and_save for heap compaction, normally -1. */
1285 if (gencgc_alloc_start_page != -1) {
1286 restart_page = gencgc_alloc_start_page;
1289 /* FIXME: This is on bytes instead of nbytes pending cleanup of
1290 * long from the interface. */
1291 gc_assert(bytes>=0);
1292 /* Search for a page with at least nbytes of space. We prefer
1293 * not to split small objects on multiple pages, to reduce the
1294 * number of contiguous allocation regions spaning multiple
1295 * pages: this helps avoid excessive conservativism.
1297 * For other objects, we guarantee that they start on their own
1300 first_page = restart_page;
1301 while (first_page < page_table_pages) {
1303 if (page_free_p(first_page)) {
1304 gc_assert(0 == page_table[first_page].bytes_used);
1305 bytes_found = GENCGC_CARD_BYTES;
1306 } else if (small_object &&
1307 (page_table[first_page].allocated == page_type_flag) &&
1308 (page_table[first_page].large_object == 0) &&
1309 (page_table[first_page].gen == gc_alloc_generation) &&
1310 (page_table[first_page].write_protected == 0) &&
1311 (page_table[first_page].dont_move == 0)) {
1312 bytes_found = GENCGC_CARD_BYTES - page_table[first_page].bytes_used;
1313 if (bytes_found < nbytes) {
1314 if (bytes_found > most_bytes_found)
1315 most_bytes_found = bytes_found;
1324 gc_assert(page_table[first_page].write_protected == 0);
1325 for (last_page = first_page+1;
1326 ((last_page < page_table_pages) &&
1327 page_free_p(last_page) &&
1328 (bytes_found < nbytes_goal));
1330 bytes_found += GENCGC_CARD_BYTES;
1331 gc_assert(0 == page_table[last_page].bytes_used);
1332 gc_assert(0 == page_table[last_page].write_protected);
1335 if (bytes_found > most_bytes_found) {
1336 most_bytes_found = bytes_found;
1337 most_bytes_found_from = first_page;
1338 most_bytes_found_to = last_page;
1340 if (bytes_found >= nbytes_goal)
1343 first_page = last_page;
1346 bytes_found = most_bytes_found;
1347 restart_page = first_page + 1;
1349 /* Check for a failure */
1350 if (bytes_found < nbytes) {
1351 gc_assert(restart_page >= page_table_pages);
1352 gc_heap_exhausted_error_or_lose(most_bytes_found, nbytes);
1355 gc_assert(most_bytes_found_to);
1356 *restart_page_ptr = most_bytes_found_from;
1357 return most_bytes_found_to-1;
1360 /* Allocate bytes. All the rest of the special-purpose allocation
1361 * functions will eventually call this */
1364 gc_alloc_with_region(long nbytes,int page_type_flag, struct alloc_region *my_region,
1367 void *new_free_pointer;
1369 if (nbytes>=large_object_size)
1370 return gc_alloc_large(nbytes, page_type_flag, my_region);
1372 /* Check whether there is room in the current alloc region. */
1373 new_free_pointer = my_region->free_pointer + nbytes;
1375 /* fprintf(stderr, "alloc %d bytes from %p to %p\n", nbytes,
1376 my_region->free_pointer, new_free_pointer); */
1378 if (new_free_pointer <= my_region->end_addr) {
1379 /* If so then allocate from the current alloc region. */
1380 void *new_obj = my_region->free_pointer;
1381 my_region->free_pointer = new_free_pointer;
1383 /* Unless a `quick' alloc was requested, check whether the
1384 alloc region is almost empty. */
1386 void_diff(my_region->end_addr,my_region->free_pointer) <= 32) {
1387 /* If so, finished with the current region. */
1388 gc_alloc_update_page_tables(page_type_flag, my_region);
1389 /* Set up a new region. */
1390 gc_alloc_new_region(32 /*bytes*/, page_type_flag, my_region);
1393 return((void *)new_obj);
1396 /* Else not enough free space in the current region: retry with a
1399 gc_alloc_update_page_tables(page_type_flag, my_region);
1400 gc_alloc_new_region(nbytes, page_type_flag, my_region);
1401 return gc_alloc_with_region(nbytes, page_type_flag, my_region,0);
1404 /* these are only used during GC: all allocation from the mutator calls
1405 * alloc() -> gc_alloc_with_region() with the appropriate per-thread
1408 static inline void *
1409 gc_quick_alloc(long nbytes)
1411 return gc_general_alloc(nbytes, BOXED_PAGE_FLAG, ALLOC_QUICK);
1414 static inline void *
1415 gc_quick_alloc_large(long nbytes)
1417 return gc_general_alloc(nbytes, BOXED_PAGE_FLAG ,ALLOC_QUICK);
1420 static inline void *
1421 gc_alloc_unboxed(long nbytes)
1423 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, 0);
1426 static inline void *
1427 gc_quick_alloc_unboxed(long nbytes)
1429 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, ALLOC_QUICK);
1432 static inline void *
1433 gc_quick_alloc_large_unboxed(long nbytes)
1435 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, ALLOC_QUICK);
1439 /* Copy a large boxed object. If the object is in a large object
1440 * region then it is simply promoted, else it is copied. If it's large
1441 * enough then it's copied to a large object region.
1443 * Vectors may have shrunk. If the object is not copied the space
1444 * needs to be reclaimed, and the page_tables corrected. */
1446 copy_large_object(lispobj object, long nwords)
1450 page_index_t first_page;
1452 gc_assert(is_lisp_pointer(object));
1453 gc_assert(from_space_p(object));
1454 gc_assert((nwords & 0x01) == 0);
1457 /* Check whether it's in a large object region. */
1458 first_page = find_page_index((void *)object);
1459 gc_assert(first_page >= 0);
1461 if (page_table[first_page].large_object) {
1463 /* Promote the object. */
1465 unsigned long remaining_bytes;
1466 page_index_t next_page;
1467 unsigned long bytes_freed;
1468 unsigned long old_bytes_used;
1470 /* Note: Any page write-protection must be removed, else a
1471 * later scavenge_newspace may incorrectly not scavenge these
1472 * pages. This would not be necessary if they are added to the
1473 * new areas, but let's do it for them all (they'll probably
1474 * be written anyway?). */
1476 gc_assert(page_table[first_page].region_start_offset == 0);
1478 next_page = first_page;
1479 remaining_bytes = nwords*N_WORD_BYTES;
1480 while (remaining_bytes > GENCGC_CARD_BYTES) {
1481 gc_assert(page_table[next_page].gen == from_space);
1482 gc_assert(page_boxed_p(next_page));
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 gc_assert(page_table[next_page].write_protected == 0);
1490 page_table[next_page].gen = new_space;
1492 remaining_bytes -= GENCGC_CARD_BYTES;
1496 /* Now only one page remains, but the object may have shrunk
1497 * so there may be more unused pages which will be freed. */
1499 /* The object may have shrunk but shouldn't have grown. */
1500 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1502 page_table[next_page].gen = new_space;
1503 gc_assert(page_boxed_p(next_page));
1505 /* Adjust the bytes_used. */
1506 old_bytes_used = page_table[next_page].bytes_used;
1507 page_table[next_page].bytes_used = remaining_bytes;
1509 bytes_freed = old_bytes_used - remaining_bytes;
1511 /* Free any remaining pages; needs care. */
1513 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
1514 (page_table[next_page].gen == from_space) &&
1515 page_boxed_p(next_page) &&
1516 page_table[next_page].large_object &&
1517 (page_table[next_page].region_start_offset ==
1518 npage_bytes(next_page - first_page))) {
1519 /* Checks out OK, free the page. Don't need to bother zeroing
1520 * pages as this should have been done before shrinking the
1521 * object. These pages shouldn't be write-protected as they
1522 * should be zero filled. */
1523 gc_assert(page_table[next_page].write_protected == 0);
1525 old_bytes_used = page_table[next_page].bytes_used;
1526 page_table[next_page].allocated = FREE_PAGE_FLAG;
1527 page_table[next_page].bytes_used = 0;
1528 bytes_freed += old_bytes_used;
1532 generations[from_space].bytes_allocated -= N_WORD_BYTES*nwords
1534 generations[new_space].bytes_allocated += N_WORD_BYTES*nwords;
1535 bytes_allocated -= bytes_freed;
1537 /* Add the region to the new_areas if requested. */
1538 add_new_area(first_page,0,nwords*N_WORD_BYTES);
1542 /* Get tag of object. */
1543 tag = lowtag_of(object);
1545 /* Allocate space. */
1546 new = gc_quick_alloc_large(nwords*N_WORD_BYTES);
1548 memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1550 /* Return Lisp pointer of new object. */
1551 return ((lispobj) new) | tag;
1555 /* to copy unboxed objects */
1557 copy_unboxed_object(lispobj object, long nwords)
1562 gc_assert(is_lisp_pointer(object));
1563 gc_assert(from_space_p(object));
1564 gc_assert((nwords & 0x01) == 0);
1566 /* Get tag of object. */
1567 tag = lowtag_of(object);
1569 /* Allocate space. */
1570 new = gc_quick_alloc_unboxed(nwords*N_WORD_BYTES);
1572 memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1574 /* Return Lisp pointer of new object. */
1575 return ((lispobj) new) | tag;
1578 /* to copy large unboxed objects
1580 * If the object is in a large object region then it is simply
1581 * promoted, else it is copied. If it's large enough then it's copied
1582 * to a large object region.
1584 * Bignums and vectors may have shrunk. If the object is not copied
1585 * the space needs to be reclaimed, and the page_tables corrected.
1587 * KLUDGE: There's a lot of cut-and-paste duplication between this
1588 * function and copy_large_object(..). -- WHN 20000619 */
1590 copy_large_unboxed_object(lispobj object, long nwords)
1594 page_index_t first_page;
1596 gc_assert(is_lisp_pointer(object));
1597 gc_assert(from_space_p(object));
1598 gc_assert((nwords & 0x01) == 0);
1600 if ((nwords > 1024*1024) && gencgc_verbose) {
1601 FSHOW((stderr, "/copy_large_unboxed_object: %d bytes\n",
1602 nwords*N_WORD_BYTES));
1605 /* Check whether it's a large object. */
1606 first_page = find_page_index((void *)object);
1607 gc_assert(first_page >= 0);
1609 if (page_table[first_page].large_object) {
1610 /* Promote the object. Note: Unboxed objects may have been
1611 * allocated to a BOXED region so it may be necessary to
1612 * change the region to UNBOXED. */
1613 unsigned long remaining_bytes;
1614 page_index_t next_page;
1615 unsigned long bytes_freed;
1616 unsigned long old_bytes_used;
1618 gc_assert(page_table[first_page].region_start_offset == 0);
1620 next_page = first_page;
1621 remaining_bytes = nwords*N_WORD_BYTES;
1622 while (remaining_bytes > GENCGC_CARD_BYTES) {
1623 gc_assert(page_table[next_page].gen == from_space);
1624 gc_assert(page_allocated_no_region_p(next_page));
1625 gc_assert(page_table[next_page].large_object);
1626 gc_assert(page_table[next_page].region_start_offset ==
1627 npage_bytes(next_page-first_page));
1628 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
1630 page_table[next_page].gen = new_space;
1631 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1632 remaining_bytes -= GENCGC_CARD_BYTES;
1636 /* Now only one page remains, but the object may have shrunk so
1637 * there may be more unused pages which will be freed. */
1639 /* Object may have shrunk but shouldn't have grown - check. */
1640 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1642 page_table[next_page].gen = new_space;
1643 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1645 /* Adjust the bytes_used. */
1646 old_bytes_used = page_table[next_page].bytes_used;
1647 page_table[next_page].bytes_used = remaining_bytes;
1649 bytes_freed = old_bytes_used - remaining_bytes;
1651 /* Free any remaining pages; needs care. */
1653 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
1654 (page_table[next_page].gen == from_space) &&
1655 page_allocated_no_region_p(next_page) &&
1656 page_table[next_page].large_object &&
1657 (page_table[next_page].region_start_offset ==
1658 npage_bytes(next_page - first_page))) {
1659 /* Checks out OK, free the page. Don't need to both zeroing
1660 * pages as this should have been done before shrinking the
1661 * object. These pages shouldn't be write-protected, even if
1662 * boxed they should be zero filled. */
1663 gc_assert(page_table[next_page].write_protected == 0);
1665 old_bytes_used = page_table[next_page].bytes_used;
1666 page_table[next_page].allocated = FREE_PAGE_FLAG;
1667 page_table[next_page].bytes_used = 0;
1668 bytes_freed += old_bytes_used;
1672 if ((bytes_freed > 0) && gencgc_verbose) {
1674 "/copy_large_unboxed bytes_freed=%d\n",
1678 generations[from_space].bytes_allocated -=
1679 nwords*N_WORD_BYTES + bytes_freed;
1680 generations[new_space].bytes_allocated += nwords*N_WORD_BYTES;
1681 bytes_allocated -= bytes_freed;
1686 /* Get tag of object. */
1687 tag = lowtag_of(object);
1689 /* Allocate space. */
1690 new = gc_quick_alloc_large_unboxed(nwords*N_WORD_BYTES);
1692 /* Copy the object. */
1693 memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1695 /* Return Lisp pointer of new object. */
1696 return ((lispobj) new) | tag;
1705 * code and code-related objects
1708 static lispobj trans_fun_header(lispobj object);
1709 static lispobj trans_boxed(lispobj object);
1712 /* Scan a x86 compiled code object, looking for possible fixups that
1713 * have been missed after a move.
1715 * Two types of fixups are needed:
1716 * 1. Absolute fixups to within the code object.
1717 * 2. Relative fixups to outside the code object.
1719 * Currently only absolute fixups to the constant vector, or to the
1720 * code area are checked. */
1722 sniff_code_object(struct code *code, unsigned long displacement)
1724 #ifdef LISP_FEATURE_X86
1725 long nheader_words, ncode_words, nwords;
1727 void *constants_start_addr = NULL, *constants_end_addr;
1728 void *code_start_addr, *code_end_addr;
1729 int fixup_found = 0;
1731 if (!check_code_fixups)
1734 FSHOW((stderr, "/sniffing code: %p, %lu\n", code, displacement));
1736 ncode_words = fixnum_value(code->code_size);
1737 nheader_words = HeaderValue(*(lispobj *)code);
1738 nwords = ncode_words + nheader_words;
1740 constants_start_addr = (void *)code + 5*N_WORD_BYTES;
1741 constants_end_addr = (void *)code + nheader_words*N_WORD_BYTES;
1742 code_start_addr = (void *)code + nheader_words*N_WORD_BYTES;
1743 code_end_addr = (void *)code + nwords*N_WORD_BYTES;
1745 /* Work through the unboxed code. */
1746 for (p = code_start_addr; p < code_end_addr; p++) {
1747 void *data = *(void **)p;
1748 unsigned d1 = *((unsigned char *)p - 1);
1749 unsigned d2 = *((unsigned char *)p - 2);
1750 unsigned d3 = *((unsigned char *)p - 3);
1751 unsigned d4 = *((unsigned char *)p - 4);
1753 unsigned d5 = *((unsigned char *)p - 5);
1754 unsigned d6 = *((unsigned char *)p - 6);
1757 /* Check for code references. */
1758 /* Check for a 32 bit word that looks like an absolute
1759 reference to within the code adea of the code object. */
1760 if ((data >= (code_start_addr-displacement))
1761 && (data < (code_end_addr-displacement))) {
1762 /* function header */
1764 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) ==
1766 /* Skip the function header */
1770 /* the case of PUSH imm32 */
1774 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1775 p, d6, d5, d4, d3, d2, d1, data));
1776 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1778 /* the case of MOV [reg-8],imm32 */
1780 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1781 || d2==0x45 || d2==0x46 || d2==0x47)
1785 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1786 p, d6, d5, d4, d3, d2, d1, data));
1787 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1789 /* the case of LEA reg,[disp32] */
1790 if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1793 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1794 p, d6, d5, d4, d3, d2, d1, data));
1795 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1799 /* Check for constant references. */
1800 /* Check for a 32 bit word that looks like an absolute
1801 reference to within the constant vector. Constant references
1803 if ((data >= (constants_start_addr-displacement))
1804 && (data < (constants_end_addr-displacement))
1805 && (((unsigned)data & 0x3) == 0)) {
1810 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1811 p, d6, d5, d4, d3, d2, d1, data));
1812 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1815 /* the case of MOV m32,EAX */
1819 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1820 p, d6, d5, d4, d3, d2, d1, data));
1821 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1824 /* the case of CMP m32,imm32 */
1825 if ((d1 == 0x3d) && (d2 == 0x81)) {
1828 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1829 p, d6, d5, d4, d3, d2, d1, data));
1831 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1834 /* Check for a mod=00, r/m=101 byte. */
1835 if ((d1 & 0xc7) == 5) {
1840 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1841 p, d6, d5, d4, d3, d2, d1, data));
1842 FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1844 /* the case of CMP reg32,m32 */
1848 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1849 p, d6, d5, d4, d3, d2, d1, data));
1850 FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1852 /* the case of MOV m32,reg32 */
1856 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1857 p, d6, d5, d4, d3, d2, d1, data));
1858 FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1860 /* the case of MOV reg32,m32 */
1864 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1865 p, d6, d5, d4, d3, d2, d1, data));
1866 FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1868 /* the case of LEA reg32,m32 */
1872 "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1873 p, d6, d5, d4, d3, d2, d1, data));
1874 FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1880 /* If anything was found, print some information on the code
1884 "/compiled code object at %x: header words = %d, code words = %d\n",
1885 code, nheader_words, ncode_words));
1887 "/const start = %x, end = %x\n",
1888 constants_start_addr, constants_end_addr));
1890 "/code start = %x, end = %x\n",
1891 code_start_addr, code_end_addr));
1897 gencgc_apply_code_fixups(struct code *old_code, struct code *new_code)
1899 /* x86-64 uses pc-relative addressing instead of this kludge */
1900 #ifndef LISP_FEATURE_X86_64
1901 long nheader_words, ncode_words, nwords;
1902 void *constants_start_addr, *constants_end_addr;
1903 void *code_start_addr, *code_end_addr;
1904 lispobj fixups = NIL;
1905 unsigned long displacement =
1906 (unsigned long)new_code - (unsigned long)old_code;
1907 struct vector *fixups_vector;
1909 ncode_words = fixnum_value(new_code->code_size);
1910 nheader_words = HeaderValue(*(lispobj *)new_code);
1911 nwords = ncode_words + nheader_words;
1913 "/compiled code object at %x: header words = %d, code words = %d\n",
1914 new_code, nheader_words, ncode_words)); */
1915 constants_start_addr = (void *)new_code + 5*N_WORD_BYTES;
1916 constants_end_addr = (void *)new_code + nheader_words*N_WORD_BYTES;
1917 code_start_addr = (void *)new_code + nheader_words*N_WORD_BYTES;
1918 code_end_addr = (void *)new_code + nwords*N_WORD_BYTES;
1921 "/const start = %x, end = %x\n",
1922 constants_start_addr,constants_end_addr));
1924 "/code start = %x; end = %x\n",
1925 code_start_addr,code_end_addr));
1928 /* The first constant should be a pointer to the fixups for this
1929 code objects. Check. */
1930 fixups = new_code->constants[0];
1932 /* It will be 0 or the unbound-marker if there are no fixups (as
1933 * will be the case if the code object has been purified, for
1934 * example) and will be an other pointer if it is valid. */
1935 if ((fixups == 0) || (fixups == UNBOUND_MARKER_WIDETAG) ||
1936 !is_lisp_pointer(fixups)) {
1937 /* Check for possible errors. */
1938 if (check_code_fixups)
1939 sniff_code_object(new_code, displacement);
1944 fixups_vector = (struct vector *)native_pointer(fixups);
1946 /* Could be pointing to a forwarding pointer. */
1947 /* FIXME is this always in from_space? if so, could replace this code with
1948 * forwarding_pointer_p/forwarding_pointer_value */
1949 if (is_lisp_pointer(fixups) &&
1950 (find_page_index((void*)fixups_vector) != -1) &&
1951 (fixups_vector->header == 0x01)) {
1952 /* If so, then follow it. */
1953 /*SHOW("following pointer to a forwarding pointer");*/
1955 (struct vector *)native_pointer((lispobj)fixups_vector->length);
1958 /*SHOW("got fixups");*/
1960 if (widetag_of(fixups_vector->header) == SIMPLE_ARRAY_WORD_WIDETAG) {
1961 /* Got the fixups for the code block. Now work through the vector,
1962 and apply a fixup at each address. */
1963 long length = fixnum_value(fixups_vector->length);
1965 for (i = 0; i < length; i++) {
1966 unsigned long offset = fixups_vector->data[i];
1967 /* Now check the current value of offset. */
1968 unsigned long old_value =
1969 *(unsigned long *)((unsigned long)code_start_addr + offset);
1971 /* If it's within the old_code object then it must be an
1972 * absolute fixup (relative ones are not saved) */
1973 if ((old_value >= (unsigned long)old_code)
1974 && (old_value < ((unsigned long)old_code
1975 + nwords*N_WORD_BYTES)))
1976 /* So add the dispacement. */
1977 *(unsigned long *)((unsigned long)code_start_addr + offset) =
1978 old_value + displacement;
1980 /* It is outside the old code object so it must be a
1981 * relative fixup (absolute fixups are not saved). So
1982 * subtract the displacement. */
1983 *(unsigned long *)((unsigned long)code_start_addr + offset) =
1984 old_value - displacement;
1987 /* This used to just print a note to stderr, but a bogus fixup seems to
1988 * indicate real heap corruption, so a hard hailure is in order. */
1989 lose("fixup vector %p has a bad widetag: %d\n",
1990 fixups_vector, widetag_of(fixups_vector->header));
1993 /* Check for possible errors. */
1994 if (check_code_fixups) {
1995 sniff_code_object(new_code,displacement);
2002 trans_boxed_large(lispobj object)
2005 unsigned long length;
2007 gc_assert(is_lisp_pointer(object));
2009 header = *((lispobj *) native_pointer(object));
2010 length = HeaderValue(header) + 1;
2011 length = CEILING(length, 2);
2013 return copy_large_object(object, length);
2016 /* Doesn't seem to be used, delete it after the grace period. */
2019 trans_unboxed_large(lispobj object)
2022 unsigned long length;
2024 gc_assert(is_lisp_pointer(object));
2026 header = *((lispobj *) native_pointer(object));
2027 length = HeaderValue(header) + 1;
2028 length = CEILING(length, 2);
2030 return copy_large_unboxed_object(object, length);
2038 /* XX This is a hack adapted from cgc.c. These don't work too
2039 * efficiently with the gencgc as a list of the weak pointers is
2040 * maintained within the objects which causes writes to the pages. A
2041 * limited attempt is made to avoid unnecessary writes, but this needs
2043 #define WEAK_POINTER_NWORDS \
2044 CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
2047 scav_weak_pointer(lispobj *where, lispobj object)
2049 /* Since we overwrite the 'next' field, we have to make
2050 * sure not to do so for pointers already in the list.
2051 * Instead of searching the list of weak_pointers each
2052 * time, we ensure that next is always NULL when the weak
2053 * pointer isn't in the list, and not NULL otherwise.
2054 * Since we can't use NULL to denote end of list, we
2055 * use a pointer back to the same weak_pointer.
2057 struct weak_pointer * wp = (struct weak_pointer*)where;
2059 if (NULL == wp->next) {
2060 wp->next = weak_pointers;
2062 if (NULL == wp->next)
2066 /* Do not let GC scavenge the value slot of the weak pointer.
2067 * (That is why it is a weak pointer.) */
2069 return WEAK_POINTER_NWORDS;
2074 search_read_only_space(void *pointer)
2076 lispobj *start = (lispobj *) READ_ONLY_SPACE_START;
2077 lispobj *end = (lispobj *) SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
2078 if ((pointer < (void *)start) || (pointer >= (void *)end))
2080 return (gc_search_space(start,
2081 (((lispobj *)pointer)+2)-start,
2082 (lispobj *) pointer));
2086 search_static_space(void *pointer)
2088 lispobj *start = (lispobj *)STATIC_SPACE_START;
2089 lispobj *end = (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
2090 if ((pointer < (void *)start) || (pointer >= (void *)end))
2092 return (gc_search_space(start,
2093 (((lispobj *)pointer)+2)-start,
2094 (lispobj *) pointer));
2097 /* a faster version for searching the dynamic space. This will work even
2098 * if the object is in a current allocation region. */
2100 search_dynamic_space(void *pointer)
2102 page_index_t page_index = find_page_index(pointer);
2105 /* The address may be invalid, so do some checks. */
2106 if ((page_index == -1) || page_free_p(page_index))
2108 start = (lispobj *)page_region_start(page_index);
2109 return (gc_search_space(start,
2110 (((lispobj *)pointer)+2)-start,
2111 (lispobj *)pointer));
2114 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2116 /* Is there any possibility that pointer is a valid Lisp object
2117 * reference, and/or something else (e.g. subroutine call return
2118 * address) which should prevent us from moving the referred-to thing?
2119 * This is called from preserve_pointers() */
2121 possibly_valid_dynamic_space_pointer(lispobj *pointer)
2123 lispobj *start_addr;
2125 /* Find the object start address. */
2126 if ((start_addr = search_dynamic_space(pointer)) == NULL) {
2130 return looks_like_valid_lisp_pointer_p(pointer, start_addr);
2133 #endif // defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2135 /* Adjust large bignum and vector objects. This will adjust the
2136 * allocated region if the size has shrunk, and move unboxed objects
2137 * into unboxed pages. The pages are not promoted here, and the
2138 * promoted region is not added to the new_regions; this is really
2139 * only designed to be called from preserve_pointer(). Shouldn't fail
2140 * if this is missed, just may delay the moving of objects to unboxed
2141 * pages, and the freeing of pages. */
2143 maybe_adjust_large_object(lispobj *where)
2145 page_index_t first_page;
2146 page_index_t next_page;
2149 unsigned long remaining_bytes;
2150 unsigned long bytes_freed;
2151 unsigned long old_bytes_used;
2155 /* Check whether it's a vector or bignum object. */
2156 switch (widetag_of(where[0])) {
2157 case SIMPLE_VECTOR_WIDETAG:
2158 boxed = BOXED_PAGE_FLAG;
2160 case BIGNUM_WIDETAG:
2161 case SIMPLE_BASE_STRING_WIDETAG:
2162 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2163 case SIMPLE_CHARACTER_STRING_WIDETAG:
2165 case SIMPLE_BIT_VECTOR_WIDETAG:
2166 case SIMPLE_ARRAY_NIL_WIDETAG:
2167 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2168 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2169 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2170 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2171 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2172 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2174 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
2176 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2177 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2178 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2179 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2181 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2182 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2184 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2185 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2187 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2188 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2191 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
2193 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2194 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2196 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2197 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2199 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2200 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2201 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2202 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2204 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2205 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2207 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2208 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2210 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2211 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2213 boxed = UNBOXED_PAGE_FLAG;
2219 /* Find its current size. */
2220 nwords = (sizetab[widetag_of(where[0])])(where);
2222 first_page = find_page_index((void *)where);
2223 gc_assert(first_page >= 0);
2225 /* Note: Any page write-protection must be removed, else a later
2226 * scavenge_newspace may incorrectly not scavenge these pages.
2227 * This would not be necessary if they are added to the new areas,
2228 * but lets do it for them all (they'll probably be written
2231 gc_assert(page_table[first_page].region_start_offset == 0);
2233 next_page = first_page;
2234 remaining_bytes = nwords*N_WORD_BYTES;
2235 while (remaining_bytes > GENCGC_CARD_BYTES) {
2236 gc_assert(page_table[next_page].gen == from_space);
2237 gc_assert(page_allocated_no_region_p(next_page));
2238 gc_assert(page_table[next_page].large_object);
2239 gc_assert(page_table[next_page].region_start_offset ==
2240 npage_bytes(next_page-first_page));
2241 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
2243 page_table[next_page].allocated = boxed;
2245 /* Shouldn't be write-protected at this stage. Essential that the
2247 gc_assert(!page_table[next_page].write_protected);
2248 remaining_bytes -= GENCGC_CARD_BYTES;
2252 /* Now only one page remains, but the object may have shrunk so
2253 * there may be more unused pages which will be freed. */
2255 /* Object may have shrunk but shouldn't have grown - check. */
2256 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2258 page_table[next_page].allocated = boxed;
2259 gc_assert(page_table[next_page].allocated ==
2260 page_table[first_page].allocated);
2262 /* Adjust the bytes_used. */
2263 old_bytes_used = page_table[next_page].bytes_used;
2264 page_table[next_page].bytes_used = remaining_bytes;
2266 bytes_freed = old_bytes_used - remaining_bytes;
2268 /* Free any remaining pages; needs care. */
2270 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
2271 (page_table[next_page].gen == from_space) &&
2272 page_allocated_no_region_p(next_page) &&
2273 page_table[next_page].large_object &&
2274 (page_table[next_page].region_start_offset ==
2275 npage_bytes(next_page - first_page))) {
2276 /* It checks out OK, free the page. We don't need to both zeroing
2277 * pages as this should have been done before shrinking the
2278 * object. These pages shouldn't be write protected as they
2279 * should be zero filled. */
2280 gc_assert(page_table[next_page].write_protected == 0);
2282 old_bytes_used = page_table[next_page].bytes_used;
2283 page_table[next_page].allocated = FREE_PAGE_FLAG;
2284 page_table[next_page].bytes_used = 0;
2285 bytes_freed += old_bytes_used;
2289 if ((bytes_freed > 0) && gencgc_verbose) {
2291 "/maybe_adjust_large_object() freed %d\n",
2295 generations[from_space].bytes_allocated -= bytes_freed;
2296 bytes_allocated -= bytes_freed;
2301 /* Take a possible pointer to a Lisp object and mark its page in the
2302 * page_table so that it will not be relocated during a GC.
2304 * This involves locating the page it points to, then backing up to
2305 * the start of its region, then marking all pages dont_move from there
2306 * up to the first page that's not full or has a different generation
2308 * It is assumed that all the page static flags have been cleared at
2309 * the start of a GC.
2311 * It is also assumed that the current gc_alloc() region has been
2312 * flushed and the tables updated. */
2315 preserve_pointer(void *addr)
2317 page_index_t addr_page_index = find_page_index(addr);
2318 page_index_t first_page;
2320 unsigned int region_allocation;
2322 /* quick check 1: Address is quite likely to have been invalid. */
2323 if ((addr_page_index == -1)
2324 || page_free_p(addr_page_index)
2325 || (page_table[addr_page_index].bytes_used == 0)
2326 || (page_table[addr_page_index].gen != from_space)
2327 /* Skip if already marked dont_move. */
2328 || (page_table[addr_page_index].dont_move != 0))
2330 gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2331 /* (Now that we know that addr_page_index is in range, it's
2332 * safe to index into page_table[] with it.) */
2333 region_allocation = page_table[addr_page_index].allocated;
2335 /* quick check 2: Check the offset within the page.
2338 if (((unsigned long)addr & (GENCGC_CARD_BYTES - 1)) >
2339 page_table[addr_page_index].bytes_used)
2342 /* Filter out anything which can't be a pointer to a Lisp object
2343 * (or, as a special case which also requires dont_move, a return
2344 * address referring to something in a CodeObject). This is
2345 * expensive but important, since it vastly reduces the
2346 * probability that random garbage will be bogusly interpreted as
2347 * a pointer which prevents a page from moving.
2349 * This only needs to happen on x86oids, where this is used for
2350 * conservative roots. Non-x86oid systems only ever call this
2351 * function on known-valid lisp objects. */
2352 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2353 if (!(code_page_p(addr_page_index)
2354 || (is_lisp_pointer((lispobj)addr) &&
2355 possibly_valid_dynamic_space_pointer(addr))))
2359 /* Find the beginning of the region. Note that there may be
2360 * objects in the region preceding the one that we were passed a
2361 * pointer to: if this is the case, we will write-protect all the
2362 * previous objects' pages too. */
2365 /* I think this'd work just as well, but without the assertions.
2366 * -dan 2004.01.01 */
2367 first_page = find_page_index(page_region_start(addr_page_index))
2369 first_page = addr_page_index;
2370 while (page_table[first_page].region_start_offset != 0) {
2372 /* Do some checks. */
2373 gc_assert(page_table[first_page].bytes_used == GENCGC_CARD_BYTES);
2374 gc_assert(page_table[first_page].gen == from_space);
2375 gc_assert(page_table[first_page].allocated == region_allocation);
2379 /* Adjust any large objects before promotion as they won't be
2380 * copied after promotion. */
2381 if (page_table[first_page].large_object) {
2382 maybe_adjust_large_object(page_address(first_page));
2383 /* If a large object has shrunk then addr may now point to a
2384 * free area in which case it's ignored here. Note it gets
2385 * through the valid pointer test above because the tail looks
2387 if (page_free_p(addr_page_index)
2388 || (page_table[addr_page_index].bytes_used == 0)
2389 /* Check the offset within the page. */
2390 || (((unsigned long)addr & (GENCGC_CARD_BYTES - 1))
2391 > page_table[addr_page_index].bytes_used)) {
2393 "weird? ignore ptr 0x%x to freed area of large object\n",
2397 /* It may have moved to unboxed pages. */
2398 region_allocation = page_table[first_page].allocated;
2401 /* Now work forward until the end of this contiguous area is found,
2402 * marking all pages as dont_move. */
2403 for (i = first_page; ;i++) {
2404 gc_assert(page_table[i].allocated == region_allocation);
2406 /* Mark the page static. */
2407 page_table[i].dont_move = 1;
2409 /* Move the page to the new_space. XX I'd rather not do this
2410 * but the GC logic is not quite able to copy with the static
2411 * pages remaining in the from space. This also requires the
2412 * generation bytes_allocated counters be updated. */
2413 page_table[i].gen = new_space;
2414 generations[new_space].bytes_allocated += page_table[i].bytes_used;
2415 generations[from_space].bytes_allocated -= page_table[i].bytes_used;
2417 /* It is essential that the pages are not write protected as
2418 * they may have pointers into the old-space which need
2419 * scavenging. They shouldn't be write protected at this
2421 gc_assert(!page_table[i].write_protected);
2423 /* Check whether this is the last page in this contiguous block.. */
2424 if ((page_table[i].bytes_used < GENCGC_CARD_BYTES)
2425 /* ..or it is CARD_BYTES and is the last in the block */
2427 || (page_table[i+1].bytes_used == 0) /* next page free */
2428 || (page_table[i+1].gen != from_space) /* diff. gen */
2429 || (page_table[i+1].region_start_offset == 0))
2433 /* Check that the page is now static. */
2434 gc_assert(page_table[addr_page_index].dont_move != 0);
2437 /* If the given page is not write-protected, then scan it for pointers
2438 * to younger generations or the top temp. generation, if no
2439 * suspicious pointers are found then the page is write-protected.
2441 * Care is taken to check for pointers to the current gc_alloc()
2442 * region if it is a younger generation or the temp. generation. This
2443 * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2444 * the gc_alloc_generation does not need to be checked as this is only
2445 * called from scavenge_generation() when the gc_alloc generation is
2446 * younger, so it just checks if there is a pointer to the current
2449 * We return 1 if the page was write-protected, else 0. */
2451 update_page_write_prot(page_index_t page)
2453 generation_index_t gen = page_table[page].gen;
2456 void **page_addr = (void **)page_address(page);
2457 long num_words = page_table[page].bytes_used / N_WORD_BYTES;
2459 /* Shouldn't be a free page. */
2460 gc_assert(page_allocated_p(page));
2461 gc_assert(page_table[page].bytes_used != 0);
2463 /* Skip if it's already write-protected, pinned, or unboxed */
2464 if (page_table[page].write_protected
2465 /* FIXME: What's the reason for not write-protecting pinned pages? */
2466 || page_table[page].dont_move
2467 || page_unboxed_p(page))
2470 /* Scan the page for pointers to younger generations or the
2471 * top temp. generation. */
2473 for (j = 0; j < num_words; j++) {
2474 void *ptr = *(page_addr+j);
2475 page_index_t index = find_page_index(ptr);
2477 /* Check that it's in the dynamic space */
2479 if (/* Does it point to a younger or the temp. generation? */
2480 (page_allocated_p(index)
2481 && (page_table[index].bytes_used != 0)
2482 && ((page_table[index].gen < gen)
2483 || (page_table[index].gen == SCRATCH_GENERATION)))
2485 /* Or does it point within a current gc_alloc() region? */
2486 || ((boxed_region.start_addr <= ptr)
2487 && (ptr <= boxed_region.free_pointer))
2488 || ((unboxed_region.start_addr <= ptr)
2489 && (ptr <= unboxed_region.free_pointer))) {
2496 /* Write-protect the page. */
2497 /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2499 os_protect((void *)page_addr,
2501 OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2503 /* Note the page as protected in the page tables. */
2504 page_table[page].write_protected = 1;
2510 /* Scavenge all generations from FROM to TO, inclusive, except for
2511 * new_space which needs special handling, as new objects may be
2512 * added which are not checked here - use scavenge_newspace generation.
2514 * Write-protected pages should not have any pointers to the
2515 * from_space so do need scavenging; thus write-protected pages are
2516 * not always scavenged. There is some code to check that these pages
2517 * are not written; but to check fully the write-protected pages need
2518 * to be scavenged by disabling the code to skip them.
2520 * Under the current scheme when a generation is GCed the younger
2521 * generations will be empty. So, when a generation is being GCed it
2522 * is only necessary to scavenge the older generations for pointers
2523 * not the younger. So a page that does not have pointers to younger
2524 * generations does not need to be scavenged.
2526 * The write-protection can be used to note pages that don't have
2527 * pointers to younger pages. But pages can be written without having
2528 * pointers to younger generations. After the pages are scavenged here
2529 * they can be scanned for pointers to younger generations and if
2530 * there are none the page can be write-protected.
2532 * One complication is when the newspace is the top temp. generation.
2534 * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2535 * that none were written, which they shouldn't be as they should have
2536 * no pointers to younger generations. This breaks down for weak
2537 * pointers as the objects contain a link to the next and are written
2538 * if a weak pointer is scavenged. Still it's a useful check. */
2540 scavenge_generations(generation_index_t from, generation_index_t to)
2543 page_index_t num_wp = 0;
2547 /* Clear the write_protected_cleared flags on all pages. */
2548 for (i = 0; i < page_table_pages; i++)
2549 page_table[i].write_protected_cleared = 0;
2552 for (i = 0; i < last_free_page; i++) {
2553 generation_index_t generation = page_table[i].gen;
2555 && (page_table[i].bytes_used != 0)
2556 && (generation != new_space)
2557 && (generation >= from)
2558 && (generation <= to)) {
2559 page_index_t last_page,j;
2560 int write_protected=1;
2562 /* This should be the start of a region */
2563 gc_assert(page_table[i].region_start_offset == 0);
2565 /* Now work forward until the end of the region */
2566 for (last_page = i; ; last_page++) {
2568 write_protected && page_table[last_page].write_protected;
2569 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
2570 /* Or it is CARD_BYTES and is the last in the block */
2571 || (!page_boxed_p(last_page+1))
2572 || (page_table[last_page+1].bytes_used == 0)
2573 || (page_table[last_page+1].gen != generation)
2574 || (page_table[last_page+1].region_start_offset == 0))
2577 if (!write_protected) {
2578 scavenge(page_address(i),
2579 ((unsigned long)(page_table[last_page].bytes_used
2580 + npage_bytes(last_page-i)))
2583 /* Now scan the pages and write protect those that
2584 * don't have pointers to younger generations. */
2585 if (enable_page_protection) {
2586 for (j = i; j <= last_page; j++) {
2587 num_wp += update_page_write_prot(j);
2590 if ((gencgc_verbose > 1) && (num_wp != 0)) {
2592 "/write protected %d pages within generation %d\n",
2593 num_wp, generation));
2601 /* Check that none of the write_protected pages in this generation
2602 * have been written to. */
2603 for (i = 0; i < page_table_pages; i++) {
2604 if (page_allocated_p(i)
2605 && (page_table[i].bytes_used != 0)
2606 && (page_table[i].gen == generation)
2607 && (page_table[i].write_protected_cleared != 0)) {
2608 FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2610 "/page bytes_used=%d region_start_offset=%lu dont_move=%d\n",
2611 page_table[i].bytes_used,
2612 page_table[i].region_start_offset,
2613 page_table[i].dont_move));
2614 lose("write to protected page %d in scavenge_generation()\n", i);
2621 /* Scavenge a newspace generation. As it is scavenged new objects may
2622 * be allocated to it; these will also need to be scavenged. This
2623 * repeats until there are no more objects unscavenged in the
2624 * newspace generation.
2626 * To help improve the efficiency, areas written are recorded by
2627 * gc_alloc() and only these scavenged. Sometimes a little more will be
2628 * scavenged, but this causes no harm. An easy check is done that the
2629 * scavenged bytes equals the number allocated in the previous
2632 * Write-protected pages are not scanned except if they are marked
2633 * dont_move in which case they may have been promoted and still have
2634 * pointers to the from space.
2636 * Write-protected pages could potentially be written by alloc however
2637 * to avoid having to handle re-scavenging of write-protected pages
2638 * gc_alloc() does not write to write-protected pages.
2640 * New areas of objects allocated are recorded alternatively in the two
2641 * new_areas arrays below. */
2642 static struct new_area new_areas_1[NUM_NEW_AREAS];
2643 static struct new_area new_areas_2[NUM_NEW_AREAS];
2645 /* Do one full scan of the new space generation. This is not enough to
2646 * complete the job as new objects may be added to the generation in
2647 * the process which are not scavenged. */
2649 scavenge_newspace_generation_one_scan(generation_index_t generation)
2654 "/starting one full scan of newspace generation %d\n",
2656 for (i = 0; i < last_free_page; i++) {
2657 /* Note that this skips over open regions when it encounters them. */
2659 && (page_table[i].bytes_used != 0)
2660 && (page_table[i].gen == generation)
2661 && ((page_table[i].write_protected == 0)
2662 /* (This may be redundant as write_protected is now
2663 * cleared before promotion.) */
2664 || (page_table[i].dont_move == 1))) {
2665 page_index_t last_page;
2668 /* The scavenge will start at the region_start_offset of
2671 * We need to find the full extent of this contiguous
2672 * block in case objects span pages.
2674 * Now work forward until the end of this contiguous area
2675 * is found. A small area is preferred as there is a
2676 * better chance of its pages being write-protected. */
2677 for (last_page = i; ;last_page++) {
2678 /* If all pages are write-protected and movable,
2679 * then no need to scavenge */
2680 all_wp=all_wp && page_table[last_page].write_protected &&
2681 !page_table[last_page].dont_move;
2683 /* Check whether this is the last page in this
2684 * contiguous block */
2685 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
2686 /* Or it is CARD_BYTES and is the last in the block */
2687 || (!page_boxed_p(last_page+1))
2688 || (page_table[last_page+1].bytes_used == 0)
2689 || (page_table[last_page+1].gen != generation)
2690 || (page_table[last_page+1].region_start_offset == 0))
2694 /* Do a limited check for write-protected pages. */
2696 long nwords = (((unsigned long)
2697 (page_table[last_page].bytes_used
2698 + npage_bytes(last_page-i)
2699 + page_table[i].region_start_offset))
2701 new_areas_ignore_page = last_page;
2703 scavenge(page_region_start(i), nwords);
2710 "/done with one full scan of newspace generation %d\n",
2714 /* Do a complete scavenge of the newspace generation. */
2716 scavenge_newspace_generation(generation_index_t generation)
2720 /* the new_areas array currently being written to by gc_alloc() */
2721 struct new_area (*current_new_areas)[] = &new_areas_1;
2722 long current_new_areas_index;
2724 /* the new_areas created by the previous scavenge cycle */
2725 struct new_area (*previous_new_areas)[] = NULL;
2726 long previous_new_areas_index;
2728 /* Flush the current regions updating the tables. */
2729 gc_alloc_update_all_page_tables();
2731 /* Turn on the recording of new areas by gc_alloc(). */
2732 new_areas = current_new_areas;
2733 new_areas_index = 0;
2735 /* Don't need to record new areas that get scavenged anyway during
2736 * scavenge_newspace_generation_one_scan. */
2737 record_new_objects = 1;
2739 /* Start with a full scavenge. */
2740 scavenge_newspace_generation_one_scan(generation);
2742 /* Record all new areas now. */
2743 record_new_objects = 2;
2745 /* Give a chance to weak hash tables to make other objects live.
2746 * FIXME: The algorithm implemented here for weak hash table gcing
2747 * is O(W^2+N) as Bruno Haible warns in
2748 * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
2749 * see "Implementation 2". */
2750 scav_weak_hash_tables();
2752 /* Flush the current regions updating the tables. */
2753 gc_alloc_update_all_page_tables();
2755 /* Grab new_areas_index. */
2756 current_new_areas_index = new_areas_index;
2759 "The first scan is finished; current_new_areas_index=%d.\n",
2760 current_new_areas_index));*/
2762 while (current_new_areas_index > 0) {
2763 /* Move the current to the previous new areas */
2764 previous_new_areas = current_new_areas;
2765 previous_new_areas_index = current_new_areas_index;
2767 /* Scavenge all the areas in previous new areas. Any new areas
2768 * allocated are saved in current_new_areas. */
2770 /* Allocate an array for current_new_areas; alternating between
2771 * new_areas_1 and 2 */
2772 if (previous_new_areas == &new_areas_1)
2773 current_new_areas = &new_areas_2;
2775 current_new_areas = &new_areas_1;
2777 /* Set up for gc_alloc(). */
2778 new_areas = current_new_areas;
2779 new_areas_index = 0;
2781 /* Check whether previous_new_areas had overflowed. */
2782 if (previous_new_areas_index >= NUM_NEW_AREAS) {
2784 /* New areas of objects allocated have been lost so need to do a
2785 * full scan to be sure! If this becomes a problem try
2786 * increasing NUM_NEW_AREAS. */
2787 if (gencgc_verbose) {
2788 SHOW("new_areas overflow, doing full scavenge");
2791 /* Don't need to record new areas that get scavenged
2792 * anyway during scavenge_newspace_generation_one_scan. */
2793 record_new_objects = 1;
2795 scavenge_newspace_generation_one_scan(generation);
2797 /* Record all new areas now. */
2798 record_new_objects = 2;
2800 scav_weak_hash_tables();
2802 /* Flush the current regions updating the tables. */
2803 gc_alloc_update_all_page_tables();
2807 /* Work through previous_new_areas. */
2808 for (i = 0; i < previous_new_areas_index; i++) {
2809 page_index_t page = (*previous_new_areas)[i].page;
2810 size_t offset = (*previous_new_areas)[i].offset;
2811 size_t size = (*previous_new_areas)[i].size / N_WORD_BYTES;
2812 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
2813 scavenge(page_address(page)+offset, size);
2816 scav_weak_hash_tables();
2818 /* Flush the current regions updating the tables. */
2819 gc_alloc_update_all_page_tables();
2822 current_new_areas_index = new_areas_index;
2825 "The re-scan has finished; current_new_areas_index=%d.\n",
2826 current_new_areas_index));*/
2829 /* Turn off recording of areas allocated by gc_alloc(). */
2830 record_new_objects = 0;
2835 /* Check that none of the write_protected pages in this generation
2836 * have been written to. */
2837 for (i = 0; i < page_table_pages; i++) {
2838 if (page_allocated_p(i)
2839 && (page_table[i].bytes_used != 0)
2840 && (page_table[i].gen == generation)
2841 && (page_table[i].write_protected_cleared != 0)
2842 && (page_table[i].dont_move == 0)) {
2843 lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
2844 i, generation, page_table[i].dont_move);
2851 /* Un-write-protect all the pages in from_space. This is done at the
2852 * start of a GC else there may be many page faults while scavenging
2853 * the newspace (I've seen drive the system time to 99%). These pages
2854 * would need to be unprotected anyway before unmapping in
2855 * free_oldspace; not sure what effect this has on paging.. */
2857 unprotect_oldspace(void)
2860 void *region_addr = 0;
2861 void *page_addr = 0;
2862 unsigned long region_bytes = 0;
2864 for (i = 0; i < last_free_page; i++) {
2865 if (page_allocated_p(i)
2866 && (page_table[i].bytes_used != 0)
2867 && (page_table[i].gen == from_space)) {
2869 /* Remove any write-protection. We should be able to rely
2870 * on the write-protect flag to avoid redundant calls. */
2871 if (page_table[i].write_protected) {
2872 page_table[i].write_protected = 0;
2873 page_addr = page_address(i);
2876 region_addr = page_addr;
2877 region_bytes = GENCGC_CARD_BYTES;
2878 } else if (region_addr + region_bytes == page_addr) {
2879 /* Region continue. */
2880 region_bytes += GENCGC_CARD_BYTES;
2882 /* Unprotect previous region. */
2883 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2884 /* First page in new region. */
2885 region_addr = page_addr;
2886 region_bytes = GENCGC_CARD_BYTES;
2892 /* Unprotect last region. */
2893 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2897 /* Work through all the pages and free any in from_space. This
2898 * assumes that all objects have been copied or promoted to an older
2899 * generation. Bytes_allocated and the generation bytes_allocated
2900 * counter are updated. The number of bytes freed is returned. */
2901 static unsigned long
2904 unsigned long bytes_freed = 0;
2905 page_index_t first_page, last_page;
2910 /* Find a first page for the next region of pages. */
2911 while ((first_page < last_free_page)
2912 && (page_free_p(first_page)
2913 || (page_table[first_page].bytes_used == 0)
2914 || (page_table[first_page].gen != from_space)))
2917 if (first_page >= last_free_page)
2920 /* Find the last page of this region. */
2921 last_page = first_page;
2924 /* Free the page. */
2925 bytes_freed += page_table[last_page].bytes_used;
2926 generations[page_table[last_page].gen].bytes_allocated -=
2927 page_table[last_page].bytes_used;
2928 page_table[last_page].allocated = FREE_PAGE_FLAG;
2929 page_table[last_page].bytes_used = 0;
2930 /* Should already be unprotected by unprotect_oldspace(). */
2931 gc_assert(!page_table[last_page].write_protected);
2934 while ((last_page < last_free_page)
2935 && page_allocated_p(last_page)
2936 && (page_table[last_page].bytes_used != 0)
2937 && (page_table[last_page].gen == from_space));
2939 #ifdef READ_PROTECT_FREE_PAGES
2940 os_protect(page_address(first_page),
2941 npage_bytes(last_page-first_page),
2944 first_page = last_page;
2945 } while (first_page < last_free_page);
2947 bytes_allocated -= bytes_freed;
2952 /* Print some information about a pointer at the given address. */
2954 print_ptr(lispobj *addr)
2956 /* If addr is in the dynamic space then out the page information. */
2957 page_index_t pi1 = find_page_index((void*)addr);
2960 fprintf(stderr," %x: page %d alloc %d gen %d bytes_used %d offset %lu dont_move %d\n",
2961 (unsigned long) addr,
2963 page_table[pi1].allocated,
2964 page_table[pi1].gen,
2965 page_table[pi1].bytes_used,
2966 page_table[pi1].region_start_offset,
2967 page_table[pi1].dont_move);
2968 fprintf(stderr," %x %x %x %x (%x) %x %x %x %x\n",
2982 is_in_stack_space(lispobj ptr)
2984 /* For space verification: Pointers can be valid if they point
2985 * to a thread stack space. This would be faster if the thread
2986 * structures had page-table entries as if they were part of
2987 * the heap space. */
2989 for_each_thread(th) {
2990 if ((th->control_stack_start <= (lispobj *)ptr) &&
2991 (th->control_stack_end >= (lispobj *)ptr)) {
2999 verify_space(lispobj *start, size_t words)
3001 int is_in_dynamic_space = (find_page_index((void*)start) != -1);
3002 int is_in_readonly_space =
3003 (READ_ONLY_SPACE_START <= (unsigned long)start &&
3004 (unsigned long)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3008 lispobj thing = *(lispobj*)start;
3010 if (is_lisp_pointer(thing)) {
3011 page_index_t page_index = find_page_index((void*)thing);
3012 long to_readonly_space =
3013 (READ_ONLY_SPACE_START <= thing &&
3014 thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3015 long to_static_space =
3016 (STATIC_SPACE_START <= thing &&
3017 thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3019 /* Does it point to the dynamic space? */
3020 if (page_index != -1) {
3021 /* If it's within the dynamic space it should point to a used
3022 * page. XX Could check the offset too. */
3023 if (page_allocated_p(page_index)
3024 && (page_table[page_index].bytes_used == 0))
3025 lose ("Ptr %p @ %p sees free page.\n", thing, start);
3026 /* Check that it doesn't point to a forwarding pointer! */
3027 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3028 lose("Ptr %p @ %p sees forwarding ptr.\n", thing, start);
3030 /* Check that its not in the RO space as it would then be a
3031 * pointer from the RO to the dynamic space. */
3032 if (is_in_readonly_space) {
3033 lose("ptr to dynamic space %p from RO space %x\n",
3036 /* Does it point to a plausible object? This check slows
3037 * it down a lot (so it's commented out).
3039 * "a lot" is serious: it ate 50 minutes cpu time on
3040 * my duron 950 before I came back from lunch and
3043 * FIXME: Add a variable to enable this
3046 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
3047 lose("ptr %p to invalid object %p\n", thing, start);
3051 extern void funcallable_instance_tramp;
3052 /* Verify that it points to another valid space. */
3053 if (!to_readonly_space && !to_static_space
3054 && (thing != (lispobj)&funcallable_instance_tramp)
3055 && !is_in_stack_space(thing)) {
3056 lose("Ptr %p @ %p sees junk.\n", thing, start);
3060 if (!(fixnump(thing))) {
3062 switch(widetag_of(*start)) {
3065 case SIMPLE_VECTOR_WIDETAG:
3067 case COMPLEX_WIDETAG:
3068 case SIMPLE_ARRAY_WIDETAG:
3069 case COMPLEX_BASE_STRING_WIDETAG:
3070 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
3071 case COMPLEX_CHARACTER_STRING_WIDETAG:
3073 case COMPLEX_VECTOR_NIL_WIDETAG:
3074 case COMPLEX_BIT_VECTOR_WIDETAG:
3075 case COMPLEX_VECTOR_WIDETAG:
3076 case COMPLEX_ARRAY_WIDETAG:
3077 case CLOSURE_HEADER_WIDETAG:
3078 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3079 case VALUE_CELL_HEADER_WIDETAG:
3080 case SYMBOL_HEADER_WIDETAG:
3081 case CHARACTER_WIDETAG:
3082 #if N_WORD_BITS == 64
3083 case SINGLE_FLOAT_WIDETAG:
3085 case UNBOUND_MARKER_WIDETAG:
3090 case INSTANCE_HEADER_WIDETAG:
3093 long ntotal = HeaderValue(thing);
3094 lispobj layout = ((struct instance *)start)->slots[0];
3099 nuntagged = ((struct layout *)
3100 native_pointer(layout))->n_untagged_slots;
3101 verify_space(start + 1,
3102 ntotal - fixnum_value(nuntagged));
3106 case CODE_HEADER_WIDETAG:
3108 lispobj object = *start;
3110 long nheader_words, ncode_words, nwords;
3112 struct simple_fun *fheaderp;
3114 code = (struct code *) start;
3116 /* Check that it's not in the dynamic space.
3117 * FIXME: Isn't is supposed to be OK for code
3118 * objects to be in the dynamic space these days? */
3119 if (is_in_dynamic_space
3120 /* It's ok if it's byte compiled code. The trace
3121 * table offset will be a fixnum if it's x86
3122 * compiled code - check.
3124 * FIXME: #^#@@! lack of abstraction here..
3125 * This line can probably go away now that
3126 * there's no byte compiler, but I've got
3127 * too much to worry about right now to try
3128 * to make sure. -- WHN 2001-10-06 */
3129 && fixnump(code->trace_table_offset)
3130 /* Only when enabled */
3131 && verify_dynamic_code_check) {
3133 "/code object at %p in the dynamic space\n",
3137 ncode_words = fixnum_value(code->code_size);
3138 nheader_words = HeaderValue(object);
3139 nwords = ncode_words + nheader_words;
3140 nwords = CEILING(nwords, 2);
3141 /* Scavenge the boxed section of the code data block */
3142 verify_space(start + 1, nheader_words - 1);
3144 /* Scavenge the boxed section of each function
3145 * object in the code data block. */
3146 fheaderl = code->entry_points;
3147 while (fheaderl != NIL) {
3149 (struct simple_fun *) native_pointer(fheaderl);
3150 gc_assert(widetag_of(fheaderp->header) ==
3151 SIMPLE_FUN_HEADER_WIDETAG);
3152 verify_space(&fheaderp->name, 1);
3153 verify_space(&fheaderp->arglist, 1);
3154 verify_space(&fheaderp->type, 1);
3155 fheaderl = fheaderp->next;
3161 /* unboxed objects */
3162 case BIGNUM_WIDETAG:
3163 #if N_WORD_BITS != 64
3164 case SINGLE_FLOAT_WIDETAG:
3166 case DOUBLE_FLOAT_WIDETAG:
3167 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3168 case LONG_FLOAT_WIDETAG:
3170 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3171 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3173 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3174 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3176 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3177 case COMPLEX_LONG_FLOAT_WIDETAG:
3179 case SIMPLE_BASE_STRING_WIDETAG:
3180 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3181 case SIMPLE_CHARACTER_STRING_WIDETAG:
3183 case SIMPLE_BIT_VECTOR_WIDETAG:
3184 case SIMPLE_ARRAY_NIL_WIDETAG:
3185 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3186 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3187 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3188 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3189 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3190 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3192 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
3194 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3195 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3196 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3197 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3199 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3200 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3202 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3203 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3205 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3206 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3209 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
3211 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3212 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3214 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3215 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3217 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3218 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3219 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3220 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3222 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3223 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3225 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3226 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3228 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3229 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3232 case WEAK_POINTER_WIDETAG:
3233 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3234 case NO_TLS_VALUE_MARKER_WIDETAG:
3236 count = (sizetab[widetag_of(*start)])(start);
3240 lose("Unhandled widetag %p at %p\n",
3241 widetag_of(*start), start);
3253 /* FIXME: It would be nice to make names consistent so that
3254 * foo_size meant size *in* *bytes* instead of size in some
3255 * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3256 * Some counts of lispobjs are called foo_count; it might be good
3257 * to grep for all foo_size and rename the appropriate ones to
3259 long read_only_space_size =
3260 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3261 - (lispobj*)READ_ONLY_SPACE_START;
3262 long static_space_size =
3263 (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3264 - (lispobj*)STATIC_SPACE_START;
3266 for_each_thread(th) {
3267 long binding_stack_size =
3268 (lispobj*)get_binding_stack_pointer(th)
3269 - (lispobj*)th->binding_stack_start;
3270 verify_space(th->binding_stack_start, binding_stack_size);
3272 verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3273 verify_space((lispobj*)STATIC_SPACE_START , static_space_size);
3277 verify_generation(generation_index_t generation)
3281 for (i = 0; i < last_free_page; i++) {
3282 if (page_allocated_p(i)
3283 && (page_table[i].bytes_used != 0)
3284 && (page_table[i].gen == generation)) {
3285 page_index_t last_page;
3286 int region_allocation = page_table[i].allocated;
3288 /* This should be the start of a contiguous block */
3289 gc_assert(page_table[i].region_start_offset == 0);
3291 /* Need to find the full extent of this contiguous block in case
3292 objects span pages. */
3294 /* Now work forward until the end of this contiguous area is
3296 for (last_page = i; ;last_page++)
3297 /* Check whether this is the last page in this contiguous
3299 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
3300 /* Or it is CARD_BYTES and is the last in the block */
3301 || (page_table[last_page+1].allocated != region_allocation)
3302 || (page_table[last_page+1].bytes_used == 0)
3303 || (page_table[last_page+1].gen != generation)
3304 || (page_table[last_page+1].region_start_offset == 0))
3307 verify_space(page_address(i),
3309 (page_table[last_page].bytes_used
3310 + npage_bytes(last_page-i)))
3317 /* Check that all the free space is zero filled. */
3319 verify_zero_fill(void)
3323 for (page = 0; page < last_free_page; page++) {
3324 if (page_free_p(page)) {
3325 /* The whole page should be zero filled. */
3326 long *start_addr = (long *)page_address(page);
3329 for (i = 0; i < size; i++) {
3330 if (start_addr[i] != 0) {
3331 lose("free page not zero at %x\n", start_addr + i);
3335 long free_bytes = GENCGC_CARD_BYTES - page_table[page].bytes_used;
3336 if (free_bytes > 0) {
3337 long *start_addr = (long *)((unsigned long)page_address(page)
3338 + page_table[page].bytes_used);
3339 long size = free_bytes / N_WORD_BYTES;
3341 for (i = 0; i < size; i++) {
3342 if (start_addr[i] != 0) {
3343 lose("free region not zero at %x\n", start_addr + i);
3351 /* External entry point for verify_zero_fill */
3353 gencgc_verify_zero_fill(void)
3355 /* Flush the alloc regions updating the tables. */
3356 gc_alloc_update_all_page_tables();
3357 SHOW("verifying zero fill");
3362 verify_dynamic_space(void)
3364 generation_index_t i;
3366 for (i = 0; i <= HIGHEST_NORMAL_GENERATION; i++)
3367 verify_generation(i);
3369 if (gencgc_enable_verify_zero_fill)
3373 /* Write-protect all the dynamic boxed pages in the given generation. */
3375 write_protect_generation_pages(generation_index_t generation)
3379 gc_assert(generation < SCRATCH_GENERATION);
3381 for (start = 0; start < last_free_page; start++) {
3382 if (protect_page_p(start, generation)) {
3386 /* Note the page as protected in the page tables. */
3387 page_table[start].write_protected = 1;
3389 for (last = start + 1; last < last_free_page; last++) {
3390 if (!protect_page_p(last, generation))
3392 page_table[last].write_protected = 1;
3395 page_start = (void *)page_address(start);
3397 os_protect(page_start,
3398 npage_bytes(last - start),
3399 OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3405 if (gencgc_verbose > 1) {
3407 "/write protected %d of %d pages in generation %d\n",
3408 count_write_protect_generation_pages(generation),
3409 count_generation_pages(generation),
3414 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3416 scavenge_control_stack(struct thread *th)
3418 lispobj *control_stack =
3419 (lispobj *)(th->control_stack_start);
3420 unsigned long control_stack_size =
3421 access_control_stack_pointer(th) - control_stack;
3423 scavenge(control_stack, control_stack_size);
3427 #if defined(LISP_FEATURE_SB_THREAD) && (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
3429 preserve_context_registers (os_context_t *c)
3432 /* On Darwin the signal context isn't a contiguous block of memory,
3433 * so just preserve_pointering its contents won't be sufficient.
3435 #if defined(LISP_FEATURE_DARWIN)
3436 #if defined LISP_FEATURE_X86
3437 preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3438 preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3439 preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3440 preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3441 preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3442 preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3443 preserve_pointer((void*)*os_context_pc_addr(c));
3444 #elif defined LISP_FEATURE_X86_64
3445 preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3446 preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3447 preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3448 preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3449 preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3450 preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3451 preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3452 preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3453 preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3454 preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3455 preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3456 preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3457 preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3458 preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3459 preserve_pointer((void*)*os_context_pc_addr(c));
3461 #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3464 for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3465 preserve_pointer(*ptr);
3470 /* Garbage collect a generation. If raise is 0 then the remains of the
3471 * generation are not raised to the next generation. */
3473 garbage_collect_generation(generation_index_t generation, int raise)
3475 unsigned long bytes_freed;
3477 unsigned long static_space_size;
3480 gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3482 /* The oldest generation can't be raised. */
3483 gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
3485 /* Check if weak hash tables were processed in the previous GC. */
3486 gc_assert(weak_hash_tables == NULL);
3488 /* Initialize the weak pointer list. */
3489 weak_pointers = NULL;
3491 /* When a generation is not being raised it is transported to a
3492 * temporary generation (NUM_GENERATIONS), and lowered when
3493 * done. Set up this new generation. There should be no pages
3494 * allocated to it yet. */
3496 gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
3499 /* Set the global src and dest. generations */
3500 from_space = generation;
3502 new_space = generation+1;
3504 new_space = SCRATCH_GENERATION;
3506 /* Change to a new space for allocation, resetting the alloc_start_page */
3507 gc_alloc_generation = new_space;
3508 generations[new_space].alloc_start_page = 0;
3509 generations[new_space].alloc_unboxed_start_page = 0;
3510 generations[new_space].alloc_large_start_page = 0;
3511 generations[new_space].alloc_large_unboxed_start_page = 0;
3513 /* Before any pointers are preserved, the dont_move flags on the
3514 * pages need to be cleared. */
3515 for (i = 0; i < last_free_page; i++)
3516 if(page_table[i].gen==from_space)
3517 page_table[i].dont_move = 0;
3519 /* Un-write-protect the old-space pages. This is essential for the
3520 * promoted pages as they may contain pointers into the old-space
3521 * which need to be scavenged. It also helps avoid unnecessary page
3522 * faults as forwarding pointers are written into them. They need to
3523 * be un-protected anyway before unmapping later. */
3524 unprotect_oldspace();
3526 /* Scavenge the stacks' conservative roots. */
3528 /* there are potentially two stacks for each thread: the main
3529 * stack, which may contain Lisp pointers, and the alternate stack.
3530 * We don't ever run Lisp code on the altstack, but it may
3531 * host a sigcontext with lisp objects in it */
3533 /* what we need to do: (1) find the stack pointer for the main
3534 * stack; scavenge it (2) find the interrupt context on the
3535 * alternate stack that might contain lisp values, and scavenge
3538 /* we assume that none of the preceding applies to the thread that
3539 * initiates GC. If you ever call GC from inside an altstack
3540 * handler, you will lose. */
3542 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3543 /* And if we're saving a core, there's no point in being conservative. */
3544 if (conservative_stack) {
3545 for_each_thread(th) {
3547 void **esp=(void **)-1;
3548 #ifdef LISP_FEATURE_SB_THREAD
3550 if(th==arch_os_get_current_thread()) {
3551 /* Somebody is going to burn in hell for this, but casting
3552 * it in two steps shuts gcc up about strict aliasing. */
3553 esp = (void **)((void *)&raise);
3556 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3557 for(i=free-1;i>=0;i--) {
3558 os_context_t *c=th->interrupt_contexts[i];
3559 esp1 = (void **) *os_context_register_addr(c,reg_SP);
3560 if (esp1>=(void **)th->control_stack_start &&
3561 esp1<(void **)th->control_stack_end) {
3562 if(esp1<esp) esp=esp1;
3563 preserve_context_registers(c);
3568 esp = (void **)((void *)&raise);
3570 for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp; ptr--) {
3571 preserve_pointer(*ptr);
3576 /* Non-x86oid systems don't have "conservative roots" as such, but
3577 * the same mechanism is used for objects pinned for use by alien
3579 for_each_thread(th) {
3580 lispobj pin_list = SymbolTlValue(PINNED_OBJECTS,th);
3581 while (pin_list != NIL) {
3582 struct cons *list_entry =
3583 (struct cons *)native_pointer(pin_list);
3584 preserve_pointer(list_entry->car);
3585 pin_list = list_entry->cdr;
3591 if (gencgc_verbose > 1) {
3592 long num_dont_move_pages = count_dont_move_pages();
3594 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3595 num_dont_move_pages,
3596 npage_bytes(num_dont_move_pages));
3600 /* Scavenge all the rest of the roots. */
3602 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3604 * If not x86, we need to scavenge the interrupt context(s) and the
3609 for_each_thread(th) {
3610 scavenge_interrupt_contexts(th);
3611 scavenge_control_stack(th);
3614 /* Scrub the unscavenged control stack space, so that we can't run
3615 * into any stale pointers in a later GC (this is done by the
3616 * stop-for-gc handler in the other threads). */
3617 scrub_control_stack();
3621 /* Scavenge the Lisp functions of the interrupt handlers, taking
3622 * care to avoid SIG_DFL and SIG_IGN. */
3623 for (i = 0; i < NSIG; i++) {
3624 union interrupt_handler handler = interrupt_handlers[i];
3625 if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3626 !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3627 scavenge((lispobj *)(interrupt_handlers + i), 1);
3630 /* Scavenge the binding stacks. */
3633 for_each_thread(th) {
3634 long len= (lispobj *)get_binding_stack_pointer(th) -
3635 th->binding_stack_start;
3636 scavenge((lispobj *) th->binding_stack_start,len);
3637 #ifdef LISP_FEATURE_SB_THREAD
3638 /* do the tls as well */
3639 len=(SymbolValue(FREE_TLS_INDEX,0) >> WORD_SHIFT) -
3640 (sizeof (struct thread))/(sizeof (lispobj));
3641 scavenge((lispobj *) (th+1),len);
3646 /* The original CMU CL code had scavenge-read-only-space code
3647 * controlled by the Lisp-level variable
3648 * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3649 * wasn't documented under what circumstances it was useful or
3650 * safe to turn it on, so it's been turned off in SBCL. If you
3651 * want/need this functionality, and can test and document it,
3652 * please submit a patch. */
3654 if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3655 unsigned long read_only_space_size =
3656 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3657 (lispobj*)READ_ONLY_SPACE_START;
3659 "/scavenge read only space: %d bytes\n",
3660 read_only_space_size * sizeof(lispobj)));
3661 scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3665 /* Scavenge static space. */
3667 (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3668 (lispobj *)STATIC_SPACE_START;
3669 if (gencgc_verbose > 1) {
3671 "/scavenge static space: %d bytes\n",
3672 static_space_size * sizeof(lispobj)));
3674 scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3676 /* All generations but the generation being GCed need to be
3677 * scavenged. The new_space generation needs special handling as
3678 * objects may be moved in - it is handled separately below. */
3679 scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
3681 /* Finally scavenge the new_space generation. Keep going until no
3682 * more objects are moved into the new generation */
3683 scavenge_newspace_generation(new_space);
3685 /* FIXME: I tried reenabling this check when debugging unrelated
3686 * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3687 * Since the current GC code seems to work well, I'm guessing that
3688 * this debugging code is just stale, but I haven't tried to
3689 * figure it out. It should be figured out and then either made to
3690 * work or just deleted. */
3691 #define RESCAN_CHECK 0
3693 /* As a check re-scavenge the newspace once; no new objects should
3696 os_vm_size_t old_bytes_allocated = bytes_allocated;
3697 os_vm_size_t bytes_allocated;
3699 /* Start with a full scavenge. */
3700 scavenge_newspace_generation_one_scan(new_space);
3702 /* Flush the current regions, updating the tables. */
3703 gc_alloc_update_all_page_tables();
3705 bytes_allocated = bytes_allocated - old_bytes_allocated;
3707 if (bytes_allocated != 0) {
3708 lose("Rescan of new_space allocated %d more bytes.\n",
3714 scan_weak_hash_tables();
3715 scan_weak_pointers();
3717 /* Flush the current regions, updating the tables. */
3718 gc_alloc_update_all_page_tables();
3720 /* Free the pages in oldspace, but not those marked dont_move. */
3721 bytes_freed = free_oldspace();
3723 /* If the GC is not raising the age then lower the generation back
3724 * to its normal generation number */
3726 for (i = 0; i < last_free_page; i++)
3727 if ((page_table[i].bytes_used != 0)
3728 && (page_table[i].gen == SCRATCH_GENERATION))
3729 page_table[i].gen = generation;
3730 gc_assert(generations[generation].bytes_allocated == 0);
3731 generations[generation].bytes_allocated =
3732 generations[SCRATCH_GENERATION].bytes_allocated;
3733 generations[SCRATCH_GENERATION].bytes_allocated = 0;
3736 /* Reset the alloc_start_page for generation. */
3737 generations[generation].alloc_start_page = 0;
3738 generations[generation].alloc_unboxed_start_page = 0;
3739 generations[generation].alloc_large_start_page = 0;
3740 generations[generation].alloc_large_unboxed_start_page = 0;
3742 if (generation >= verify_gens) {
3743 if (gencgc_verbose) {
3747 verify_dynamic_space();
3750 /* Set the new gc trigger for the GCed generation. */
3751 generations[generation].gc_trigger =
3752 generations[generation].bytes_allocated
3753 + generations[generation].bytes_consed_between_gc;
3756 generations[generation].num_gc = 0;
3758 ++generations[generation].num_gc;
3762 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3764 update_dynamic_space_free_pointer(void)
3766 page_index_t last_page = -1, i;
3768 for (i = 0; i < last_free_page; i++)
3769 if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
3772 last_free_page = last_page+1;
3774 set_alloc_pointer((lispobj)(page_address(last_free_page)));
3775 return 0; /* dummy value: return something ... */
3779 remap_page_range (page_index_t from, page_index_t to)
3781 /* There's a mysterious Solaris/x86 problem with using mmap
3782 * tricks for memory zeroing. See sbcl-devel thread
3783 * "Re: patch: standalone executable redux".
3785 #if defined(LISP_FEATURE_SUNOS)
3786 zero_and_mark_pages(from, to);
3789 release_granularity = gencgc_release_granularity/GENCGC_CARD_BYTES,
3790 release_mask = release_granularity-1,
3792 aligned_from = (from+release_mask)&~release_mask,
3793 aligned_end = (end&~release_mask);
3795 if (aligned_from < aligned_end) {
3796 zero_pages_with_mmap(aligned_from, aligned_end-1);
3797 if (aligned_from != from)
3798 zero_and_mark_pages(from, aligned_from-1);
3799 if (aligned_end != end)
3800 zero_and_mark_pages(aligned_end, end-1);
3802 zero_and_mark_pages(from, to);
3808 remap_free_pages (page_index_t from, page_index_t to, int forcibly)
3810 page_index_t first_page, last_page;
3813 return remap_page_range(from, to);
3815 for (first_page = from; first_page <= to; first_page++) {
3816 if (page_allocated_p(first_page) ||
3817 (page_table[first_page].need_to_zero == 0))
3820 last_page = first_page + 1;
3821 while (page_free_p(last_page) &&
3822 (last_page <= to) &&
3823 (page_table[last_page].need_to_zero == 1))
3826 remap_page_range(first_page, last_page-1);
3828 first_page = last_page;
3832 generation_index_t small_generation_limit = 1;
3834 /* GC all generations newer than last_gen, raising the objects in each
3835 * to the next older generation - we finish when all generations below
3836 * last_gen are empty. Then if last_gen is due for a GC, or if
3837 * last_gen==NUM_GENERATIONS (the scratch generation? eh?) we GC that
3838 * too. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3840 * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3841 * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3843 collect_garbage(generation_index_t last_gen)
3845 generation_index_t gen = 0, i;
3848 /* The largest value of last_free_page seen since the time
3849 * remap_free_pages was called. */
3850 static page_index_t high_water_mark = 0;
3852 FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
3853 log_generation_stats(gc_logfile, "=== GC Start ===");
3857 if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
3859 "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3864 /* Flush the alloc regions updating the tables. */
3865 gc_alloc_update_all_page_tables();
3867 /* Verify the new objects created by Lisp code. */
3868 if (pre_verify_gen_0) {
3869 FSHOW((stderr, "pre-checking generation 0\n"));
3870 verify_generation(0);
3873 if (gencgc_verbose > 1)
3874 print_generation_stats();
3877 /* Collect the generation. */
3879 if (gen >= gencgc_oldest_gen_to_gc) {
3880 /* Never raise the oldest generation. */
3885 || (generations[gen].num_gc >= generations[gen].number_of_gcs_before_promotion);
3888 if (gencgc_verbose > 1) {
3890 "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3893 generations[gen].bytes_allocated,
3894 generations[gen].gc_trigger,
3895 generations[gen].num_gc));
3898 /* If an older generation is being filled, then update its
3901 generations[gen+1].cum_sum_bytes_allocated +=
3902 generations[gen+1].bytes_allocated;
3905 garbage_collect_generation(gen, raise);
3907 /* Reset the memory age cum_sum. */
3908 generations[gen].cum_sum_bytes_allocated = 0;
3910 if (gencgc_verbose > 1) {
3911 FSHOW((stderr, "GC of generation %d finished:\n", gen));
3912 print_generation_stats();
3916 } while ((gen <= gencgc_oldest_gen_to_gc)
3917 && ((gen < last_gen)
3918 || ((gen <= gencgc_oldest_gen_to_gc)
3920 && (generations[gen].bytes_allocated
3921 > generations[gen].gc_trigger)
3922 && (generation_average_age(gen)
3923 > generations[gen].minimum_age_before_gc))));
3925 /* Now if gen-1 was raised all generations before gen are empty.
3926 * If it wasn't raised then all generations before gen-1 are empty.
3928 * Now objects within this gen's pages cannot point to younger
3929 * generations unless they are written to. This can be exploited
3930 * by write-protecting the pages of gen; then when younger
3931 * generations are GCed only the pages which have been written
3936 gen_to_wp = gen - 1;
3938 /* There's not much point in WPing pages in generation 0 as it is
3939 * never scavenged (except promoted pages). */
3940 if ((gen_to_wp > 0) && enable_page_protection) {
3941 /* Check that they are all empty. */
3942 for (i = 0; i < gen_to_wp; i++) {
3943 if (generations[i].bytes_allocated)
3944 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
3947 write_protect_generation_pages(gen_to_wp);
3950 /* Set gc_alloc() back to generation 0. The current regions should
3951 * be flushed after the above GCs. */
3952 gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
3953 gc_alloc_generation = 0;
3955 /* Save the high-water mark before updating last_free_page */
3956 if (last_free_page > high_water_mark)
3957 high_water_mark = last_free_page;
3959 update_dynamic_space_free_pointer();
3961 auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
3963 fprintf(stderr,"Next gc when %ld bytes have been consed\n",
3966 /* If we did a big GC (arbitrarily defined as gen > 1), release memory
3969 if (gen > small_generation_limit) {
3970 if (last_free_page > high_water_mark)
3971 high_water_mark = last_free_page;
3972 remap_free_pages(0, high_water_mark, 0);
3973 high_water_mark = 0;
3978 log_generation_stats(gc_logfile, "=== GC End ===");
3979 SHOW("returning from collect_garbage");
3982 /* This is called by Lisp PURIFY when it is finished. All live objects
3983 * will have been moved to the RO and Static heaps. The dynamic space
3984 * will need a full re-initialization. We don't bother having Lisp
3985 * PURIFY flush the current gc_alloc() region, as the page_tables are
3986 * re-initialized, and every page is zeroed to be sure. */
3990 page_index_t page, last_page;
3992 if (gencgc_verbose > 1) {
3993 SHOW("entering gc_free_heap");
3996 for (page = 0; page < page_table_pages; page++) {
3997 /* Skip free pages which should already be zero filled. */
3998 if (page_allocated_p(page)) {
3999 void *page_start, *addr;
4000 for (last_page = page;
4001 (last_page < page_table_pages) && page_allocated_p(last_page);
4003 /* Mark the page free. The other slots are assumed invalid
4004 * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
4005 * should not be write-protected -- except that the
4006 * generation is used for the current region but it sets
4008 page_table[page].allocated = FREE_PAGE_FLAG;
4009 page_table[page].bytes_used = 0;
4010 page_table[page].write_protected = 0;
4013 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
4014 * about this change. */
4015 page_start = (void *)page_address(page);
4016 os_protect(page_start, npage_bytes(last_page-page), OS_VM_PROT_ALL);
4017 remap_free_pages(page, last_page-1, 1);
4020 } else if (gencgc_zero_check_during_free_heap) {
4021 /* Double-check that the page is zero filled. */
4024 gc_assert(page_free_p(page));
4025 gc_assert(page_table[page].bytes_used == 0);
4026 page_start = (long *)page_address(page);
4027 for (i=0; i<GENCGC_CARD_BYTES/sizeof(long); i++) {
4028 if (page_start[i] != 0) {
4029 lose("free region not zero at %x\n", page_start + i);
4035 bytes_allocated = 0;
4037 /* Initialize the generations. */
4038 for (page = 0; page < NUM_GENERATIONS; page++) {
4039 generations[page].alloc_start_page = 0;
4040 generations[page].alloc_unboxed_start_page = 0;
4041 generations[page].alloc_large_start_page = 0;
4042 generations[page].alloc_large_unboxed_start_page = 0;
4043 generations[page].bytes_allocated = 0;
4044 generations[page].gc_trigger = 2000000;
4045 generations[page].num_gc = 0;
4046 generations[page].cum_sum_bytes_allocated = 0;
4049 if (gencgc_verbose > 1)
4050 print_generation_stats();
4052 /* Initialize gc_alloc(). */
4053 gc_alloc_generation = 0;
4055 gc_set_region_empty(&boxed_region);
4056 gc_set_region_empty(&unboxed_region);
4059 set_alloc_pointer((lispobj)((char *)heap_base));
4061 if (verify_after_free_heap) {
4062 /* Check whether purify has left any bad pointers. */
4063 FSHOW((stderr, "checking after free_heap\n"));
4073 /* Compute the number of pages needed for the dynamic space.
4074 * Dynamic space size should be aligned on page size. */
4075 page_table_pages = dynamic_space_size/GENCGC_CARD_BYTES;
4076 gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4078 /* Default nursery size to 5% of the total dynamic space size,
4080 bytes_consed_between_gcs = dynamic_space_size/(os_vm_size_t)20;
4081 if (bytes_consed_between_gcs < (1024*1024))
4082 bytes_consed_between_gcs = 1024*1024;
4084 /* The page_table must be allocated using "calloc" to initialize
4085 * the page structures correctly. There used to be a separate
4086 * initialization loop (now commented out; see below) but that was
4087 * unnecessary and did hurt startup time. */
4088 page_table = calloc(page_table_pages, sizeof(struct page));
4089 gc_assert(page_table);
4092 scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4093 transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4095 heap_base = (void*)DYNAMIC_SPACE_START;
4097 /* The page structures are initialized implicitly when page_table
4098 * is allocated with "calloc" above. Formerly we had the following
4099 * explicit initialization here (comments converted to C99 style
4100 * for readability as C's block comments don't nest):
4102 * // Initialize each page structure.
4103 * for (i = 0; i < page_table_pages; i++) {
4104 * // Initialize all pages as free.
4105 * page_table[i].allocated = FREE_PAGE_FLAG;
4106 * page_table[i].bytes_used = 0;
4108 * // Pages are not write-protected at startup.
4109 * page_table[i].write_protected = 0;
4112 * Without this loop the image starts up much faster when dynamic
4113 * space is large -- which it is on 64-bit platforms already by
4114 * default -- and when "calloc" for large arrays is implemented
4115 * using copy-on-write of a page of zeroes -- which it is at least
4116 * on Linux. In this case the pages that page_table_pages is stored
4117 * in are mapped and cleared not before the corresponding part of
4118 * dynamic space is used. For example, this saves clearing 16 MB of
4119 * memory at startup if the page size is 4 KB and the size of
4120 * dynamic space is 4 GB.
4121 * FREE_PAGE_FLAG must be 0 for this to work correctly which is
4122 * asserted below: */
4124 /* Compile time assertion: If triggered, declares an array
4125 * of dimension -1 forcing a syntax error. The intent of the
4126 * assignment is to avoid an "unused variable" warning. */
4127 char assert_free_page_flag_0[(FREE_PAGE_FLAG) ? -1 : 1];
4128 assert_free_page_flag_0[0] = assert_free_page_flag_0[0];
4131 bytes_allocated = 0;
4133 /* Initialize the generations.
4135 * FIXME: very similar to code in gc_free_heap(), should be shared */
4136 for (i = 0; i < NUM_GENERATIONS; i++) {
4137 generations[i].alloc_start_page = 0;
4138 generations[i].alloc_unboxed_start_page = 0;
4139 generations[i].alloc_large_start_page = 0;
4140 generations[i].alloc_large_unboxed_start_page = 0;
4141 generations[i].bytes_allocated = 0;
4142 generations[i].gc_trigger = 2000000;
4143 generations[i].num_gc = 0;
4144 generations[i].cum_sum_bytes_allocated = 0;
4145 /* the tune-able parameters */
4146 generations[i].bytes_consed_between_gc = bytes_consed_between_gcs;
4147 generations[i].number_of_gcs_before_promotion = 1;
4148 generations[i].minimum_age_before_gc = 0.75;
4151 /* Initialize gc_alloc. */
4152 gc_alloc_generation = 0;
4153 gc_set_region_empty(&boxed_region);
4154 gc_set_region_empty(&unboxed_region);
4159 /* Pick up the dynamic space from after a core load.
4161 * The ALLOCATION_POINTER points to the end of the dynamic space.
4165 gencgc_pickup_dynamic(void)
4167 page_index_t page = 0;
4168 void *alloc_ptr = (void *)get_alloc_pointer();
4169 lispobj *prev=(lispobj *)page_address(page);
4170 generation_index_t gen = PSEUDO_STATIC_GENERATION;
4172 lispobj *first,*ptr= (lispobj *)page_address(page);
4174 if (!gencgc_partial_pickup || page_allocated_p(page)) {
4175 /* It is possible, though rare, for the saved page table
4176 * to contain free pages below alloc_ptr. */
4177 page_table[page].gen = gen;
4178 page_table[page].bytes_used = GENCGC_CARD_BYTES;
4179 page_table[page].large_object = 0;
4180 page_table[page].write_protected = 0;
4181 page_table[page].write_protected_cleared = 0;
4182 page_table[page].dont_move = 0;
4183 page_table[page].need_to_zero = 1;
4186 if (!gencgc_partial_pickup) {
4187 page_table[page].allocated = BOXED_PAGE_FLAG;
4188 first=gc_search_space(prev,(ptr+2)-prev,ptr);
4191 page_table[page].region_start_offset =
4192 page_address(page) - (void *)prev;
4195 } while (page_address(page) < alloc_ptr);
4197 last_free_page = page;
4199 generations[gen].bytes_allocated = npage_bytes(page);
4200 bytes_allocated = npage_bytes(page);
4202 gc_alloc_update_all_page_tables();
4203 write_protect_generation_pages(gen);
4207 gc_initialize_pointers(void)
4209 gencgc_pickup_dynamic();
4213 /* alloc(..) is the external interface for memory allocation. It
4214 * allocates to generation 0. It is not called from within the garbage
4215 * collector as it is only external uses that need the check for heap
4216 * size (GC trigger) and to disable the interrupts (interrupts are
4217 * always disabled during a GC).
4219 * The vops that call alloc(..) assume that the returned space is zero-filled.
4220 * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4222 * The check for a GC trigger is only performed when the current
4223 * region is full, so in most cases it's not needed. */
4225 static inline lispobj *
4226 general_alloc_internal(long nbytes, int page_type_flag, struct alloc_region *region,
4227 struct thread *thread)
4229 #ifndef LISP_FEATURE_WIN32
4230 lispobj alloc_signal;
4233 void *new_free_pointer;
4235 gc_assert(nbytes>0);
4237 /* Check for alignment allocation problems. */
4238 gc_assert((((unsigned long)region->free_pointer & LOWTAG_MASK) == 0)
4239 && ((nbytes & LOWTAG_MASK) == 0));
4241 /* Must be inside a PA section. */
4242 gc_assert(get_pseudo_atomic_atomic(thread));
4244 /* maybe we can do this quickly ... */
4245 new_free_pointer = region->free_pointer + nbytes;
4246 if (new_free_pointer <= region->end_addr) {
4247 new_obj = (void*)(region->free_pointer);
4248 region->free_pointer = new_free_pointer;
4249 return(new_obj); /* yup */
4252 /* we have to go the long way around, it seems. Check whether we
4253 * should GC in the near future
4255 if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
4256 /* Don't flood the system with interrupts if the need to gc is
4257 * already noted. This can happen for example when SUB-GC
4258 * allocates or after a gc triggered in a WITHOUT-GCING. */
4259 if (SymbolValue(GC_PENDING,thread) == NIL) {
4260 /* set things up so that GC happens when we finish the PA
4262 SetSymbolValue(GC_PENDING,T,thread);
4263 if (SymbolValue(GC_INHIBIT,thread) == NIL) {
4264 set_pseudo_atomic_interrupted(thread);
4265 #ifdef LISP_FEATURE_PPC
4266 /* PPC calls alloc() from a trap or from pa_alloc(),
4267 * look up the most context if it's from a trap. */
4269 os_context_t *context =
4270 thread->interrupt_data->allocation_trap_context;
4271 maybe_save_gc_mask_and_block_deferrables
4272 (context ? os_context_sigmask_addr(context) : NULL);
4275 maybe_save_gc_mask_and_block_deferrables(NULL);
4280 new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4282 #ifndef LISP_FEATURE_WIN32
4283 alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4284 if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4285 if ((signed long) alloc_signal <= 0) {
4286 SetSymbolValue(ALLOC_SIGNAL, T, thread);
4289 SetSymbolValue(ALLOC_SIGNAL,
4290 alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4300 general_alloc(long nbytes, int page_type_flag)
4302 struct thread *thread = arch_os_get_current_thread();
4303 /* Select correct region, and call general_alloc_internal with it.
4304 * For other then boxed allocation we must lock first, since the
4305 * region is shared. */
4306 if (BOXED_PAGE_FLAG & page_type_flag) {
4307 #ifdef LISP_FEATURE_SB_THREAD
4308 struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4310 struct alloc_region *region = &boxed_region;
4312 return general_alloc_internal(nbytes, page_type_flag, region, thread);
4313 } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4315 gc_assert(0 == thread_mutex_lock(&allocation_lock));
4316 obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4317 gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4320 lose("bad page type flag: %d", page_type_flag);
4327 gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4328 return general_alloc(nbytes, BOXED_PAGE_FLAG);
4332 * shared support for the OS-dependent signal handlers which
4333 * catch GENCGC-related write-protect violations
4335 void unhandled_sigmemoryfault(void* addr);
4337 /* Depending on which OS we're running under, different signals might
4338 * be raised for a violation of write protection in the heap. This
4339 * function factors out the common generational GC magic which needs
4340 * to invoked in this case, and should be called from whatever signal
4341 * handler is appropriate for the OS we're running under.
4343 * Return true if this signal is a normal generational GC thing that
4344 * we were able to handle, or false if it was abnormal and control
4345 * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
4348 gencgc_handle_wp_violation(void* fault_addr)
4350 page_index_t page_index = find_page_index(fault_addr);
4353 FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4354 fault_addr, page_index));
4357 /* Check whether the fault is within the dynamic space. */
4358 if (page_index == (-1)) {
4360 /* It can be helpful to be able to put a breakpoint on this
4361 * case to help diagnose low-level problems. */
4362 unhandled_sigmemoryfault(fault_addr);
4364 /* not within the dynamic space -- not our responsibility */
4369 ret = thread_mutex_lock(&free_pages_lock);
4370 gc_assert(ret == 0);
4371 if (page_table[page_index].write_protected) {
4372 /* Unprotect the page. */
4373 os_protect(page_address(page_index), GENCGC_CARD_BYTES, OS_VM_PROT_ALL);
4374 page_table[page_index].write_protected_cleared = 1;
4375 page_table[page_index].write_protected = 0;
4377 /* The only acceptable reason for this signal on a heap
4378 * access is that GENCGC write-protected the page.
4379 * However, if two CPUs hit a wp page near-simultaneously,
4380 * we had better not have the second one lose here if it
4381 * does this test after the first one has already set wp=0
4383 if(page_table[page_index].write_protected_cleared != 1)
4384 lose("fault in heap page %d not marked as write-protected\nboxed_region.first_page: %d, boxed_region.last_page %d\n",
4385 page_index, boxed_region.first_page,
4386 boxed_region.last_page);
4388 ret = thread_mutex_unlock(&free_pages_lock);
4389 gc_assert(ret == 0);
4390 /* Don't worry, we can handle it. */
4394 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4395 * it's not just a case of the program hitting the write barrier, and
4396 * are about to let Lisp deal with it. It's basically just a
4397 * convenient place to set a gdb breakpoint. */
4399 unhandled_sigmemoryfault(void *addr)
4402 void gc_alloc_update_all_page_tables(void)
4404 /* Flush the alloc regions updating the tables. */
4407 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4408 gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4409 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4413 gc_set_region_empty(struct alloc_region *region)
4415 region->first_page = 0;
4416 region->last_page = -1;
4417 region->start_addr = page_address(0);
4418 region->free_pointer = page_address(0);
4419 region->end_addr = page_address(0);
4423 zero_all_free_pages()
4427 for (i = 0; i < last_free_page; i++) {
4428 if (page_free_p(i)) {
4429 #ifdef READ_PROTECT_FREE_PAGES
4430 os_protect(page_address(i),
4439 /* Things to do before doing a final GC before saving a core (without
4442 * + Pages in large_object pages aren't moved by the GC, so we need to
4443 * unset that flag from all pages.
4444 * + The pseudo-static generation isn't normally collected, but it seems
4445 * reasonable to collect it at least when saving a core. So move the
4446 * pages to a normal generation.
4449 prepare_for_final_gc ()
4452 for (i = 0; i < last_free_page; i++) {
4453 page_table[i].large_object = 0;
4454 if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4455 int used = page_table[i].bytes_used;
4456 page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4457 generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4458 generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4464 /* Do a non-conservative GC, and then save a core with the initial
4465 * function being set to the value of the static symbol
4466 * SB!VM:RESTART-LISP-FUNCTION */
4468 gc_and_save(char *filename, boolean prepend_runtime,
4469 boolean save_runtime_options,
4470 boolean compressed, int compression_level)
4473 void *runtime_bytes = NULL;
4474 size_t runtime_size;
4476 file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4481 conservative_stack = 0;
4483 /* The filename might come from Lisp, and be moved by the now
4484 * non-conservative GC. */
4485 filename = strdup(filename);
4487 /* Collect twice: once into relatively high memory, and then back
4488 * into low memory. This compacts the retained data into the lower
4489 * pages, minimizing the size of the core file.
4491 prepare_for_final_gc();
4492 gencgc_alloc_start_page = last_free_page;
4493 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4495 prepare_for_final_gc();
4496 gencgc_alloc_start_page = -1;
4497 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4499 if (prepend_runtime)
4500 save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
4502 /* The dumper doesn't know that pages need to be zeroed before use. */
4503 zero_all_free_pages();
4504 save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4505 prepend_runtime, save_runtime_options,
4506 compressed ? compression_level : COMPRESSION_LEVEL_NONE);
4507 /* Oops. Save still managed to fail. Since we've mangled the stack
4508 * beyond hope, there's not much we can do.
4509 * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4510 * going to be rather unsatisfactory too... */
4511 lose("Attempt to save core after non-conservative GC failed.\n");