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>.
32 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
33 #include "pthreads_win32.h"
41 #include "interrupt.h"
46 #include "gc-internal.h"
48 #include "pseudo-atomic.h"
50 #include "genesis/vector.h"
51 #include "genesis/weak-pointer.h"
52 #include "genesis/fdefn.h"
53 #include "genesis/simple-fun.h"
55 #include "genesis/hash-table.h"
56 #include "genesis/instance.h"
57 #include "genesis/layout.h"
59 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
60 #include "genesis/cons.h"
63 /* forward declarations */
64 page_index_t gc_find_freeish_pages(page_index_t *restart_page_ptr, sword_t nbytes,
72 /* Generations 0-5 are normal collected generations, 6 is only used as
73 * scratch space by the collector, and should never get collected.
76 SCRATCH_GENERATION = PSEUDO_STATIC_GENERATION+1,
80 /* Should we use page protection to help avoid the scavenging of pages
81 * that don't have pointers to younger generations? */
82 boolean enable_page_protection = 1;
84 /* the minimum size (in bytes) for a large object*/
85 #if (GENCGC_ALLOC_GRANULARITY >= PAGE_BYTES) && (GENCGC_ALLOC_GRANULARITY >= GENCGC_CARD_BYTES)
86 os_vm_size_t large_object_size = 4 * GENCGC_ALLOC_GRANULARITY;
87 #elif (GENCGC_CARD_BYTES >= PAGE_BYTES) && (GENCGC_CARD_BYTES >= GENCGC_ALLOC_GRANULARITY)
88 os_vm_size_t large_object_size = 4 * GENCGC_CARD_BYTES;
90 os_vm_size_t large_object_size = 4 * PAGE_BYTES;
93 /* Largest allocation seen since last GC. */
94 os_vm_size_t large_allocation = 0;
101 /* the verbosity level. All non-error messages are disabled at level 0;
102 * and only a few rare messages are printed at level 1. */
104 boolean gencgc_verbose = 1;
106 boolean gencgc_verbose = 0;
109 /* FIXME: At some point enable the various error-checking things below
110 * and see what they say. */
112 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
113 * Set verify_gens to HIGHEST_NORMAL_GENERATION + 1 to disable this kind of
115 generation_index_t verify_gens = HIGHEST_NORMAL_GENERATION + 1;
117 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
118 boolean pre_verify_gen_0 = 0;
120 /* Should we check for bad pointers after gc_free_heap is called
121 * from Lisp PURIFY? */
122 boolean verify_after_free_heap = 0;
124 /* Should we print a note when code objects are found in the dynamic space
125 * during a heap verify? */
126 boolean verify_dynamic_code_check = 0;
128 /* Should we check code objects for fixup errors after they are transported? */
129 boolean check_code_fixups = 0;
131 /* Should we check that newly allocated regions are zero filled? */
132 boolean gencgc_zero_check = 0;
134 /* Should we check that the free space is zero filled? */
135 boolean gencgc_enable_verify_zero_fill = 0;
137 /* Should we check that free pages are zero filled during gc_free_heap
138 * called after Lisp PURIFY? */
139 boolean gencgc_zero_check_during_free_heap = 0;
141 /* When loading a core, don't do a full scan of the memory for the
142 * memory region boundaries. (Set to true by coreparse.c if the core
143 * contained a pagetable entry).
145 boolean gencgc_partial_pickup = 0;
147 /* If defined, free pages are read-protected to ensure that nothing
151 /* #define READ_PROTECT_FREE_PAGES */
155 * GC structures and variables
158 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
159 os_vm_size_t bytes_allocated = 0;
160 os_vm_size_t auto_gc_trigger = 0;
162 /* the source and destination generations. These are set before a GC starts
164 generation_index_t from_space;
165 generation_index_t new_space;
167 /* Set to 1 when in GC */
168 boolean gc_active_p = 0;
170 /* should the GC be conservative on stack. If false (only right before
171 * saving a core), don't scan the stack / mark pages dont_move. */
172 static boolean conservative_stack = 1;
174 /* An array of page structures is allocated on gc initialization.
175 * This helps to quickly map between an address and its page structure.
176 * page_table_pages is set from the size of the dynamic space. */
177 page_index_t page_table_pages;
178 struct page *page_table;
180 static inline boolean page_allocated_p(page_index_t page) {
181 return (page_table[page].allocated != FREE_PAGE_FLAG);
184 static inline boolean page_no_region_p(page_index_t page) {
185 return !(page_table[page].allocated & OPEN_REGION_PAGE_FLAG);
188 static inline boolean page_allocated_no_region_p(page_index_t page) {
189 return ((page_table[page].allocated & (UNBOXED_PAGE_FLAG | BOXED_PAGE_FLAG))
190 && page_no_region_p(page));
193 static inline boolean page_free_p(page_index_t page) {
194 return (page_table[page].allocated == FREE_PAGE_FLAG);
197 static inline boolean page_boxed_p(page_index_t page) {
198 return (page_table[page].allocated & BOXED_PAGE_FLAG);
201 static inline boolean code_page_p(page_index_t page) {
202 return (page_table[page].allocated & CODE_PAGE_FLAG);
205 static inline boolean page_boxed_no_region_p(page_index_t page) {
206 return page_boxed_p(page) && page_no_region_p(page);
209 static inline boolean page_unboxed_p(page_index_t page) {
210 /* Both flags set == boxed code page */
211 return ((page_table[page].allocated & UNBOXED_PAGE_FLAG)
212 && !page_boxed_p(page));
215 static inline boolean protect_page_p(page_index_t page, generation_index_t generation) {
216 return (page_boxed_no_region_p(page)
217 && (page_table[page].bytes_used != 0)
218 && !page_table[page].dont_move
219 && (page_table[page].gen == generation));
222 /* To map addresses to page structures the address of the first page
224 void *heap_base = NULL;
226 /* Calculate the start address for the given page number. */
228 page_address(page_index_t page_num)
230 return (heap_base + (page_num * GENCGC_CARD_BYTES));
233 /* Calculate the address where the allocation region associated with
234 * the page starts. */
236 page_scan_start(page_index_t page_index)
238 return page_address(page_index)-page_table[page_index].scan_start_offset;
241 /* True if the page starts a contiguous block. */
242 static inline boolean
243 page_starts_contiguous_block_p(page_index_t page_index)
245 return page_table[page_index].scan_start_offset == 0;
248 /* True if the page is the last page in a contiguous block. */
249 static inline boolean
250 page_ends_contiguous_block_p(page_index_t page_index, generation_index_t gen)
252 return (/* page doesn't fill block */
253 (page_table[page_index].bytes_used < GENCGC_CARD_BYTES)
255 || page_free_p(page_index + 1)
256 /* next page contains no data */
257 || (page_table[page_index + 1].bytes_used == 0)
258 /* next page is in different generation */
259 || (page_table[page_index + 1].gen != gen)
260 /* next page starts its own contiguous block */
261 || (page_starts_contiguous_block_p(page_index + 1)));
264 /* Find the page index within the page_table for the given
265 * address. Return -1 on failure. */
267 find_page_index(void *addr)
269 if (addr >= heap_base) {
270 page_index_t index = ((pointer_sized_uint_t)addr -
271 (pointer_sized_uint_t)heap_base) / GENCGC_CARD_BYTES;
272 if (index < page_table_pages)
279 npage_bytes(page_index_t npages)
281 gc_assert(npages>=0);
282 return ((os_vm_size_t)npages)*GENCGC_CARD_BYTES;
285 /* Check that X is a higher address than Y and return offset from Y to
287 static inline os_vm_size_t
288 void_diff(void *x, void *y)
291 return (pointer_sized_uint_t)x - (pointer_sized_uint_t)y;
294 /* a structure to hold the state of a generation
296 * CAUTION: If you modify this, make sure to touch up the alien
297 * definition in src/code/gc.lisp accordingly. ...or better yes,
298 * deal with the FIXME there...
302 /* the first page that gc_alloc() checks on its next call */
303 page_index_t alloc_start_page;
305 /* the first page that gc_alloc_unboxed() checks on its next call */
306 page_index_t alloc_unboxed_start_page;
308 /* the first page that gc_alloc_large (boxed) considers on its next
309 * call. (Although it always allocates after the boxed_region.) */
310 page_index_t alloc_large_start_page;
312 /* the first page that gc_alloc_large (unboxed) considers on its
313 * next call. (Although it always allocates after the
314 * current_unboxed_region.) */
315 page_index_t alloc_large_unboxed_start_page;
317 /* the bytes allocated to this generation */
318 os_vm_size_t bytes_allocated;
320 /* the number of bytes at which to trigger a GC */
321 os_vm_size_t gc_trigger;
323 /* to calculate a new level for gc_trigger */
324 os_vm_size_t bytes_consed_between_gc;
326 /* the number of GCs since the last raise */
329 /* the number of GCs to run on the generations before raising objects to the
331 int number_of_gcs_before_promotion;
333 /* the cumulative sum of the bytes allocated to this generation. It is
334 * cleared after a GC on this generations, and update before new
335 * objects are added from a GC of a younger generation. Dividing by
336 * the bytes_allocated will give the average age of the memory in
337 * this generation since its last GC. */
338 os_vm_size_t cum_sum_bytes_allocated;
340 /* a minimum average memory age before a GC will occur helps
341 * prevent a GC when a large number of new live objects have been
342 * added, in which case a GC could be a waste of time */
343 double minimum_age_before_gc;
346 /* an array of generation structures. There needs to be one more
347 * generation structure than actual generations as the oldest
348 * generation is temporarily raised then lowered. */
349 struct generation generations[NUM_GENERATIONS];
351 /* the oldest generation that is will currently be GCed by default.
352 * Valid values are: 0, 1, ... HIGHEST_NORMAL_GENERATION
354 * The default of HIGHEST_NORMAL_GENERATION enables GC on all generations.
356 * Setting this to 0 effectively disables the generational nature of
357 * the GC. In some applications generational GC may not be useful
358 * because there are no long-lived objects.
360 * An intermediate value could be handy after moving long-lived data
361 * into an older generation so an unnecessary GC of this long-lived
362 * data can be avoided. */
363 generation_index_t gencgc_oldest_gen_to_gc = HIGHEST_NORMAL_GENERATION;
365 /* The maximum free page in the heap is maintained and used to update
366 * ALLOCATION_POINTER which is used by the room function to limit its
367 * search of the heap. XX Gencgc obviously needs to be better
368 * integrated with the Lisp code. */
369 page_index_t last_free_page;
371 #ifdef LISP_FEATURE_SB_THREAD
372 /* This lock is to prevent multiple threads from simultaneously
373 * allocating new regions which overlap each other. Note that the
374 * majority of GC is single-threaded, but alloc() may be called from
375 * >1 thread at a time and must be thread-safe. This lock must be
376 * seized before all accesses to generations[] or to parts of
377 * page_table[] that other threads may want to see */
378 static pthread_mutex_t free_pages_lock = PTHREAD_MUTEX_INITIALIZER;
379 /* This lock is used to protect non-thread-local allocation. */
380 static pthread_mutex_t allocation_lock = PTHREAD_MUTEX_INITIALIZER;
383 extern os_vm_size_t gencgc_release_granularity;
384 os_vm_size_t gencgc_release_granularity = GENCGC_RELEASE_GRANULARITY;
386 extern os_vm_size_t gencgc_alloc_granularity;
387 os_vm_size_t gencgc_alloc_granularity = GENCGC_ALLOC_GRANULARITY;
391 * miscellaneous heap functions
394 /* Count the number of pages which are write-protected within the
395 * given generation. */
397 count_write_protect_generation_pages(generation_index_t generation)
399 page_index_t i, count = 0;
401 for (i = 0; i < last_free_page; i++)
402 if (page_allocated_p(i)
403 && (page_table[i].gen == generation)
404 && (page_table[i].write_protected == 1))
409 /* Count the number of pages within the given generation. */
411 count_generation_pages(generation_index_t generation)
414 page_index_t count = 0;
416 for (i = 0; i < last_free_page; i++)
417 if (page_allocated_p(i)
418 && (page_table[i].gen == generation))
425 count_dont_move_pages(void)
428 page_index_t count = 0;
429 for (i = 0; i < last_free_page; i++) {
430 if (page_allocated_p(i)
431 && (page_table[i].dont_move != 0)) {
439 /* Work through the pages and add up the number of bytes used for the
440 * given generation. */
442 count_generation_bytes_allocated (generation_index_t gen)
445 os_vm_size_t result = 0;
446 for (i = 0; i < last_free_page; i++) {
447 if (page_allocated_p(i)
448 && (page_table[i].gen == gen))
449 result += page_table[i].bytes_used;
454 /* Return the average age of the memory in a generation. */
456 generation_average_age(generation_index_t gen)
458 if (generations[gen].bytes_allocated == 0)
462 ((double)generations[gen].cum_sum_bytes_allocated)
463 / ((double)generations[gen].bytes_allocated);
467 write_generation_stats(FILE *file)
469 generation_index_t i;
471 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
472 #define FPU_STATE_SIZE 27
473 int fpu_state[FPU_STATE_SIZE];
474 #elif defined(LISP_FEATURE_PPC)
475 #define FPU_STATE_SIZE 32
476 long long fpu_state[FPU_STATE_SIZE];
477 #elif defined(LISP_FEATURE_SPARC)
479 * 32 (single-precision) FP registers, and the FP state register.
480 * But Sparc V9 has 32 double-precision registers (equivalent to 64
481 * single-precision, but can't be accessed), so we leave enough room
484 #define FPU_STATE_SIZE (((32 + 32 + 1) + 1)/2)
485 long long fpu_state[FPU_STATE_SIZE];
488 /* This code uses the FP instructions which may be set up for Lisp
489 * so they need to be saved and reset for C. */
492 /* Print the heap stats. */
494 " Gen StaPg UbSta LaSta LUbSt Boxed Unboxed LB LUB !move Alloc Waste Trig WP GCs Mem-age\n");
496 for (i = 0; i < SCRATCH_GENERATION; i++) {
498 page_index_t boxed_cnt = 0;
499 page_index_t unboxed_cnt = 0;
500 page_index_t large_boxed_cnt = 0;
501 page_index_t large_unboxed_cnt = 0;
502 page_index_t pinned_cnt=0;
504 for (j = 0; j < last_free_page; j++)
505 if (page_table[j].gen == i) {
507 /* Count the number of boxed pages within the given
509 if (page_boxed_p(j)) {
510 if (page_table[j].large_object)
515 if(page_table[j].dont_move) pinned_cnt++;
516 /* Count the number of unboxed pages within the given
518 if (page_unboxed_p(j)) {
519 if (page_table[j].large_object)
526 gc_assert(generations[i].bytes_allocated
527 == count_generation_bytes_allocated(i));
529 " %1d: %5ld %5ld %5ld %5ld",
531 generations[i].alloc_start_page,
532 generations[i].alloc_unboxed_start_page,
533 generations[i].alloc_large_start_page,
534 generations[i].alloc_large_unboxed_start_page);
536 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT
537 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT,
538 boxed_cnt, unboxed_cnt, large_boxed_cnt,
539 large_unboxed_cnt, pinned_cnt);
544 " %4"PAGE_INDEX_FMT" %3d %7.4f\n",
545 generations[i].bytes_allocated,
546 (npage_bytes(count_generation_pages(i)) - generations[i].bytes_allocated),
547 generations[i].gc_trigger,
548 count_write_protect_generation_pages(i),
549 generations[i].num_gc,
550 generation_average_age(i));
552 fprintf(file," Total bytes allocated = %"OS_VM_SIZE_FMT"\n", bytes_allocated);
553 fprintf(file," Dynamic-space-size bytes = %"OS_VM_SIZE_FMT"\n", dynamic_space_size);
555 fpu_restore(fpu_state);
559 write_heap_exhaustion_report(FILE *file, long available, long requested,
560 struct thread *thread)
563 "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
564 gc_active_p ? "garbage collection" : "allocation",
567 write_generation_stats(file);
568 fprintf(file, "GC control variables:\n");
569 fprintf(file, " *GC-INHIBIT* = %s\n *GC-PENDING* = %s\n",
570 SymbolValue(GC_INHIBIT,thread)==NIL ? "false" : "true",
571 (SymbolValue(GC_PENDING, thread) == T) ?
572 "true" : ((SymbolValue(GC_PENDING, thread) == NIL) ?
573 "false" : "in progress"));
574 #ifdef LISP_FEATURE_SB_THREAD
575 fprintf(file, " *STOP-FOR-GC-PENDING* = %s\n",
576 SymbolValue(STOP_FOR_GC_PENDING,thread)==NIL ? "false" : "true");
581 print_generation_stats(void)
583 write_generation_stats(stderr);
586 extern char* gc_logfile;
587 char * gc_logfile = NULL;
590 log_generation_stats(char *logfile, char *header)
593 FILE * log = fopen(logfile, "a");
595 fprintf(log, "%s\n", header);
596 write_generation_stats(log);
599 fprintf(stderr, "Could not open gc logfile: %s\n", logfile);
606 report_heap_exhaustion(long available, long requested, struct thread *th)
609 FILE * log = fopen(gc_logfile, "a");
611 write_heap_exhaustion_report(log, available, requested, th);
614 fprintf(stderr, "Could not open gc logfile: %s\n", gc_logfile);
618 /* Always to stderr as well. */
619 write_heap_exhaustion_report(stderr, available, requested, th);
623 #if defined(LISP_FEATURE_X86)
624 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
627 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
628 * if zeroing it ourselves, i.e. in practice give the memory back to the
629 * OS. Generally done after a large GC.
631 void zero_pages_with_mmap(page_index_t start, page_index_t end) {
633 void *addr = page_address(start), *new_addr;
634 os_vm_size_t length = npage_bytes(1+end-start);
639 gc_assert(length >= gencgc_release_granularity);
640 gc_assert((length % gencgc_release_granularity) == 0);
642 os_invalidate(addr, length);
643 new_addr = os_validate(addr, length);
644 if (new_addr == NULL || new_addr != addr) {
645 lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
649 for (i = start; i <= end; i++) {
650 page_table[i].need_to_zero = 0;
654 /* Zero the pages from START to END (inclusive). Generally done just after
655 * a new region has been allocated.
658 zero_pages(page_index_t start, page_index_t end) {
662 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
663 fast_bzero(page_address(start), npage_bytes(1+end-start));
665 bzero(page_address(start), npage_bytes(1+end-start));
671 zero_and_mark_pages(page_index_t start, page_index_t end) {
674 zero_pages(start, end);
675 for (i = start; i <= end; i++)
676 page_table[i].need_to_zero = 0;
679 /* Zero the pages from START to END (inclusive), except for those
680 * pages that are known to already zeroed. Mark all pages in the
681 * ranges as non-zeroed.
684 zero_dirty_pages(page_index_t start, page_index_t end) {
687 for (i = start; i <= end; i++) {
688 if (!page_table[i].need_to_zero) continue;
689 for (j = i+1; (j <= end) && (page_table[j].need_to_zero); j++);
694 for (i = start; i <= end; i++) {
695 page_table[i].need_to_zero = 1;
701 * To support quick and inline allocation, regions of memory can be
702 * allocated and then allocated from with just a free pointer and a
703 * check against an end address.
705 * Since objects can be allocated to spaces with different properties
706 * e.g. boxed/unboxed, generation, ages; there may need to be many
707 * allocation regions.
709 * Each allocation region may start within a partly used page. Many
710 * features of memory use are noted on a page wise basis, e.g. the
711 * generation; so if a region starts within an existing allocated page
712 * it must be consistent with this page.
714 * During the scavenging of the newspace, objects will be transported
715 * into an allocation region, and pointers updated to point to this
716 * allocation region. It is possible that these pointers will be
717 * scavenged again before the allocation region is closed, e.g. due to
718 * trans_list which jumps all over the place to cleanup the list. It
719 * is important to be able to determine properties of all objects
720 * pointed to when scavenging, e.g to detect pointers to the oldspace.
721 * Thus it's important that the allocation regions have the correct
722 * properties set when allocated, and not just set when closed. The
723 * region allocation routines return regions with the specified
724 * properties, and grab all the pages, setting their properties
725 * appropriately, except that the amount used is not known.
727 * These regions are used to support quicker allocation using just a
728 * free pointer. The actual space used by the region is not reflected
729 * in the pages tables until it is closed. It can't be scavenged until
732 * When finished with the region it should be closed, which will
733 * update the page tables for the actual space used returning unused
734 * space. Further it may be noted in the new regions which is
735 * necessary when scavenging the newspace.
737 * Large objects may be allocated directly without an allocation
738 * region, the page tables are updated immediately.
740 * Unboxed objects don't contain pointers to other objects and so
741 * don't need scavenging. Further they can't contain pointers to
742 * younger generations so WP is not needed. By allocating pages to
743 * unboxed objects the whole page never needs scavenging or
744 * write-protecting. */
746 /* We are only using two regions at present. Both are for the current
747 * newspace generation. */
748 struct alloc_region boxed_region;
749 struct alloc_region unboxed_region;
751 /* The generation currently being allocated to. */
752 static generation_index_t gc_alloc_generation;
754 static inline page_index_t
755 generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large)
758 if (UNBOXED_PAGE_FLAG == page_type_flag) {
759 return generations[generation].alloc_large_unboxed_start_page;
760 } else if (BOXED_PAGE_FLAG & page_type_flag) {
761 /* Both code and data. */
762 return generations[generation].alloc_large_start_page;
764 lose("bad page type flag: %d", page_type_flag);
767 if (UNBOXED_PAGE_FLAG == page_type_flag) {
768 return generations[generation].alloc_unboxed_start_page;
769 } else if (BOXED_PAGE_FLAG & page_type_flag) {
770 /* Both code and data. */
771 return generations[generation].alloc_start_page;
773 lose("bad page_type_flag: %d", page_type_flag);
779 set_generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large,
783 if (UNBOXED_PAGE_FLAG == page_type_flag) {
784 generations[generation].alloc_large_unboxed_start_page = page;
785 } else if (BOXED_PAGE_FLAG & page_type_flag) {
786 /* Both code and data. */
787 generations[generation].alloc_large_start_page = page;
789 lose("bad page type flag: %d", page_type_flag);
792 if (UNBOXED_PAGE_FLAG == page_type_flag) {
793 generations[generation].alloc_unboxed_start_page = page;
794 } else if (BOXED_PAGE_FLAG & page_type_flag) {
795 /* Both code and data. */
796 generations[generation].alloc_start_page = page;
798 lose("bad page type flag: %d", page_type_flag);
803 /* Find a new region with room for at least the given number of bytes.
805 * It starts looking at the current generation's alloc_start_page. So
806 * may pick up from the previous region if there is enough space. This
807 * keeps the allocation contiguous when scavenging the newspace.
809 * The alloc_region should have been closed by a call to
810 * gc_alloc_update_page_tables(), and will thus be in an empty state.
812 * To assist the scavenging functions write-protected pages are not
813 * used. Free pages should not be write-protected.
815 * It is critical to the conservative GC that the start of regions be
816 * known. To help achieve this only small regions are allocated at a
819 * During scavenging, pointers may be found to within the current
820 * region and the page generation must be set so that pointers to the
821 * from space can be recognized. Therefore the generation of pages in
822 * the region are set to gc_alloc_generation. To prevent another
823 * allocation call using the same pages, all the pages in the region
824 * are allocated, although they will initially be empty.
827 gc_alloc_new_region(sword_t nbytes, int page_type_flag, struct alloc_region *alloc_region)
829 page_index_t first_page;
830 page_index_t last_page;
831 os_vm_size_t bytes_found;
837 "/alloc_new_region for %d bytes from gen %d\n",
838 nbytes, gc_alloc_generation));
841 /* Check that the region is in a reset state. */
842 gc_assert((alloc_region->first_page == 0)
843 && (alloc_region->last_page == -1)
844 && (alloc_region->free_pointer == alloc_region->end_addr));
845 ret = thread_mutex_lock(&free_pages_lock);
847 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0);
848 last_page=gc_find_freeish_pages(&first_page, nbytes, page_type_flag);
849 bytes_found=(GENCGC_CARD_BYTES - page_table[first_page].bytes_used)
850 + npage_bytes(last_page-first_page);
852 /* Set up the alloc_region. */
853 alloc_region->first_page = first_page;
854 alloc_region->last_page = last_page;
855 alloc_region->start_addr = page_table[first_page].bytes_used
856 + page_address(first_page);
857 alloc_region->free_pointer = alloc_region->start_addr;
858 alloc_region->end_addr = alloc_region->start_addr + bytes_found;
860 /* Set up the pages. */
862 /* The first page may have already been in use. */
863 if (page_table[first_page].bytes_used == 0) {
864 page_table[first_page].allocated = page_type_flag;
865 page_table[first_page].gen = gc_alloc_generation;
866 page_table[first_page].large_object = 0;
867 page_table[first_page].scan_start_offset = 0;
870 gc_assert(page_table[first_page].allocated == page_type_flag);
871 page_table[first_page].allocated |= OPEN_REGION_PAGE_FLAG;
873 gc_assert(page_table[first_page].gen == gc_alloc_generation);
874 gc_assert(page_table[first_page].large_object == 0);
876 for (i = first_page+1; i <= last_page; i++) {
877 page_table[i].allocated = page_type_flag;
878 page_table[i].gen = gc_alloc_generation;
879 page_table[i].large_object = 0;
880 /* This may not be necessary for unboxed regions (think it was
882 page_table[i].scan_start_offset =
883 void_diff(page_address(i),alloc_region->start_addr);
884 page_table[i].allocated |= OPEN_REGION_PAGE_FLAG ;
886 /* Bump up last_free_page. */
887 if (last_page+1 > last_free_page) {
888 last_free_page = last_page+1;
889 /* do we only want to call this on special occasions? like for
891 set_alloc_pointer((lispobj)page_address(last_free_page));
893 ret = thread_mutex_unlock(&free_pages_lock);
896 #ifdef READ_PROTECT_FREE_PAGES
897 os_protect(page_address(first_page),
898 npage_bytes(1+last_page-first_page),
902 /* If the first page was only partial, don't check whether it's
903 * zeroed (it won't be) and don't zero it (since the parts that
904 * we're interested in are guaranteed to be zeroed).
906 if (page_table[first_page].bytes_used) {
910 zero_dirty_pages(first_page, last_page);
912 /* we can do this after releasing free_pages_lock */
913 if (gencgc_zero_check) {
915 for (p = (word_t *)alloc_region->start_addr;
916 p < (word_t *)alloc_region->end_addr; p++) {
918 lose("The new region is not zero at %p (start=%p, end=%p).\n",
919 p, alloc_region->start_addr, alloc_region->end_addr);
925 /* If the record_new_objects flag is 2 then all new regions created
928 * If it's 1 then then it is only recorded if the first page of the
929 * current region is <= new_areas_ignore_page. This helps avoid
930 * unnecessary recording when doing full scavenge pass.
932 * The new_object structure holds the page, byte offset, and size of
933 * new regions of objects. Each new area is placed in the array of
934 * these structures pointer to by new_areas. new_areas_index holds the
935 * offset into new_areas.
937 * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
938 * later code must detect this and handle it, probably by doing a full
939 * scavenge of a generation. */
940 #define NUM_NEW_AREAS 512
941 static int record_new_objects = 0;
942 static page_index_t new_areas_ignore_page;
948 static struct new_area (*new_areas)[];
949 static size_t new_areas_index;
950 size_t max_new_areas;
952 /* Add a new area to new_areas. */
954 add_new_area(page_index_t first_page, size_t offset, size_t size)
956 size_t new_area_start, c;
959 /* Ignore if full. */
960 if (new_areas_index >= NUM_NEW_AREAS)
963 switch (record_new_objects) {
967 if (first_page > new_areas_ignore_page)
976 new_area_start = npage_bytes(first_page) + offset;
978 /* Search backwards for a prior area that this follows from. If
979 found this will save adding a new area. */
980 for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
982 npage_bytes((*new_areas)[i].page)
983 + (*new_areas)[i].offset
984 + (*new_areas)[i].size;
986 "/add_new_area S1 %d %d %d %d\n",
987 i, c, new_area_start, area_end));*/
988 if (new_area_start == area_end) {
990 "/adding to [%d] %d %d %d with %d %d %d:\n",
992 (*new_areas)[i].page,
993 (*new_areas)[i].offset,
994 (*new_areas)[i].size,
998 (*new_areas)[i].size += size;
1003 (*new_areas)[new_areas_index].page = first_page;
1004 (*new_areas)[new_areas_index].offset = offset;
1005 (*new_areas)[new_areas_index].size = size;
1007 "/new_area %d page %d offset %d size %d\n",
1008 new_areas_index, first_page, offset, size));*/
1011 /* Note the max new_areas used. */
1012 if (new_areas_index > max_new_areas)
1013 max_new_areas = new_areas_index;
1016 /* Update the tables for the alloc_region. The region may be added to
1019 * When done the alloc_region is set up so that the next quick alloc
1020 * will fail safely and thus a new region will be allocated. Further
1021 * it is safe to try to re-update the page table of this reset
1024 gc_alloc_update_page_tables(int page_type_flag, struct alloc_region *alloc_region)
1027 page_index_t first_page;
1028 page_index_t next_page;
1029 os_vm_size_t bytes_used;
1030 os_vm_size_t region_size;
1031 os_vm_size_t byte_cnt;
1032 page_bytes_t orig_first_page_bytes_used;
1036 first_page = alloc_region->first_page;
1038 /* Catch an unused alloc_region. */
1039 if ((first_page == 0) && (alloc_region->last_page == -1))
1042 next_page = first_page+1;
1044 ret = thread_mutex_lock(&free_pages_lock);
1045 gc_assert(ret == 0);
1046 if (alloc_region->free_pointer != alloc_region->start_addr) {
1047 /* some bytes were allocated in the region */
1048 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1050 gc_assert(alloc_region->start_addr ==
1051 (page_address(first_page)
1052 + page_table[first_page].bytes_used));
1054 /* All the pages used need to be updated */
1056 /* Update the first page. */
1058 /* If the page was free then set up the gen, and
1059 * scan_start_offset. */
1060 if (page_table[first_page].bytes_used == 0)
1061 gc_assert(page_starts_contiguous_block_p(first_page));
1062 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1064 gc_assert(page_table[first_page].allocated & page_type_flag);
1065 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1066 gc_assert(page_table[first_page].large_object == 0);
1070 /* Calculate the number of bytes used in this page. This is not
1071 * always the number of new bytes, unless it was free. */
1073 if ((bytes_used = void_diff(alloc_region->free_pointer,
1074 page_address(first_page)))
1075 >GENCGC_CARD_BYTES) {
1076 bytes_used = GENCGC_CARD_BYTES;
1079 page_table[first_page].bytes_used = bytes_used;
1080 byte_cnt += bytes_used;
1083 /* All the rest of the pages should be free. We need to set
1084 * their scan_start_offset pointer to the start of the
1085 * region, and set the bytes_used. */
1087 page_table[next_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1088 gc_assert(page_table[next_page].allocated & page_type_flag);
1089 gc_assert(page_table[next_page].bytes_used == 0);
1090 gc_assert(page_table[next_page].gen == gc_alloc_generation);
1091 gc_assert(page_table[next_page].large_object == 0);
1093 gc_assert(page_table[next_page].scan_start_offset ==
1094 void_diff(page_address(next_page),
1095 alloc_region->start_addr));
1097 /* Calculate the number of bytes used in this page. */
1099 if ((bytes_used = void_diff(alloc_region->free_pointer,
1100 page_address(next_page)))>GENCGC_CARD_BYTES) {
1101 bytes_used = GENCGC_CARD_BYTES;
1104 page_table[next_page].bytes_used = bytes_used;
1105 byte_cnt += bytes_used;
1110 region_size = void_diff(alloc_region->free_pointer,
1111 alloc_region->start_addr);
1112 bytes_allocated += region_size;
1113 generations[gc_alloc_generation].bytes_allocated += region_size;
1115 gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
1117 /* Set the generations alloc restart page to the last page of
1119 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0, next_page-1);
1121 /* Add the region to the new_areas if requested. */
1122 if (BOXED_PAGE_FLAG & page_type_flag)
1123 add_new_area(first_page,orig_first_page_bytes_used, region_size);
1127 "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1129 gc_alloc_generation));
1132 /* There are no bytes allocated. Unallocate the first_page if
1133 * there are 0 bytes_used. */
1134 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1135 if (page_table[first_page].bytes_used == 0)
1136 page_table[first_page].allocated = FREE_PAGE_FLAG;
1139 /* Unallocate any unused pages. */
1140 while (next_page <= alloc_region->last_page) {
1141 gc_assert(page_table[next_page].bytes_used == 0);
1142 page_table[next_page].allocated = FREE_PAGE_FLAG;
1145 ret = thread_mutex_unlock(&free_pages_lock);
1146 gc_assert(ret == 0);
1148 /* alloc_region is per-thread, we're ok to do this unlocked */
1149 gc_set_region_empty(alloc_region);
1152 static inline void *gc_quick_alloc(word_t nbytes);
1154 /* Allocate a possibly large object. */
1156 gc_alloc_large(sword_t nbytes, int page_type_flag, struct alloc_region *alloc_region)
1159 page_index_t first_page, next_page, last_page;
1160 page_bytes_t orig_first_page_bytes_used;
1161 os_vm_size_t byte_cnt;
1162 os_vm_size_t bytes_used;
1165 ret = thread_mutex_lock(&free_pages_lock);
1166 gc_assert(ret == 0);
1168 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1);
1169 if (first_page <= alloc_region->last_page) {
1170 first_page = alloc_region->last_page+1;
1173 last_page=gc_find_freeish_pages(&first_page,nbytes, page_type_flag);
1175 gc_assert(first_page > alloc_region->last_page);
1177 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1, last_page);
1179 /* Set up the pages. */
1180 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1182 /* If the first page was free then set up the gen, and
1183 * scan_start_offset. */
1184 if (page_table[first_page].bytes_used == 0) {
1185 page_table[first_page].allocated = page_type_flag;
1186 page_table[first_page].gen = gc_alloc_generation;
1187 page_table[first_page].scan_start_offset = 0;
1188 page_table[first_page].large_object = 1;
1191 gc_assert(page_table[first_page].allocated == page_type_flag);
1192 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1193 gc_assert(page_table[first_page].large_object == 1);
1197 /* Calc. the number of bytes used in this page. This is not
1198 * always the number of new bytes, unless it was free. */
1200 if ((bytes_used = nbytes+orig_first_page_bytes_used) > GENCGC_CARD_BYTES) {
1201 bytes_used = GENCGC_CARD_BYTES;
1204 page_table[first_page].bytes_used = bytes_used;
1205 byte_cnt += bytes_used;
1207 next_page = first_page+1;
1209 /* All the rest of the pages should be free. We need to set their
1210 * scan_start_offset pointer to the start of the region, and set
1211 * the bytes_used. */
1213 gc_assert(page_free_p(next_page));
1214 gc_assert(page_table[next_page].bytes_used == 0);
1215 page_table[next_page].allocated = page_type_flag;
1216 page_table[next_page].gen = gc_alloc_generation;
1217 page_table[next_page].large_object = 1;
1219 page_table[next_page].scan_start_offset =
1220 npage_bytes(next_page-first_page) - orig_first_page_bytes_used;
1222 /* Calculate the number of bytes used in this page. */
1224 bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt;
1225 if (bytes_used > GENCGC_CARD_BYTES) {
1226 bytes_used = GENCGC_CARD_BYTES;
1229 page_table[next_page].bytes_used = bytes_used;
1230 page_table[next_page].write_protected=0;
1231 page_table[next_page].dont_move=0;
1232 byte_cnt += bytes_used;
1236 gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
1238 bytes_allocated += nbytes;
1239 generations[gc_alloc_generation].bytes_allocated += nbytes;
1241 /* Add the region to the new_areas if requested. */
1242 if (BOXED_PAGE_FLAG & page_type_flag)
1243 add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1245 /* Bump up last_free_page */
1246 if (last_page+1 > last_free_page) {
1247 last_free_page = last_page+1;
1248 set_alloc_pointer((lispobj)(page_address(last_free_page)));
1250 ret = thread_mutex_unlock(&free_pages_lock);
1251 gc_assert(ret == 0);
1253 #ifdef READ_PROTECT_FREE_PAGES
1254 os_protect(page_address(first_page),
1255 npage_bytes(1+last_page-first_page),
1259 zero_dirty_pages(first_page, last_page);
1261 return page_address(first_page);
1264 static page_index_t gencgc_alloc_start_page = -1;
1267 gc_heap_exhausted_error_or_lose (sword_t available, sword_t requested)
1269 struct thread *thread = arch_os_get_current_thread();
1270 /* Write basic information before doing anything else: if we don't
1271 * call to lisp this is a must, and even if we do there is always
1272 * the danger that we bounce back here before the error has been
1273 * handled, or indeed even printed.
1275 report_heap_exhaustion(available, requested, thread);
1276 if (gc_active_p || (available == 0)) {
1277 /* If we are in GC, or totally out of memory there is no way
1278 * to sanely transfer control to the lisp-side of things.
1280 lose("Heap exhausted, game over.");
1283 /* FIXME: assert free_pages_lock held */
1284 (void)thread_mutex_unlock(&free_pages_lock);
1285 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
1286 gc_assert(get_pseudo_atomic_atomic(thread));
1287 clear_pseudo_atomic_atomic(thread);
1288 if (get_pseudo_atomic_interrupted(thread))
1289 do_pending_interrupt();
1291 /* Another issue is that signalling HEAP-EXHAUSTED error leads
1292 * to running user code at arbitrary places, even in a
1293 * WITHOUT-INTERRUPTS which may lead to a deadlock without
1294 * running out of the heap. So at this point all bets are
1296 if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
1297 corruption_warning_and_maybe_lose
1298 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1299 funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR),
1300 alloc_number(available), alloc_number(requested));
1301 lose("HEAP-EXHAUSTED-ERROR fell through");
1306 gc_find_freeish_pages(page_index_t *restart_page_ptr, sword_t bytes,
1309 page_index_t most_bytes_found_from = 0, most_bytes_found_to = 0;
1310 page_index_t first_page, last_page, restart_page = *restart_page_ptr;
1311 os_vm_size_t nbytes = bytes;
1312 os_vm_size_t nbytes_goal = nbytes;
1313 os_vm_size_t bytes_found = 0;
1314 os_vm_size_t most_bytes_found = 0;
1315 boolean small_object = nbytes < GENCGC_CARD_BYTES;
1316 /* FIXME: assert(free_pages_lock is held); */
1318 if (nbytes_goal < gencgc_alloc_granularity)
1319 nbytes_goal = gencgc_alloc_granularity;
1321 /* Toggled by gc_and_save for heap compaction, normally -1. */
1322 if (gencgc_alloc_start_page != -1) {
1323 restart_page = gencgc_alloc_start_page;
1326 /* FIXME: This is on bytes instead of nbytes pending cleanup of
1327 * long from the interface. */
1328 gc_assert(bytes>=0);
1329 /* Search for a page with at least nbytes of space. We prefer
1330 * not to split small objects on multiple pages, to reduce the
1331 * number of contiguous allocation regions spaning multiple
1332 * pages: this helps avoid excessive conservativism.
1334 * For other objects, we guarantee that they start on their own
1337 first_page = restart_page;
1338 while (first_page < page_table_pages) {
1340 if (page_free_p(first_page)) {
1341 gc_assert(0 == page_table[first_page].bytes_used);
1342 bytes_found = GENCGC_CARD_BYTES;
1343 } else if (small_object &&
1344 (page_table[first_page].allocated == page_type_flag) &&
1345 (page_table[first_page].large_object == 0) &&
1346 (page_table[first_page].gen == gc_alloc_generation) &&
1347 (page_table[first_page].write_protected == 0) &&
1348 (page_table[first_page].dont_move == 0)) {
1349 bytes_found = GENCGC_CARD_BYTES - page_table[first_page].bytes_used;
1350 if (bytes_found < nbytes) {
1351 if (bytes_found > most_bytes_found)
1352 most_bytes_found = bytes_found;
1361 gc_assert(page_table[first_page].write_protected == 0);
1362 for (last_page = first_page+1;
1363 ((last_page < page_table_pages) &&
1364 page_free_p(last_page) &&
1365 (bytes_found < nbytes_goal));
1367 bytes_found += GENCGC_CARD_BYTES;
1368 gc_assert(0 == page_table[last_page].bytes_used);
1369 gc_assert(0 == page_table[last_page].write_protected);
1372 if (bytes_found > most_bytes_found) {
1373 most_bytes_found = bytes_found;
1374 most_bytes_found_from = first_page;
1375 most_bytes_found_to = last_page;
1377 if (bytes_found >= nbytes_goal)
1380 first_page = last_page;
1383 bytes_found = most_bytes_found;
1384 restart_page = first_page + 1;
1386 /* Check for a failure */
1387 if (bytes_found < nbytes) {
1388 gc_assert(restart_page >= page_table_pages);
1389 gc_heap_exhausted_error_or_lose(most_bytes_found, nbytes);
1392 gc_assert(most_bytes_found_to);
1393 *restart_page_ptr = most_bytes_found_from;
1394 return most_bytes_found_to-1;
1397 /* Allocate bytes. All the rest of the special-purpose allocation
1398 * functions will eventually call this */
1401 gc_alloc_with_region(sword_t nbytes,int page_type_flag, struct alloc_region *my_region,
1404 void *new_free_pointer;
1406 if (nbytes>=large_object_size)
1407 return gc_alloc_large(nbytes, page_type_flag, my_region);
1409 /* Check whether there is room in the current alloc region. */
1410 new_free_pointer = my_region->free_pointer + nbytes;
1412 /* fprintf(stderr, "alloc %d bytes from %p to %p\n", nbytes,
1413 my_region->free_pointer, new_free_pointer); */
1415 if (new_free_pointer <= my_region->end_addr) {
1416 /* If so then allocate from the current alloc region. */
1417 void *new_obj = my_region->free_pointer;
1418 my_region->free_pointer = new_free_pointer;
1420 /* Unless a `quick' alloc was requested, check whether the
1421 alloc region is almost empty. */
1423 void_diff(my_region->end_addr,my_region->free_pointer) <= 32) {
1424 /* If so, finished with the current region. */
1425 gc_alloc_update_page_tables(page_type_flag, my_region);
1426 /* Set up a new region. */
1427 gc_alloc_new_region(32 /*bytes*/, page_type_flag, my_region);
1430 return((void *)new_obj);
1433 /* Else not enough free space in the current region: retry with a
1436 gc_alloc_update_page_tables(page_type_flag, my_region);
1437 gc_alloc_new_region(nbytes, page_type_flag, my_region);
1438 return gc_alloc_with_region(nbytes, page_type_flag, my_region,0);
1441 /* these are only used during GC: all allocation from the mutator calls
1442 * alloc() -> gc_alloc_with_region() with the appropriate per-thread
1445 static inline void *
1446 gc_quick_alloc(word_t nbytes)
1448 return gc_general_alloc(nbytes, BOXED_PAGE_FLAG, ALLOC_QUICK);
1451 static inline void *
1452 gc_alloc_unboxed(word_t nbytes)
1454 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, 0);
1457 static inline void *
1458 gc_quick_alloc_unboxed(word_t nbytes)
1460 return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, ALLOC_QUICK);
1463 /* Copy a large object. If the object is in a large object region then
1464 * it is simply promoted, else it is copied. If it's large enough then
1465 * it's copied to a large object region.
1467 * Bignums and vectors may have shrunk. If the object is not copied
1468 * the space needs to be reclaimed, and the page_tables corrected. */
1470 general_copy_large_object(lispobj object, word_t nwords, boolean boxedp)
1474 page_index_t first_page;
1476 gc_assert(is_lisp_pointer(object));
1477 gc_assert(from_space_p(object));
1478 gc_assert((nwords & 0x01) == 0);
1480 if ((nwords > 1024*1024) && gencgc_verbose) {
1481 FSHOW((stderr, "/general_copy_large_object: %d bytes\n",
1482 nwords*N_WORD_BYTES));
1485 /* Check whether it's a large object. */
1486 first_page = find_page_index((void *)object);
1487 gc_assert(first_page >= 0);
1489 if (page_table[first_page].large_object) {
1490 /* Promote the object. Note: Unboxed objects may have been
1491 * allocated to a BOXED region so it may be necessary to
1492 * change the region to UNBOXED. */
1493 os_vm_size_t remaining_bytes;
1494 os_vm_size_t bytes_freed;
1495 page_index_t next_page;
1496 page_bytes_t old_bytes_used;
1498 /* FIXME: This comment is somewhat stale.
1500 * Note: Any page write-protection must be removed, else a
1501 * later scavenge_newspace may incorrectly not scavenge these
1502 * pages. This would not be necessary if they are added to the
1503 * new areas, but let's do it for them all (they'll probably
1504 * be written anyway?). */
1506 gc_assert(page_starts_contiguous_block_p(first_page));
1507 next_page = first_page;
1508 remaining_bytes = nwords*N_WORD_BYTES;
1510 while (remaining_bytes > GENCGC_CARD_BYTES) {
1511 gc_assert(page_table[next_page].gen == from_space);
1512 gc_assert(page_table[next_page].large_object);
1513 gc_assert(page_table[next_page].scan_start_offset ==
1514 npage_bytes(next_page-first_page));
1515 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
1516 /* Should have been unprotected by unprotect_oldspace()
1517 * for boxed objects, and after promotion unboxed ones
1518 * should not be on protected pages at all. */
1519 gc_assert(!page_table[next_page].write_protected);
1522 gc_assert(page_boxed_p(next_page));
1524 gc_assert(page_allocated_no_region_p(next_page));
1525 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1527 page_table[next_page].gen = new_space;
1529 remaining_bytes -= GENCGC_CARD_BYTES;
1533 /* Now only one page remains, but the object may have shrunk so
1534 * there may be more unused pages which will be freed. */
1536 /* Object may have shrunk but shouldn't have grown - check. */
1537 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1539 page_table[next_page].gen = new_space;
1542 gc_assert(page_boxed_p(next_page));
1544 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1546 /* Adjust the bytes_used. */
1547 old_bytes_used = page_table[next_page].bytes_used;
1548 page_table[next_page].bytes_used = remaining_bytes;
1550 bytes_freed = old_bytes_used - remaining_bytes;
1552 /* Free any remaining pages; needs care. */
1554 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
1555 (page_table[next_page].gen == from_space) &&
1556 /* FIXME: It is not obvious to me why this is necessary
1557 * as a loop condition: it seems to me that the
1558 * scan_start_offset test should be sufficient, but
1559 * experimentally that is not the case. --NS
1562 page_boxed_p(next_page) :
1563 page_allocated_no_region_p(next_page)) &&
1564 page_table[next_page].large_object &&
1565 (page_table[next_page].scan_start_offset ==
1566 npage_bytes(next_page - first_page))) {
1567 /* Checks out OK, free the page. Don't need to both zeroing
1568 * pages as this should have been done before shrinking the
1569 * object. These pages shouldn't be write-protected, even if
1570 * boxed they should be zero filled. */
1571 gc_assert(page_table[next_page].write_protected == 0);
1573 old_bytes_used = page_table[next_page].bytes_used;
1574 page_table[next_page].allocated = FREE_PAGE_FLAG;
1575 page_table[next_page].bytes_used = 0;
1576 bytes_freed += old_bytes_used;
1580 if ((bytes_freed > 0) && gencgc_verbose) {
1582 "/general_copy_large_object bytes_freed=%"OS_VM_SIZE_FMT"\n",
1586 generations[from_space].bytes_allocated -= nwords*N_WORD_BYTES
1588 generations[new_space].bytes_allocated += nwords*N_WORD_BYTES;
1589 bytes_allocated -= bytes_freed;
1591 /* Add the region to the new_areas if requested. */
1593 add_new_area(first_page,0,nwords*N_WORD_BYTES);
1598 /* Get tag of object. */
1599 tag = lowtag_of(object);
1601 /* Allocate space. */
1602 new = gc_general_alloc(nwords*N_WORD_BYTES,
1603 (boxedp ? BOXED_PAGE_FLAG : UNBOXED_PAGE_FLAG),
1606 /* Copy the object. */
1607 memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1609 /* Return Lisp pointer of new object. */
1610 return ((lispobj) new) | tag;
1615 copy_large_object(lispobj object, sword_t nwords)
1617 return general_copy_large_object(object, nwords, 1);
1621 copy_large_unboxed_object(lispobj object, sword_t nwords)
1623 return general_copy_large_object(object, nwords, 0);
1626 /* to copy unboxed objects */
1628 copy_unboxed_object(lispobj object, sword_t nwords)
1630 return gc_general_copy_object(object, nwords, UNBOXED_PAGE_FLAG);
1635 * code and code-related objects
1638 static lispobj trans_fun_header(lispobj object);
1639 static lispobj trans_boxed(lispobj object);
1642 /* Scan a x86 compiled code object, looking for possible fixups that
1643 * have been missed after a move.
1645 * Two types of fixups are needed:
1646 * 1. Absolute fixups to within the code object.
1647 * 2. Relative fixups to outside the code object.
1649 * Currently only absolute fixups to the constant vector, or to the
1650 * code area are checked. */
1652 sniff_code_object(struct code *code, os_vm_size_t displacement)
1654 #ifdef LISP_FEATURE_X86
1655 sword_t nheader_words, ncode_words, nwords;
1656 os_vm_address_t constants_start_addr = NULL, constants_end_addr, p;
1657 os_vm_address_t code_start_addr, code_end_addr;
1658 os_vm_address_t code_addr = (os_vm_address_t)code;
1659 int fixup_found = 0;
1661 if (!check_code_fixups)
1664 FSHOW((stderr, "/sniffing code: %p, %lu\n", code, displacement));
1666 ncode_words = fixnum_value(code->code_size);
1667 nheader_words = HeaderValue(*(lispobj *)code);
1668 nwords = ncode_words + nheader_words;
1670 constants_start_addr = code_addr + 5*N_WORD_BYTES;
1671 constants_end_addr = code_addr + nheader_words*N_WORD_BYTES;
1672 code_start_addr = code_addr + nheader_words*N_WORD_BYTES;
1673 code_end_addr = code_addr + nwords*N_WORD_BYTES;
1675 /* Work through the unboxed code. */
1676 for (p = code_start_addr; p < code_end_addr; p++) {
1677 void *data = *(void **)p;
1678 unsigned d1 = *((unsigned char *)p - 1);
1679 unsigned d2 = *((unsigned char *)p - 2);
1680 unsigned d3 = *((unsigned char *)p - 3);
1681 unsigned d4 = *((unsigned char *)p - 4);
1683 unsigned d5 = *((unsigned char *)p - 5);
1684 unsigned d6 = *((unsigned char *)p - 6);
1687 /* Check for code references. */
1688 /* Check for a 32 bit word that looks like an absolute
1689 reference to within the code adea of the code object. */
1690 if ((data >= (void*)(code_start_addr-displacement))
1691 && (data < (void*)(code_end_addr-displacement))) {
1692 /* function header */
1694 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) ==
1696 /* Skip the function header */
1700 /* the case of PUSH imm32 */
1704 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1705 p, d6, d5, d4, d3, d2, d1, data));
1706 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1708 /* the case of MOV [reg-8],imm32 */
1710 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1711 || d2==0x45 || d2==0x46 || d2==0x47)
1715 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1716 p, d6, d5, d4, d3, d2, d1, data));
1717 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1719 /* the case of LEA reg,[disp32] */
1720 if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1723 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1724 p, d6, d5, d4, d3, d2, d1, data));
1725 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1729 /* Check for constant references. */
1730 /* Check for a 32 bit word that looks like an absolute
1731 reference to within the constant vector. Constant references
1733 if ((data >= (void*)(constants_start_addr-displacement))
1734 && (data < (void*)(constants_end_addr-displacement))
1735 && (((unsigned)data & 0x3) == 0)) {
1740 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1741 p, d6, d5, d4, d3, d2, d1, data));
1742 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1745 /* the case of MOV m32,EAX */
1749 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1750 p, d6, d5, d4, d3, d2, d1, data));
1751 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1754 /* the case of CMP m32,imm32 */
1755 if ((d1 == 0x3d) && (d2 == 0x81)) {
1758 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1759 p, d6, d5, d4, d3, d2, d1, data));
1761 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1764 /* Check for a mod=00, r/m=101 byte. */
1765 if ((d1 & 0xc7) == 5) {
1770 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1771 p, d6, d5, d4, d3, d2, d1, data));
1772 FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1774 /* the case of CMP reg32,m32 */
1778 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1779 p, d6, d5, d4, d3, d2, d1, data));
1780 FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1782 /* the case of MOV m32,reg32 */
1786 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1787 p, d6, d5, d4, d3, d2, d1, data));
1788 FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1790 /* the case of MOV reg32,m32 */
1794 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1795 p, d6, d5, d4, d3, d2, d1, data));
1796 FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1798 /* the case of LEA reg32,m32 */
1802 "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1803 p, d6, d5, d4, d3, d2, d1, data));
1804 FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1810 /* If anything was found, print some information on the code
1814 "/compiled code object at %x: header words = %d, code words = %d\n",
1815 code, nheader_words, ncode_words));
1817 "/const start = %x, end = %x\n",
1818 constants_start_addr, constants_end_addr));
1820 "/code start = %x, end = %x\n",
1821 code_start_addr, code_end_addr));
1827 gencgc_apply_code_fixups(struct code *old_code, struct code *new_code)
1829 /* x86-64 uses pc-relative addressing instead of this kludge */
1830 #ifndef LISP_FEATURE_X86_64
1831 sword_t nheader_words, ncode_words, nwords;
1832 os_vm_address_t constants_start_addr, constants_end_addr;
1833 os_vm_address_t code_start_addr, code_end_addr;
1834 os_vm_address_t code_addr = (os_vm_address_t)new_code;
1835 os_vm_address_t old_addr = (os_vm_address_t)old_code;
1836 os_vm_size_t displacement = code_addr - old_addr;
1837 lispobj fixups = NIL;
1838 struct vector *fixups_vector;
1840 ncode_words = fixnum_value(new_code->code_size);
1841 nheader_words = HeaderValue(*(lispobj *)new_code);
1842 nwords = ncode_words + nheader_words;
1844 "/compiled code object at %x: header words = %d, code words = %d\n",
1845 new_code, nheader_words, ncode_words)); */
1846 constants_start_addr = code_addr + 5*N_WORD_BYTES;
1847 constants_end_addr = code_addr + nheader_words*N_WORD_BYTES;
1848 code_start_addr = code_addr + nheader_words*N_WORD_BYTES;
1849 code_end_addr = code_addr + nwords*N_WORD_BYTES;
1852 "/const start = %x, end = %x\n",
1853 constants_start_addr,constants_end_addr));
1855 "/code start = %x; end = %x\n",
1856 code_start_addr,code_end_addr));
1859 /* The first constant should be a pointer to the fixups for this
1860 code objects. Check. */
1861 fixups = new_code->constants[0];
1863 /* It will be 0 or the unbound-marker if there are no fixups (as
1864 * will be the case if the code object has been purified, for
1865 * example) and will be an other pointer if it is valid. */
1866 if ((fixups == 0) || (fixups == UNBOUND_MARKER_WIDETAG) ||
1867 !is_lisp_pointer(fixups)) {
1868 /* Check for possible errors. */
1869 if (check_code_fixups)
1870 sniff_code_object(new_code, displacement);
1875 fixups_vector = (struct vector *)native_pointer(fixups);
1877 /* Could be pointing to a forwarding pointer. */
1878 /* FIXME is this always in from_space? if so, could replace this code with
1879 * forwarding_pointer_p/forwarding_pointer_value */
1880 if (is_lisp_pointer(fixups) &&
1881 (find_page_index((void*)fixups_vector) != -1) &&
1882 (fixups_vector->header == 0x01)) {
1883 /* If so, then follow it. */
1884 /*SHOW("following pointer to a forwarding pointer");*/
1886 (struct vector *)native_pointer((lispobj)fixups_vector->length);
1889 /*SHOW("got fixups");*/
1891 if (widetag_of(fixups_vector->header) == SIMPLE_ARRAY_WORD_WIDETAG) {
1892 /* Got the fixups for the code block. Now work through the vector,
1893 and apply a fixup at each address. */
1894 sword_t length = fixnum_value(fixups_vector->length);
1896 for (i = 0; i < length; i++) {
1897 long offset = fixups_vector->data[i];
1898 /* Now check the current value of offset. */
1899 os_vm_address_t old_value = *(os_vm_address_t *)(code_start_addr + offset);
1901 /* If it's within the old_code object then it must be an
1902 * absolute fixup (relative ones are not saved) */
1903 if ((old_value >= old_addr)
1904 && (old_value < (old_addr + nwords*N_WORD_BYTES)))
1905 /* So add the dispacement. */
1906 *(os_vm_address_t *)(code_start_addr + offset) =
1907 old_value + displacement;
1909 /* It is outside the old code object so it must be a
1910 * relative fixup (absolute fixups are not saved). So
1911 * subtract the displacement. */
1912 *(os_vm_address_t *)(code_start_addr + offset) =
1913 old_value - displacement;
1916 /* This used to just print a note to stderr, but a bogus fixup seems to
1917 * indicate real heap corruption, so a hard hailure is in order. */
1918 lose("fixup vector %p has a bad widetag: %d\n",
1919 fixups_vector, widetag_of(fixups_vector->header));
1922 /* Check for possible errors. */
1923 if (check_code_fixups) {
1924 sniff_code_object(new_code,displacement);
1931 trans_boxed_large(lispobj object)
1936 gc_assert(is_lisp_pointer(object));
1938 header = *((lispobj *) native_pointer(object));
1939 length = HeaderValue(header) + 1;
1940 length = CEILING(length, 2);
1942 return copy_large_object(object, length);
1945 /* Doesn't seem to be used, delete it after the grace period. */
1948 trans_unboxed_large(lispobj object)
1953 gc_assert(is_lisp_pointer(object));
1955 header = *((lispobj *) native_pointer(object));
1956 length = HeaderValue(header) + 1;
1957 length = CEILING(length, 2);
1959 return copy_large_unboxed_object(object, length);
1967 /* XX This is a hack adapted from cgc.c. These don't work too
1968 * efficiently with the gencgc as a list of the weak pointers is
1969 * maintained within the objects which causes writes to the pages. A
1970 * limited attempt is made to avoid unnecessary writes, but this needs
1972 #define WEAK_POINTER_NWORDS \
1973 CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
1976 scav_weak_pointer(lispobj *where, lispobj object)
1978 /* Since we overwrite the 'next' field, we have to make
1979 * sure not to do so for pointers already in the list.
1980 * Instead of searching the list of weak_pointers each
1981 * time, we ensure that next is always NULL when the weak
1982 * pointer isn't in the list, and not NULL otherwise.
1983 * Since we can't use NULL to denote end of list, we
1984 * use a pointer back to the same weak_pointer.
1986 struct weak_pointer * wp = (struct weak_pointer*)where;
1988 if (NULL == wp->next) {
1989 wp->next = weak_pointers;
1991 if (NULL == wp->next)
1995 /* Do not let GC scavenge the value slot of the weak pointer.
1996 * (That is why it is a weak pointer.) */
1998 return WEAK_POINTER_NWORDS;
2003 search_read_only_space(void *pointer)
2005 lispobj *start = (lispobj *) READ_ONLY_SPACE_START;
2006 lispobj *end = (lispobj *) SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
2007 if ((pointer < (void *)start) || (pointer >= (void *)end))
2009 return (gc_search_space(start,
2010 (((lispobj *)pointer)+2)-start,
2011 (lispobj *) pointer));
2015 search_static_space(void *pointer)
2017 lispobj *start = (lispobj *)STATIC_SPACE_START;
2018 lispobj *end = (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
2019 if ((pointer < (void *)start) || (pointer >= (void *)end))
2021 return (gc_search_space(start,
2022 (((lispobj *)pointer)+2)-start,
2023 (lispobj *) pointer));
2026 /* a faster version for searching the dynamic space. This will work even
2027 * if the object is in a current allocation region. */
2029 search_dynamic_space(void *pointer)
2031 page_index_t page_index = find_page_index(pointer);
2034 /* The address may be invalid, so do some checks. */
2035 if ((page_index == -1) || page_free_p(page_index))
2037 start = (lispobj *)page_scan_start(page_index);
2038 return (gc_search_space(start,
2039 (((lispobj *)pointer)+2)-start,
2040 (lispobj *)pointer));
2043 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2045 /* Is there any possibility that pointer is a valid Lisp object
2046 * reference, and/or something else (e.g. subroutine call return
2047 * address) which should prevent us from moving the referred-to thing?
2048 * This is called from preserve_pointers() */
2050 possibly_valid_dynamic_space_pointer(lispobj *pointer)
2052 lispobj *start_addr;
2054 /* Find the object start address. */
2055 if ((start_addr = search_dynamic_space(pointer)) == NULL) {
2059 return looks_like_valid_lisp_pointer_p(pointer, start_addr);
2062 #endif // defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2064 /* Adjust large bignum and vector objects. This will adjust the
2065 * allocated region if the size has shrunk, and move unboxed objects
2066 * into unboxed pages. The pages are not promoted here, and the
2067 * promoted region is not added to the new_regions; this is really
2068 * only designed to be called from preserve_pointer(). Shouldn't fail
2069 * if this is missed, just may delay the moving of objects to unboxed
2070 * pages, and the freeing of pages. */
2072 maybe_adjust_large_object(lispobj *where)
2074 page_index_t first_page;
2075 page_index_t next_page;
2078 uword_t remaining_bytes;
2079 uword_t bytes_freed;
2080 uword_t old_bytes_used;
2084 /* Check whether it's a vector or bignum object. */
2085 switch (widetag_of(where[0])) {
2086 case SIMPLE_VECTOR_WIDETAG:
2087 boxed = BOXED_PAGE_FLAG;
2089 case BIGNUM_WIDETAG:
2090 case SIMPLE_BASE_STRING_WIDETAG:
2091 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2092 case SIMPLE_CHARACTER_STRING_WIDETAG:
2094 case SIMPLE_BIT_VECTOR_WIDETAG:
2095 case SIMPLE_ARRAY_NIL_WIDETAG:
2096 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2097 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2098 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2099 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2100 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2101 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2103 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
2105 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2106 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2107 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2108 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2110 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2111 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2113 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2114 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2116 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2117 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2120 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
2122 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2123 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2125 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2126 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2128 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2129 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2130 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2131 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2133 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2134 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2136 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2137 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2139 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2140 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2142 boxed = UNBOXED_PAGE_FLAG;
2148 /* Find its current size. */
2149 nwords = (sizetab[widetag_of(where[0])])(where);
2151 first_page = find_page_index((void *)where);
2152 gc_assert(first_page >= 0);
2154 /* Note: Any page write-protection must be removed, else a later
2155 * scavenge_newspace may incorrectly not scavenge these pages.
2156 * This would not be necessary if they are added to the new areas,
2157 * but lets do it for them all (they'll probably be written
2160 gc_assert(page_starts_contiguous_block_p(first_page));
2162 next_page = first_page;
2163 remaining_bytes = nwords*N_WORD_BYTES;
2164 while (remaining_bytes > GENCGC_CARD_BYTES) {
2165 gc_assert(page_table[next_page].gen == from_space);
2166 gc_assert(page_allocated_no_region_p(next_page));
2167 gc_assert(page_table[next_page].large_object);
2168 gc_assert(page_table[next_page].scan_start_offset ==
2169 npage_bytes(next_page-first_page));
2170 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
2172 page_table[next_page].allocated = boxed;
2174 /* Shouldn't be write-protected at this stage. Essential that the
2176 gc_assert(!page_table[next_page].write_protected);
2177 remaining_bytes -= GENCGC_CARD_BYTES;
2181 /* Now only one page remains, but the object may have shrunk so
2182 * there may be more unused pages which will be freed. */
2184 /* Object may have shrunk but shouldn't have grown - check. */
2185 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2187 page_table[next_page].allocated = boxed;
2188 gc_assert(page_table[next_page].allocated ==
2189 page_table[first_page].allocated);
2191 /* Adjust the bytes_used. */
2192 old_bytes_used = page_table[next_page].bytes_used;
2193 page_table[next_page].bytes_used = remaining_bytes;
2195 bytes_freed = old_bytes_used - remaining_bytes;
2197 /* Free any remaining pages; needs care. */
2199 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
2200 (page_table[next_page].gen == from_space) &&
2201 page_allocated_no_region_p(next_page) &&
2202 page_table[next_page].large_object &&
2203 (page_table[next_page].scan_start_offset ==
2204 npage_bytes(next_page - first_page))) {
2205 /* It checks out OK, free the page. We don't need to both zeroing
2206 * pages as this should have been done before shrinking the
2207 * object. These pages shouldn't be write protected as they
2208 * should be zero filled. */
2209 gc_assert(page_table[next_page].write_protected == 0);
2211 old_bytes_used = page_table[next_page].bytes_used;
2212 page_table[next_page].allocated = FREE_PAGE_FLAG;
2213 page_table[next_page].bytes_used = 0;
2214 bytes_freed += old_bytes_used;
2218 if ((bytes_freed > 0) && gencgc_verbose) {
2220 "/maybe_adjust_large_object() freed %d\n",
2224 generations[from_space].bytes_allocated -= bytes_freed;
2225 bytes_allocated -= bytes_freed;
2230 /* Take a possible pointer to a Lisp object and mark its page in the
2231 * page_table so that it will not be relocated during a GC.
2233 * This involves locating the page it points to, then backing up to
2234 * the start of its region, then marking all pages dont_move from there
2235 * up to the first page that's not full or has a different generation
2237 * It is assumed that all the page static flags have been cleared at
2238 * the start of a GC.
2240 * It is also assumed that the current gc_alloc() region has been
2241 * flushed and the tables updated. */
2244 preserve_pointer(void *addr)
2246 page_index_t addr_page_index = find_page_index(addr);
2247 page_index_t first_page;
2249 unsigned int region_allocation;
2251 /* quick check 1: Address is quite likely to have been invalid. */
2252 if ((addr_page_index == -1)
2253 || page_free_p(addr_page_index)
2254 || (page_table[addr_page_index].bytes_used == 0)
2255 || (page_table[addr_page_index].gen != from_space)
2256 /* Skip if already marked dont_move. */
2257 || (page_table[addr_page_index].dont_move != 0))
2259 gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2260 /* (Now that we know that addr_page_index is in range, it's
2261 * safe to index into page_table[] with it.) */
2262 region_allocation = page_table[addr_page_index].allocated;
2264 /* quick check 2: Check the offset within the page.
2267 if (((uword_t)addr & (GENCGC_CARD_BYTES - 1)) >
2268 page_table[addr_page_index].bytes_used)
2271 /* Filter out anything which can't be a pointer to a Lisp object
2272 * (or, as a special case which also requires dont_move, a return
2273 * address referring to something in a CodeObject). This is
2274 * expensive but important, since it vastly reduces the
2275 * probability that random garbage will be bogusly interpreted as
2276 * a pointer which prevents a page from moving.
2278 * This only needs to happen on x86oids, where this is used for
2279 * conservative roots. Non-x86oid systems only ever call this
2280 * function on known-valid lisp objects. */
2281 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2282 if (!(code_page_p(addr_page_index)
2283 || (is_lisp_pointer((lispobj)addr) &&
2284 possibly_valid_dynamic_space_pointer(addr))))
2288 /* Find the beginning of the region. Note that there may be
2289 * objects in the region preceding the one that we were passed a
2290 * pointer to: if this is the case, we will write-protect all the
2291 * previous objects' pages too. */
2294 /* I think this'd work just as well, but without the assertions.
2295 * -dan 2004.01.01 */
2296 first_page = find_page_index(page_scan_start(addr_page_index))
2298 first_page = addr_page_index;
2299 while (!page_starts_contiguous_block_p(first_page)) {
2301 /* Do some checks. */
2302 gc_assert(page_table[first_page].bytes_used == GENCGC_CARD_BYTES);
2303 gc_assert(page_table[first_page].gen == from_space);
2304 gc_assert(page_table[first_page].allocated == region_allocation);
2308 /* Adjust any large objects before promotion as they won't be
2309 * copied after promotion. */
2310 if (page_table[first_page].large_object) {
2311 maybe_adjust_large_object(page_address(first_page));
2312 /* If a large object has shrunk then addr may now point to a
2313 * free area in which case it's ignored here. Note it gets
2314 * through the valid pointer test above because the tail looks
2316 if (page_free_p(addr_page_index)
2317 || (page_table[addr_page_index].bytes_used == 0)
2318 /* Check the offset within the page. */
2319 || (((uword_t)addr & (GENCGC_CARD_BYTES - 1))
2320 > page_table[addr_page_index].bytes_used)) {
2322 "weird? ignore ptr 0x%x to freed area of large object\n",
2326 /* It may have moved to unboxed pages. */
2327 region_allocation = page_table[first_page].allocated;
2330 /* Now work forward until the end of this contiguous area is found,
2331 * marking all pages as dont_move. */
2332 for (i = first_page; ;i++) {
2333 gc_assert(page_table[i].allocated == region_allocation);
2335 /* Mark the page static. */
2336 page_table[i].dont_move = 1;
2338 /* It is essential that the pages are not write protected as
2339 * they may have pointers into the old-space which need
2340 * scavenging. They shouldn't be write protected at this
2342 gc_assert(!page_table[i].write_protected);
2344 /* Check whether this is the last page in this contiguous block.. */
2345 if (page_ends_contiguous_block_p(i, from_space))
2349 /* Check that the page is now static. */
2350 gc_assert(page_table[addr_page_index].dont_move != 0);
2353 /* If the given page is not write-protected, then scan it for pointers
2354 * to younger generations or the top temp. generation, if no
2355 * suspicious pointers are found then the page is write-protected.
2357 * Care is taken to check for pointers to the current gc_alloc()
2358 * region if it is a younger generation or the temp. generation. This
2359 * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2360 * the gc_alloc_generation does not need to be checked as this is only
2361 * called from scavenge_generation() when the gc_alloc generation is
2362 * younger, so it just checks if there is a pointer to the current
2365 * We return 1 if the page was write-protected, else 0. */
2367 update_page_write_prot(page_index_t page)
2369 generation_index_t gen = page_table[page].gen;
2372 void **page_addr = (void **)page_address(page);
2373 sword_t num_words = page_table[page].bytes_used / N_WORD_BYTES;
2375 /* Shouldn't be a free page. */
2376 gc_assert(page_allocated_p(page));
2377 gc_assert(page_table[page].bytes_used != 0);
2379 /* Skip if it's already write-protected, pinned, or unboxed */
2380 if (page_table[page].write_protected
2381 /* FIXME: What's the reason for not write-protecting pinned pages? */
2382 || page_table[page].dont_move
2383 || page_unboxed_p(page))
2386 /* Scan the page for pointers to younger generations or the
2387 * top temp. generation. */
2389 for (j = 0; j < num_words; j++) {
2390 void *ptr = *(page_addr+j);
2391 page_index_t index = find_page_index(ptr);
2393 /* Check that it's in the dynamic space */
2395 if (/* Does it point to a younger or the temp. generation? */
2396 (page_allocated_p(index)
2397 && (page_table[index].bytes_used != 0)
2398 && ((page_table[index].gen < gen)
2399 || (page_table[index].gen == SCRATCH_GENERATION)))
2401 /* Or does it point within a current gc_alloc() region? */
2402 || ((boxed_region.start_addr <= ptr)
2403 && (ptr <= boxed_region.free_pointer))
2404 || ((unboxed_region.start_addr <= ptr)
2405 && (ptr <= unboxed_region.free_pointer))) {
2412 /* Write-protect the page. */
2413 /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2415 os_protect((void *)page_addr,
2417 OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2419 /* Note the page as protected in the page tables. */
2420 page_table[page].write_protected = 1;
2426 /* Scavenge all generations from FROM to TO, inclusive, except for
2427 * new_space which needs special handling, as new objects may be
2428 * added which are not checked here - use scavenge_newspace generation.
2430 * Write-protected pages should not have any pointers to the
2431 * from_space so do need scavenging; thus write-protected pages are
2432 * not always scavenged. There is some code to check that these pages
2433 * are not written; but to check fully the write-protected pages need
2434 * to be scavenged by disabling the code to skip them.
2436 * Under the current scheme when a generation is GCed the younger
2437 * generations will be empty. So, when a generation is being GCed it
2438 * is only necessary to scavenge the older generations for pointers
2439 * not the younger. So a page that does not have pointers to younger
2440 * generations does not need to be scavenged.
2442 * The write-protection can be used to note pages that don't have
2443 * pointers to younger pages. But pages can be written without having
2444 * pointers to younger generations. After the pages are scavenged here
2445 * they can be scanned for pointers to younger generations and if
2446 * there are none the page can be write-protected.
2448 * One complication is when the newspace is the top temp. generation.
2450 * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2451 * that none were written, which they shouldn't be as they should have
2452 * no pointers to younger generations. This breaks down for weak
2453 * pointers as the objects contain a link to the next and are written
2454 * if a weak pointer is scavenged. Still it's a useful check. */
2456 scavenge_generations(generation_index_t from, generation_index_t to)
2459 page_index_t num_wp = 0;
2463 /* Clear the write_protected_cleared flags on all pages. */
2464 for (i = 0; i < page_table_pages; i++)
2465 page_table[i].write_protected_cleared = 0;
2468 for (i = 0; i < last_free_page; i++) {
2469 generation_index_t generation = page_table[i].gen;
2471 && (page_table[i].bytes_used != 0)
2472 && (generation != new_space)
2473 && (generation >= from)
2474 && (generation <= to)) {
2475 page_index_t last_page,j;
2476 int write_protected=1;
2478 /* This should be the start of a region */
2479 gc_assert(page_starts_contiguous_block_p(i));
2481 /* Now work forward until the end of the region */
2482 for (last_page = i; ; last_page++) {
2484 write_protected && page_table[last_page].write_protected;
2485 if (page_ends_contiguous_block_p(last_page, generation))
2488 if (!write_protected) {
2489 scavenge(page_address(i),
2490 ((uword_t)(page_table[last_page].bytes_used
2491 + npage_bytes(last_page-i)))
2494 /* Now scan the pages and write protect those that
2495 * don't have pointers to younger generations. */
2496 if (enable_page_protection) {
2497 for (j = i; j <= last_page; j++) {
2498 num_wp += update_page_write_prot(j);
2501 if ((gencgc_verbose > 1) && (num_wp != 0)) {
2503 "/write protected %d pages within generation %d\n",
2504 num_wp, generation));
2512 /* Check that none of the write_protected pages in this generation
2513 * have been written to. */
2514 for (i = 0; i < page_table_pages; i++) {
2515 if (page_allocated_p(i)
2516 && (page_table[i].bytes_used != 0)
2517 && (page_table[i].gen == generation)
2518 && (page_table[i].write_protected_cleared != 0)) {
2519 FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2521 "/page bytes_used=%d scan_start_offset=%lu dont_move=%d\n",
2522 page_table[i].bytes_used,
2523 page_table[i].scan_start_offset,
2524 page_table[i].dont_move));
2525 lose("write to protected page %d in scavenge_generation()\n", i);
2532 /* Scavenge a newspace generation. As it is scavenged new objects may
2533 * be allocated to it; these will also need to be scavenged. This
2534 * repeats until there are no more objects unscavenged in the
2535 * newspace generation.
2537 * To help improve the efficiency, areas written are recorded by
2538 * gc_alloc() and only these scavenged. Sometimes a little more will be
2539 * scavenged, but this causes no harm. An easy check is done that the
2540 * scavenged bytes equals the number allocated in the previous
2543 * Write-protected pages are not scanned except if they are marked
2544 * dont_move in which case they may have been promoted and still have
2545 * pointers to the from space.
2547 * Write-protected pages could potentially be written by alloc however
2548 * to avoid having to handle re-scavenging of write-protected pages
2549 * gc_alloc() does not write to write-protected pages.
2551 * New areas of objects allocated are recorded alternatively in the two
2552 * new_areas arrays below. */
2553 static struct new_area new_areas_1[NUM_NEW_AREAS];
2554 static struct new_area new_areas_2[NUM_NEW_AREAS];
2556 /* Do one full scan of the new space generation. This is not enough to
2557 * complete the job as new objects may be added to the generation in
2558 * the process which are not scavenged. */
2560 scavenge_newspace_generation_one_scan(generation_index_t generation)
2565 "/starting one full scan of newspace generation %d\n",
2567 for (i = 0; i < last_free_page; i++) {
2568 /* Note that this skips over open regions when it encounters them. */
2570 && (page_table[i].bytes_used != 0)
2571 && (page_table[i].gen == generation)
2572 && ((page_table[i].write_protected == 0)
2573 /* (This may be redundant as write_protected is now
2574 * cleared before promotion.) */
2575 || (page_table[i].dont_move == 1))) {
2576 page_index_t last_page;
2579 /* The scavenge will start at the scan_start_offset of
2582 * We need to find the full extent of this contiguous
2583 * block in case objects span pages.
2585 * Now work forward until the end of this contiguous area
2586 * is found. A small area is preferred as there is a
2587 * better chance of its pages being write-protected. */
2588 for (last_page = i; ;last_page++) {
2589 /* If all pages are write-protected and movable,
2590 * then no need to scavenge */
2591 all_wp=all_wp && page_table[last_page].write_protected &&
2592 !page_table[last_page].dont_move;
2594 /* Check whether this is the last page in this
2595 * contiguous block */
2596 if (page_ends_contiguous_block_p(last_page, generation))
2600 /* Do a limited check for write-protected pages. */
2602 sword_t nwords = (((uword_t)
2603 (page_table[last_page].bytes_used
2604 + npage_bytes(last_page-i)
2605 + page_table[i].scan_start_offset))
2607 new_areas_ignore_page = last_page;
2609 scavenge(page_scan_start(i), nwords);
2616 "/done with one full scan of newspace generation %d\n",
2620 /* Do a complete scavenge of the newspace generation. */
2622 scavenge_newspace_generation(generation_index_t generation)
2626 /* the new_areas array currently being written to by gc_alloc() */
2627 struct new_area (*current_new_areas)[] = &new_areas_1;
2628 size_t current_new_areas_index;
2630 /* the new_areas created by the previous scavenge cycle */
2631 struct new_area (*previous_new_areas)[] = NULL;
2632 size_t previous_new_areas_index;
2634 /* Flush the current regions updating the tables. */
2635 gc_alloc_update_all_page_tables();
2637 /* Turn on the recording of new areas by gc_alloc(). */
2638 new_areas = current_new_areas;
2639 new_areas_index = 0;
2641 /* Don't need to record new areas that get scavenged anyway during
2642 * scavenge_newspace_generation_one_scan. */
2643 record_new_objects = 1;
2645 /* Start with a full scavenge. */
2646 scavenge_newspace_generation_one_scan(generation);
2648 /* Record all new areas now. */
2649 record_new_objects = 2;
2651 /* Give a chance to weak hash tables to make other objects live.
2652 * FIXME: The algorithm implemented here for weak hash table gcing
2653 * is O(W^2+N) as Bruno Haible warns in
2654 * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
2655 * see "Implementation 2". */
2656 scav_weak_hash_tables();
2658 /* Flush the current regions updating the tables. */
2659 gc_alloc_update_all_page_tables();
2661 /* Grab new_areas_index. */
2662 current_new_areas_index = new_areas_index;
2665 "The first scan is finished; current_new_areas_index=%d.\n",
2666 current_new_areas_index));*/
2668 while (current_new_areas_index > 0) {
2669 /* Move the current to the previous new areas */
2670 previous_new_areas = current_new_areas;
2671 previous_new_areas_index = current_new_areas_index;
2673 /* Scavenge all the areas in previous new areas. Any new areas
2674 * allocated are saved in current_new_areas. */
2676 /* Allocate an array for current_new_areas; alternating between
2677 * new_areas_1 and 2 */
2678 if (previous_new_areas == &new_areas_1)
2679 current_new_areas = &new_areas_2;
2681 current_new_areas = &new_areas_1;
2683 /* Set up for gc_alloc(). */
2684 new_areas = current_new_areas;
2685 new_areas_index = 0;
2687 /* Check whether previous_new_areas had overflowed. */
2688 if (previous_new_areas_index >= NUM_NEW_AREAS) {
2690 /* New areas of objects allocated have been lost so need to do a
2691 * full scan to be sure! If this becomes a problem try
2692 * increasing NUM_NEW_AREAS. */
2693 if (gencgc_verbose) {
2694 SHOW("new_areas overflow, doing full scavenge");
2697 /* Don't need to record new areas that get scavenged
2698 * anyway during scavenge_newspace_generation_one_scan. */
2699 record_new_objects = 1;
2701 scavenge_newspace_generation_one_scan(generation);
2703 /* Record all new areas now. */
2704 record_new_objects = 2;
2706 scav_weak_hash_tables();
2708 /* Flush the current regions updating the tables. */
2709 gc_alloc_update_all_page_tables();
2713 /* Work through previous_new_areas. */
2714 for (i = 0; i < previous_new_areas_index; i++) {
2715 page_index_t page = (*previous_new_areas)[i].page;
2716 size_t offset = (*previous_new_areas)[i].offset;
2717 size_t size = (*previous_new_areas)[i].size / N_WORD_BYTES;
2718 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
2719 scavenge(page_address(page)+offset, size);
2722 scav_weak_hash_tables();
2724 /* Flush the current regions updating the tables. */
2725 gc_alloc_update_all_page_tables();
2728 current_new_areas_index = new_areas_index;
2731 "The re-scan has finished; current_new_areas_index=%d.\n",
2732 current_new_areas_index));*/
2735 /* Turn off recording of areas allocated by gc_alloc(). */
2736 record_new_objects = 0;
2741 /* Check that none of the write_protected pages in this generation
2742 * have been written to. */
2743 for (i = 0; i < page_table_pages; i++) {
2744 if (page_allocated_p(i)
2745 && (page_table[i].bytes_used != 0)
2746 && (page_table[i].gen == generation)
2747 && (page_table[i].write_protected_cleared != 0)
2748 && (page_table[i].dont_move == 0)) {
2749 lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
2750 i, generation, page_table[i].dont_move);
2757 /* Un-write-protect all the pages in from_space. This is done at the
2758 * start of a GC else there may be many page faults while scavenging
2759 * the newspace (I've seen drive the system time to 99%). These pages
2760 * would need to be unprotected anyway before unmapping in
2761 * free_oldspace; not sure what effect this has on paging.. */
2763 unprotect_oldspace(void)
2766 void *region_addr = 0;
2767 void *page_addr = 0;
2768 uword_t region_bytes = 0;
2770 for (i = 0; i < last_free_page; i++) {
2771 if (page_allocated_p(i)
2772 && (page_table[i].bytes_used != 0)
2773 && (page_table[i].gen == from_space)) {
2775 /* Remove any write-protection. We should be able to rely
2776 * on the write-protect flag to avoid redundant calls. */
2777 if (page_table[i].write_protected) {
2778 page_table[i].write_protected = 0;
2779 page_addr = page_address(i);
2782 region_addr = page_addr;
2783 region_bytes = GENCGC_CARD_BYTES;
2784 } else if (region_addr + region_bytes == page_addr) {
2785 /* Region continue. */
2786 region_bytes += GENCGC_CARD_BYTES;
2788 /* Unprotect previous region. */
2789 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2790 /* First page in new region. */
2791 region_addr = page_addr;
2792 region_bytes = GENCGC_CARD_BYTES;
2798 /* Unprotect last region. */
2799 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2803 /* Work through all the pages and free any in from_space. This
2804 * assumes that all objects have been copied or promoted to an older
2805 * generation. Bytes_allocated and the generation bytes_allocated
2806 * counter are updated. The number of bytes freed is returned. */
2810 uword_t bytes_freed = 0;
2811 page_index_t first_page, last_page;
2816 /* Find a first page for the next region of pages. */
2817 while ((first_page < last_free_page)
2818 && (page_free_p(first_page)
2819 || (page_table[first_page].bytes_used == 0)
2820 || (page_table[first_page].gen != from_space)))
2823 if (first_page >= last_free_page)
2826 /* Find the last page of this region. */
2827 last_page = first_page;
2830 /* Free the page. */
2831 bytes_freed += page_table[last_page].bytes_used;
2832 generations[page_table[last_page].gen].bytes_allocated -=
2833 page_table[last_page].bytes_used;
2834 page_table[last_page].allocated = FREE_PAGE_FLAG;
2835 page_table[last_page].bytes_used = 0;
2836 /* Should already be unprotected by unprotect_oldspace(). */
2837 gc_assert(!page_table[last_page].write_protected);
2840 while ((last_page < last_free_page)
2841 && page_allocated_p(last_page)
2842 && (page_table[last_page].bytes_used != 0)
2843 && (page_table[last_page].gen == from_space));
2845 #ifdef READ_PROTECT_FREE_PAGES
2846 os_protect(page_address(first_page),
2847 npage_bytes(last_page-first_page),
2850 first_page = last_page;
2851 } while (first_page < last_free_page);
2853 bytes_allocated -= bytes_freed;
2858 /* Print some information about a pointer at the given address. */
2860 print_ptr(lispobj *addr)
2862 /* If addr is in the dynamic space then out the page information. */
2863 page_index_t pi1 = find_page_index((void*)addr);
2866 fprintf(stderr," %p: page %d alloc %d gen %d bytes_used %d offset %lu dont_move %d\n",
2869 page_table[pi1].allocated,
2870 page_table[pi1].gen,
2871 page_table[pi1].bytes_used,
2872 page_table[pi1].scan_start_offset,
2873 page_table[pi1].dont_move);
2874 fprintf(stderr," %x %x %x %x (%x) %x %x %x %x\n",
2888 is_in_stack_space(lispobj ptr)
2890 /* For space verification: Pointers can be valid if they point
2891 * to a thread stack space. This would be faster if the thread
2892 * structures had page-table entries as if they were part of
2893 * the heap space. */
2895 for_each_thread(th) {
2896 if ((th->control_stack_start <= (lispobj *)ptr) &&
2897 (th->control_stack_end >= (lispobj *)ptr)) {
2905 verify_space(lispobj *start, size_t words)
2907 int is_in_dynamic_space = (find_page_index((void*)start) != -1);
2908 int is_in_readonly_space =
2909 (READ_ONLY_SPACE_START <= (uword_t)start &&
2910 (uword_t)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
2914 lispobj thing = *(lispobj*)start;
2916 if (is_lisp_pointer(thing)) {
2917 page_index_t page_index = find_page_index((void*)thing);
2918 sword_t to_readonly_space =
2919 (READ_ONLY_SPACE_START <= thing &&
2920 thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
2921 sword_t to_static_space =
2922 (STATIC_SPACE_START <= thing &&
2923 thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
2925 /* Does it point to the dynamic space? */
2926 if (page_index != -1) {
2927 /* If it's within the dynamic space it should point to a used
2928 * page. XX Could check the offset too. */
2929 if (page_allocated_p(page_index)
2930 && (page_table[page_index].bytes_used == 0))
2931 lose ("Ptr %p @ %p sees free page.\n", thing, start);
2932 /* Check that it doesn't point to a forwarding pointer! */
2933 if (*((lispobj *)native_pointer(thing)) == 0x01) {
2934 lose("Ptr %p @ %p sees forwarding ptr.\n", thing, start);
2936 /* Check that its not in the RO space as it would then be a
2937 * pointer from the RO to the dynamic space. */
2938 if (is_in_readonly_space) {
2939 lose("ptr to dynamic space %p from RO space %x\n",
2942 /* Does it point to a plausible object? This check slows
2943 * it down a lot (so it's commented out).
2945 * "a lot" is serious: it ate 50 minutes cpu time on
2946 * my duron 950 before I came back from lunch and
2949 * FIXME: Add a variable to enable this
2952 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
2953 lose("ptr %p to invalid object %p\n", thing, start);
2957 extern void funcallable_instance_tramp;
2958 /* Verify that it points to another valid space. */
2959 if (!to_readonly_space && !to_static_space
2960 && (thing != (lispobj)&funcallable_instance_tramp)
2961 && !is_in_stack_space(thing)) {
2962 lose("Ptr %p @ %p sees junk.\n", thing, start);
2966 if (!(fixnump(thing))) {
2968 switch(widetag_of(*start)) {
2971 case SIMPLE_VECTOR_WIDETAG:
2973 case COMPLEX_WIDETAG:
2974 case SIMPLE_ARRAY_WIDETAG:
2975 case COMPLEX_BASE_STRING_WIDETAG:
2976 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
2977 case COMPLEX_CHARACTER_STRING_WIDETAG:
2979 case COMPLEX_VECTOR_NIL_WIDETAG:
2980 case COMPLEX_BIT_VECTOR_WIDETAG:
2981 case COMPLEX_VECTOR_WIDETAG:
2982 case COMPLEX_ARRAY_WIDETAG:
2983 case CLOSURE_HEADER_WIDETAG:
2984 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2985 case VALUE_CELL_HEADER_WIDETAG:
2986 case SYMBOL_HEADER_WIDETAG:
2987 case CHARACTER_WIDETAG:
2988 #if N_WORD_BITS == 64
2989 case SINGLE_FLOAT_WIDETAG:
2991 case UNBOUND_MARKER_WIDETAG:
2996 case INSTANCE_HEADER_WIDETAG:
2999 sword_t ntotal = HeaderValue(thing);
3000 lispobj layout = ((struct instance *)start)->slots[0];
3005 nuntagged = ((struct layout *)
3006 native_pointer(layout))->n_untagged_slots;
3007 verify_space(start + 1,
3008 ntotal - fixnum_value(nuntagged));
3012 case CODE_HEADER_WIDETAG:
3014 lispobj object = *start;
3016 sword_t nheader_words, ncode_words, nwords;
3018 struct simple_fun *fheaderp;
3020 code = (struct code *) start;
3022 /* Check that it's not in the dynamic space.
3023 * FIXME: Isn't is supposed to be OK for code
3024 * objects to be in the dynamic space these days? */
3025 if (is_in_dynamic_space
3026 /* It's ok if it's byte compiled code. The trace
3027 * table offset will be a fixnum if it's x86
3028 * compiled code - check.
3030 * FIXME: #^#@@! lack of abstraction here..
3031 * This line can probably go away now that
3032 * there's no byte compiler, but I've got
3033 * too much to worry about right now to try
3034 * to make sure. -- WHN 2001-10-06 */
3035 && fixnump(code->trace_table_offset)
3036 /* Only when enabled */
3037 && verify_dynamic_code_check) {
3039 "/code object at %p in the dynamic space\n",
3043 ncode_words = fixnum_value(code->code_size);
3044 nheader_words = HeaderValue(object);
3045 nwords = ncode_words + nheader_words;
3046 nwords = CEILING(nwords, 2);
3047 /* Scavenge the boxed section of the code data block */
3048 verify_space(start + 1, nheader_words - 1);
3050 /* Scavenge the boxed section of each function
3051 * object in the code data block. */
3052 fheaderl = code->entry_points;
3053 while (fheaderl != NIL) {
3055 (struct simple_fun *) native_pointer(fheaderl);
3056 gc_assert(widetag_of(fheaderp->header) ==
3057 SIMPLE_FUN_HEADER_WIDETAG);
3058 verify_space(&fheaderp->name, 1);
3059 verify_space(&fheaderp->arglist, 1);
3060 verify_space(&fheaderp->type, 1);
3061 fheaderl = fheaderp->next;
3067 /* unboxed objects */
3068 case BIGNUM_WIDETAG:
3069 #if N_WORD_BITS != 64
3070 case SINGLE_FLOAT_WIDETAG:
3072 case DOUBLE_FLOAT_WIDETAG:
3073 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3074 case LONG_FLOAT_WIDETAG:
3076 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3077 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3079 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3080 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3082 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3083 case COMPLEX_LONG_FLOAT_WIDETAG:
3085 case SIMPLE_BASE_STRING_WIDETAG:
3086 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3087 case SIMPLE_CHARACTER_STRING_WIDETAG:
3089 case SIMPLE_BIT_VECTOR_WIDETAG:
3090 case SIMPLE_ARRAY_NIL_WIDETAG:
3091 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3092 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3093 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3094 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3095 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3096 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3098 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
3100 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3101 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3102 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3103 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3105 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3106 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3108 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3109 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3111 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3112 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3115 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
3117 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3118 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3120 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3121 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3123 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3124 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3125 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3126 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3128 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3129 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3131 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3132 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3134 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3135 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3138 case WEAK_POINTER_WIDETAG:
3139 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3140 case NO_TLS_VALUE_MARKER_WIDETAG:
3142 count = (sizetab[widetag_of(*start)])(start);
3146 lose("Unhandled widetag %p at %p\n",
3147 widetag_of(*start), start);
3159 /* FIXME: It would be nice to make names consistent so that
3160 * foo_size meant size *in* *bytes* instead of size in some
3161 * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3162 * Some counts of lispobjs are called foo_count; it might be good
3163 * to grep for all foo_size and rename the appropriate ones to
3165 sword_t read_only_space_size =
3166 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3167 - (lispobj*)READ_ONLY_SPACE_START;
3168 sword_t static_space_size =
3169 (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3170 - (lispobj*)STATIC_SPACE_START;
3172 for_each_thread(th) {
3173 sword_t binding_stack_size =
3174 (lispobj*)get_binding_stack_pointer(th)
3175 - (lispobj*)th->binding_stack_start;
3176 verify_space(th->binding_stack_start, binding_stack_size);
3178 verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3179 verify_space((lispobj*)STATIC_SPACE_START , static_space_size);
3183 verify_generation(generation_index_t generation)
3187 for (i = 0; i < last_free_page; i++) {
3188 if (page_allocated_p(i)
3189 && (page_table[i].bytes_used != 0)
3190 && (page_table[i].gen == generation)) {
3191 page_index_t last_page;
3192 int region_allocation = page_table[i].allocated;
3194 /* This should be the start of a contiguous block */
3195 gc_assert(page_starts_contiguous_block_p(i));
3197 /* Need to find the full extent of this contiguous block in case
3198 objects span pages. */
3200 /* Now work forward until the end of this contiguous area is
3202 for (last_page = i; ;last_page++)
3203 /* Check whether this is the last page in this contiguous
3205 if (page_ends_contiguous_block_p(last_page, generation))
3208 verify_space(page_address(i),
3210 (page_table[last_page].bytes_used
3211 + npage_bytes(last_page-i)))
3218 /* Check that all the free space is zero filled. */
3220 verify_zero_fill(void)
3224 for (page = 0; page < last_free_page; page++) {
3225 if (page_free_p(page)) {
3226 /* The whole page should be zero filled. */
3227 sword_t *start_addr = (sword_t *)page_address(page);
3228 sword_t size = 1024;
3230 for (i = 0; i < size; i++) {
3231 if (start_addr[i] != 0) {
3232 lose("free page not zero at %x\n", start_addr + i);
3236 sword_t free_bytes = GENCGC_CARD_BYTES - page_table[page].bytes_used;
3237 if (free_bytes > 0) {
3238 sword_t *start_addr = (sword_t *)((uword_t)page_address(page)
3239 + page_table[page].bytes_used);
3240 sword_t size = free_bytes / N_WORD_BYTES;
3242 for (i = 0; i < size; i++) {
3243 if (start_addr[i] != 0) {
3244 lose("free region not zero at %x\n", start_addr + i);
3252 /* External entry point for verify_zero_fill */
3254 gencgc_verify_zero_fill(void)
3256 /* Flush the alloc regions updating the tables. */
3257 gc_alloc_update_all_page_tables();
3258 SHOW("verifying zero fill");
3263 verify_dynamic_space(void)
3265 generation_index_t i;
3267 for (i = 0; i <= HIGHEST_NORMAL_GENERATION; i++)
3268 verify_generation(i);
3270 if (gencgc_enable_verify_zero_fill)
3274 /* Write-protect all the dynamic boxed pages in the given generation. */
3276 write_protect_generation_pages(generation_index_t generation)
3280 gc_assert(generation < SCRATCH_GENERATION);
3282 for (start = 0; start < last_free_page; start++) {
3283 if (protect_page_p(start, generation)) {
3287 /* Note the page as protected in the page tables. */
3288 page_table[start].write_protected = 1;
3290 for (last = start + 1; last < last_free_page; last++) {
3291 if (!protect_page_p(last, generation))
3293 page_table[last].write_protected = 1;
3296 page_start = (void *)page_address(start);
3298 os_protect(page_start,
3299 npage_bytes(last - start),
3300 OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3306 if (gencgc_verbose > 1) {
3308 "/write protected %d of %d pages in generation %d\n",
3309 count_write_protect_generation_pages(generation),
3310 count_generation_pages(generation),
3315 #if defined(LISP_FEATURE_SB_THREAD) && (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
3317 preserve_context_registers (os_context_t *c)
3320 /* On Darwin the signal context isn't a contiguous block of memory,
3321 * so just preserve_pointering its contents won't be sufficient.
3323 #if defined(LISP_FEATURE_DARWIN)||defined(LISP_FEATURE_WIN32)
3324 #if defined LISP_FEATURE_X86
3325 preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3326 preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3327 preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3328 preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3329 preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3330 preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3331 preserve_pointer((void*)*os_context_pc_addr(c));
3332 #elif defined LISP_FEATURE_X86_64
3333 preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3334 preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3335 preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3336 preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3337 preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3338 preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3339 preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3340 preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3341 preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3342 preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3343 preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3344 preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3345 preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3346 preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3347 preserve_pointer((void*)*os_context_pc_addr(c));
3349 #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3352 #if !defined(LISP_FEATURE_WIN32)
3353 for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3354 preserve_pointer(*ptr);
3361 move_pinned_pages_to_newspace()
3365 /* scavenge() will evacuate all oldspace pages, but no newspace
3366 * pages. Pinned pages are precisely those pages which must not
3367 * be evacuated, so move them to newspace directly. */
3369 for (i = 0; i < last_free_page; i++) {
3370 if (page_table[i].dont_move &&
3371 /* dont_move is cleared lazily, so validate the space as well. */
3372 page_table[i].gen == from_space) {
3373 page_table[i].gen = new_space;
3374 /* And since we're moving the pages wholesale, also adjust
3375 * the generation allocation counters. */
3376 generations[new_space].bytes_allocated += page_table[i].bytes_used;
3377 generations[from_space].bytes_allocated -= page_table[i].bytes_used;
3382 /* Garbage collect a generation. If raise is 0 then the remains of the
3383 * generation are not raised to the next generation. */
3385 garbage_collect_generation(generation_index_t generation, int raise)
3387 uword_t bytes_freed;
3389 uword_t static_space_size;
3392 gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3394 /* The oldest generation can't be raised. */
3395 gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
3397 /* Check if weak hash tables were processed in the previous GC. */
3398 gc_assert(weak_hash_tables == NULL);
3400 /* Initialize the weak pointer list. */
3401 weak_pointers = NULL;
3403 /* When a generation is not being raised it is transported to a
3404 * temporary generation (NUM_GENERATIONS), and lowered when
3405 * done. Set up this new generation. There should be no pages
3406 * allocated to it yet. */
3408 gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
3411 /* Set the global src and dest. generations */
3412 from_space = generation;
3414 new_space = generation+1;
3416 new_space = SCRATCH_GENERATION;
3418 /* Change to a new space for allocation, resetting the alloc_start_page */
3419 gc_alloc_generation = new_space;
3420 generations[new_space].alloc_start_page = 0;
3421 generations[new_space].alloc_unboxed_start_page = 0;
3422 generations[new_space].alloc_large_start_page = 0;
3423 generations[new_space].alloc_large_unboxed_start_page = 0;
3425 /* Before any pointers are preserved, the dont_move flags on the
3426 * pages need to be cleared. */
3427 for (i = 0; i < last_free_page; i++)
3428 if(page_table[i].gen==from_space)
3429 page_table[i].dont_move = 0;
3431 /* Un-write-protect the old-space pages. This is essential for the
3432 * promoted pages as they may contain pointers into the old-space
3433 * which need to be scavenged. It also helps avoid unnecessary page
3434 * faults as forwarding pointers are written into them. They need to
3435 * be un-protected anyway before unmapping later. */
3436 unprotect_oldspace();
3438 /* Scavenge the stacks' conservative roots. */
3440 /* there are potentially two stacks for each thread: the main
3441 * stack, which may contain Lisp pointers, and the alternate stack.
3442 * We don't ever run Lisp code on the altstack, but it may
3443 * host a sigcontext with lisp objects in it */
3445 /* what we need to do: (1) find the stack pointer for the main
3446 * stack; scavenge it (2) find the interrupt context on the
3447 * alternate stack that might contain lisp values, and scavenge
3450 /* we assume that none of the preceding applies to the thread that
3451 * initiates GC. If you ever call GC from inside an altstack
3452 * handler, you will lose. */
3454 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3455 /* And if we're saving a core, there's no point in being conservative. */
3456 if (conservative_stack) {
3457 for_each_thread(th) {
3459 void **esp=(void **)-1;
3460 if (th->state == STATE_DEAD)
3462 # if defined(LISP_FEATURE_SB_SAFEPOINT)
3463 /* Conservative collect_garbage is always invoked with a
3464 * foreign C call or an interrupt handler on top of every
3465 * existing thread, so the stored SP in each thread
3466 * structure is valid, no matter which thread we are looking
3467 * at. For threads that were running Lisp code, the pitstop
3468 * and edge functions maintain this value within the
3469 * interrupt or exception handler. */
3470 esp = os_get_csp(th);
3471 assert_on_stack(th, esp);
3473 /* In addition to pointers on the stack, also preserve the
3474 * return PC, the only value from the context that we need
3475 * in addition to the SP. The return PC gets saved by the
3476 * foreign call wrapper, and removed from the control stack
3477 * into a register. */
3478 preserve_pointer(th->pc_around_foreign_call);
3480 /* And on platforms with interrupts: scavenge ctx registers. */
3482 /* Disabled on Windows, because it does not have an explicit
3483 * stack of `interrupt_contexts'. The reported CSP has been
3484 * chosen so that the current context on the stack is
3485 * covered by the stack scan. See also set_csp_from_context(). */
3486 # ifndef LISP_FEATURE_WIN32
3487 if (th != arch_os_get_current_thread()) {
3488 long k = fixnum_value(
3489 SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3491 preserve_context_registers(th->interrupt_contexts[--k]);
3494 # elif defined(LISP_FEATURE_SB_THREAD)
3496 if(th==arch_os_get_current_thread()) {
3497 /* Somebody is going to burn in hell for this, but casting
3498 * it in two steps shuts gcc up about strict aliasing. */
3499 esp = (void **)((void *)&raise);
3502 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3503 for(i=free-1;i>=0;i--) {
3504 os_context_t *c=th->interrupt_contexts[i];
3505 esp1 = (void **) *os_context_register_addr(c,reg_SP);
3506 if (esp1>=(void **)th->control_stack_start &&
3507 esp1<(void **)th->control_stack_end) {
3508 if(esp1<esp) esp=esp1;
3509 preserve_context_registers(c);
3514 esp = (void **)((void *)&raise);
3516 if (!esp || esp == (void*) -1)
3517 lose("garbage_collect: no SP known for thread %x (OS %x)",
3519 for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp; ptr--) {
3520 preserve_pointer(*ptr);
3525 /* Non-x86oid systems don't have "conservative roots" as such, but
3526 * the same mechanism is used for objects pinned for use by alien
3528 for_each_thread(th) {
3529 lispobj pin_list = SymbolTlValue(PINNED_OBJECTS,th);
3530 while (pin_list != NIL) {
3531 struct cons *list_entry =
3532 (struct cons *)native_pointer(pin_list);
3533 preserve_pointer(list_entry->car);
3534 pin_list = list_entry->cdr;
3540 if (gencgc_verbose > 1) {
3541 sword_t num_dont_move_pages = count_dont_move_pages();
3543 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3544 num_dont_move_pages,
3545 npage_bytes(num_dont_move_pages));
3549 /* Now that all of the pinned (dont_move) pages are known, and
3550 * before we start to scavenge (and thus relocate) objects,
3551 * relocate the pinned pages to newspace, so that the scavenger
3552 * will not attempt to relocate their contents. */
3553 move_pinned_pages_to_newspace();
3555 /* Scavenge all the rest of the roots. */
3557 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3559 * If not x86, we need to scavenge the interrupt context(s) and the
3564 for_each_thread(th) {
3565 scavenge_interrupt_contexts(th);
3566 scavenge_control_stack(th);
3569 # ifdef LISP_FEATURE_SB_SAFEPOINT
3570 /* In this case, scrub all stacks right here from the GCing thread
3571 * instead of doing what the comment below says. Suboptimal, but
3574 scrub_thread_control_stack(th);
3576 /* Scrub the unscavenged control stack space, so that we can't run
3577 * into any stale pointers in a later GC (this is done by the
3578 * stop-for-gc handler in the other threads). */
3579 scrub_control_stack();
3584 /* Scavenge the Lisp functions of the interrupt handlers, taking
3585 * care to avoid SIG_DFL and SIG_IGN. */
3586 for (i = 0; i < NSIG; i++) {
3587 union interrupt_handler handler = interrupt_handlers[i];
3588 if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3589 !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3590 scavenge((lispobj *)(interrupt_handlers + i), 1);
3593 /* Scavenge the binding stacks. */
3596 for_each_thread(th) {
3597 sword_t len= (lispobj *)get_binding_stack_pointer(th) -
3598 th->binding_stack_start;
3599 scavenge((lispobj *) th->binding_stack_start,len);
3600 #ifdef LISP_FEATURE_SB_THREAD
3601 /* do the tls as well */
3602 len=(SymbolValue(FREE_TLS_INDEX,0) >> WORD_SHIFT) -
3603 (sizeof (struct thread))/(sizeof (lispobj));
3604 scavenge((lispobj *) (th+1),len);
3609 /* The original CMU CL code had scavenge-read-only-space code
3610 * controlled by the Lisp-level variable
3611 * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3612 * wasn't documented under what circumstances it was useful or
3613 * safe to turn it on, so it's been turned off in SBCL. If you
3614 * want/need this functionality, and can test and document it,
3615 * please submit a patch. */
3617 if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3618 uword_t read_only_space_size =
3619 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3620 (lispobj*)READ_ONLY_SPACE_START;
3622 "/scavenge read only space: %d bytes\n",
3623 read_only_space_size * sizeof(lispobj)));
3624 scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3628 /* Scavenge static space. */
3630 (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3631 (lispobj *)STATIC_SPACE_START;
3632 if (gencgc_verbose > 1) {
3634 "/scavenge static space: %d bytes\n",
3635 static_space_size * sizeof(lispobj)));
3637 scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3639 /* All generations but the generation being GCed need to be
3640 * scavenged. The new_space generation needs special handling as
3641 * objects may be moved in - it is handled separately below. */
3642 scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
3644 /* Finally scavenge the new_space generation. Keep going until no
3645 * more objects are moved into the new generation */
3646 scavenge_newspace_generation(new_space);
3648 /* FIXME: I tried reenabling this check when debugging unrelated
3649 * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3650 * Since the current GC code seems to work well, I'm guessing that
3651 * this debugging code is just stale, but I haven't tried to
3652 * figure it out. It should be figured out and then either made to
3653 * work or just deleted. */
3654 #define RESCAN_CHECK 0
3656 /* As a check re-scavenge the newspace once; no new objects should
3659 os_vm_size_t old_bytes_allocated = bytes_allocated;
3660 os_vm_size_t bytes_allocated;
3662 /* Start with a full scavenge. */
3663 scavenge_newspace_generation_one_scan(new_space);
3665 /* Flush the current regions, updating the tables. */
3666 gc_alloc_update_all_page_tables();
3668 bytes_allocated = bytes_allocated - old_bytes_allocated;
3670 if (bytes_allocated != 0) {
3671 lose("Rescan of new_space allocated %d more bytes.\n",
3677 scan_weak_hash_tables();
3678 scan_weak_pointers();
3680 /* Flush the current regions, updating the tables. */
3681 gc_alloc_update_all_page_tables();
3683 /* Free the pages in oldspace, but not those marked dont_move. */
3684 bytes_freed = free_oldspace();
3686 /* If the GC is not raising the age then lower the generation back
3687 * to its normal generation number */
3689 for (i = 0; i < last_free_page; i++)
3690 if ((page_table[i].bytes_used != 0)
3691 && (page_table[i].gen == SCRATCH_GENERATION))
3692 page_table[i].gen = generation;
3693 gc_assert(generations[generation].bytes_allocated == 0);
3694 generations[generation].bytes_allocated =
3695 generations[SCRATCH_GENERATION].bytes_allocated;
3696 generations[SCRATCH_GENERATION].bytes_allocated = 0;
3699 /* Reset the alloc_start_page for generation. */
3700 generations[generation].alloc_start_page = 0;
3701 generations[generation].alloc_unboxed_start_page = 0;
3702 generations[generation].alloc_large_start_page = 0;
3703 generations[generation].alloc_large_unboxed_start_page = 0;
3705 if (generation >= verify_gens) {
3706 if (gencgc_verbose) {
3710 verify_dynamic_space();
3713 /* Set the new gc trigger for the GCed generation. */
3714 generations[generation].gc_trigger =
3715 generations[generation].bytes_allocated
3716 + generations[generation].bytes_consed_between_gc;
3719 generations[generation].num_gc = 0;
3721 ++generations[generation].num_gc;
3725 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3727 update_dynamic_space_free_pointer(void)
3729 page_index_t last_page = -1, i;
3731 for (i = 0; i < last_free_page; i++)
3732 if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
3735 last_free_page = last_page+1;
3737 set_alloc_pointer((lispobj)(page_address(last_free_page)));
3738 return 0; /* dummy value: return something ... */
3742 remap_page_range (page_index_t from, page_index_t to)
3744 /* There's a mysterious Solaris/x86 problem with using mmap
3745 * tricks for memory zeroing. See sbcl-devel thread
3746 * "Re: patch: standalone executable redux".
3748 #if defined(LISP_FEATURE_SUNOS)
3749 zero_and_mark_pages(from, to);
3752 release_granularity = gencgc_release_granularity/GENCGC_CARD_BYTES,
3753 release_mask = release_granularity-1,
3755 aligned_from = (from+release_mask)&~release_mask,
3756 aligned_end = (end&~release_mask);
3758 if (aligned_from < aligned_end) {
3759 zero_pages_with_mmap(aligned_from, aligned_end-1);
3760 if (aligned_from != from)
3761 zero_and_mark_pages(from, aligned_from-1);
3762 if (aligned_end != end)
3763 zero_and_mark_pages(aligned_end, end-1);
3765 zero_and_mark_pages(from, to);
3771 remap_free_pages (page_index_t from, page_index_t to, int forcibly)
3773 page_index_t first_page, last_page;
3776 return remap_page_range(from, to);
3778 for (first_page = from; first_page <= to; first_page++) {
3779 if (page_allocated_p(first_page) ||
3780 (page_table[first_page].need_to_zero == 0))
3783 last_page = first_page + 1;
3784 while (page_free_p(last_page) &&
3785 (last_page <= to) &&
3786 (page_table[last_page].need_to_zero == 1))
3789 remap_page_range(first_page, last_page-1);
3791 first_page = last_page;
3795 generation_index_t small_generation_limit = 1;
3797 /* GC all generations newer than last_gen, raising the objects in each
3798 * to the next older generation - we finish when all generations below
3799 * last_gen are empty. Then if last_gen is due for a GC, or if
3800 * last_gen==NUM_GENERATIONS (the scratch generation? eh?) we GC that
3801 * too. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3803 * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3804 * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3806 collect_garbage(generation_index_t last_gen)
3808 generation_index_t gen = 0, i;
3809 int raise, more = 0;
3811 /* The largest value of last_free_page seen since the time
3812 * remap_free_pages was called. */
3813 static page_index_t high_water_mark = 0;
3815 FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
3816 log_generation_stats(gc_logfile, "=== GC Start ===");
3820 if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
3822 "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3827 /* Flush the alloc regions updating the tables. */
3828 gc_alloc_update_all_page_tables();
3830 /* Verify the new objects created by Lisp code. */
3831 if (pre_verify_gen_0) {
3832 FSHOW((stderr, "pre-checking generation 0\n"));
3833 verify_generation(0);
3836 if (gencgc_verbose > 1)
3837 print_generation_stats();
3840 /* Collect the generation. */
3842 if (more || (gen >= gencgc_oldest_gen_to_gc)) {
3843 /* Never raise the oldest generation. Never raise the extra generation
3844 * collected due to more-flag. */
3850 || (generations[gen].num_gc >= generations[gen].number_of_gcs_before_promotion);
3851 /* If we would not normally raise this one, but we're
3852 * running low on space in comparison to the object-sizes
3853 * we've been seeing, raise it and collect the next one
3855 if (!raise && gen == last_gen) {
3856 more = (2*large_allocation) >= (dynamic_space_size - bytes_allocated);
3861 if (gencgc_verbose > 1) {
3863 "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3866 generations[gen].bytes_allocated,
3867 generations[gen].gc_trigger,
3868 generations[gen].num_gc));
3871 /* If an older generation is being filled, then update its
3874 generations[gen+1].cum_sum_bytes_allocated +=
3875 generations[gen+1].bytes_allocated;
3878 garbage_collect_generation(gen, raise);
3880 /* Reset the memory age cum_sum. */
3881 generations[gen].cum_sum_bytes_allocated = 0;
3883 if (gencgc_verbose > 1) {
3884 FSHOW((stderr, "GC of generation %d finished:\n", gen));
3885 print_generation_stats();
3889 } while ((gen <= gencgc_oldest_gen_to_gc)
3890 && ((gen < last_gen)
3893 && (generations[gen].bytes_allocated
3894 > generations[gen].gc_trigger)
3895 && (generation_average_age(gen)
3896 > generations[gen].minimum_age_before_gc))));
3898 /* Now if gen-1 was raised all generations before gen are empty.
3899 * If it wasn't raised then all generations before gen-1 are empty.
3901 * Now objects within this gen's pages cannot point to younger
3902 * generations unless they are written to. This can be exploited
3903 * by write-protecting the pages of gen; then when younger
3904 * generations are GCed only the pages which have been written
3909 gen_to_wp = gen - 1;
3911 /* There's not much point in WPing pages in generation 0 as it is
3912 * never scavenged (except promoted pages). */
3913 if ((gen_to_wp > 0) && enable_page_protection) {
3914 /* Check that they are all empty. */
3915 for (i = 0; i < gen_to_wp; i++) {
3916 if (generations[i].bytes_allocated)
3917 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
3920 write_protect_generation_pages(gen_to_wp);
3923 /* Set gc_alloc() back to generation 0. The current regions should
3924 * be flushed after the above GCs. */
3925 gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
3926 gc_alloc_generation = 0;
3928 /* Save the high-water mark before updating last_free_page */
3929 if (last_free_page > high_water_mark)
3930 high_water_mark = last_free_page;
3932 update_dynamic_space_free_pointer();
3934 /* Update auto_gc_trigger. Make sure we trigger the next GC before
3935 * running out of heap! */
3936 if (bytes_consed_between_gcs <= (dynamic_space_size - bytes_allocated))
3937 auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
3939 auto_gc_trigger = bytes_allocated + (dynamic_space_size - bytes_allocated)/2;
3942 fprintf(stderr,"Next gc when %"OS_VM_SIZE_FMT" bytes have been consed\n",
3945 /* If we did a big GC (arbitrarily defined as gen > 1), release memory
3948 if (gen > small_generation_limit) {
3949 if (last_free_page > high_water_mark)
3950 high_water_mark = last_free_page;
3951 remap_free_pages(0, high_water_mark, 0);
3952 high_water_mark = 0;
3956 large_allocation = 0;
3958 log_generation_stats(gc_logfile, "=== GC End ===");
3959 SHOW("returning from collect_garbage");
3962 /* This is called by Lisp PURIFY when it is finished. All live objects
3963 * will have been moved to the RO and Static heaps. The dynamic space
3964 * will need a full re-initialization. We don't bother having Lisp
3965 * PURIFY flush the current gc_alloc() region, as the page_tables are
3966 * re-initialized, and every page is zeroed to be sure. */
3970 page_index_t page, last_page;
3972 if (gencgc_verbose > 1) {
3973 SHOW("entering gc_free_heap");
3976 for (page = 0; page < page_table_pages; page++) {
3977 /* Skip free pages which should already be zero filled. */
3978 if (page_allocated_p(page)) {
3980 for (last_page = page;
3981 (last_page < page_table_pages) && page_allocated_p(last_page);
3983 /* Mark the page free. The other slots are assumed invalid
3984 * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
3985 * should not be write-protected -- except that the
3986 * generation is used for the current region but it sets
3988 page_table[page].allocated = FREE_PAGE_FLAG;
3989 page_table[page].bytes_used = 0;
3990 page_table[page].write_protected = 0;
3993 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
3994 * about this change. */
3995 page_start = (void *)page_address(page);
3996 os_protect(page_start, npage_bytes(last_page-page), OS_VM_PROT_ALL);
3997 remap_free_pages(page, last_page-1, 1);
4000 } else if (gencgc_zero_check_during_free_heap) {
4001 /* Double-check that the page is zero filled. */
4002 sword_t *page_start;
4004 gc_assert(page_free_p(page));
4005 gc_assert(page_table[page].bytes_used == 0);
4006 page_start = (sword_t *)page_address(page);
4007 for (i=0; i<GENCGC_CARD_BYTES/sizeof(sword_t); i++) {
4008 if (page_start[i] != 0) {
4009 lose("free region not zero at %x\n", page_start + i);
4015 bytes_allocated = 0;
4017 /* Initialize the generations. */
4018 for (page = 0; page < NUM_GENERATIONS; page++) {
4019 generations[page].alloc_start_page = 0;
4020 generations[page].alloc_unboxed_start_page = 0;
4021 generations[page].alloc_large_start_page = 0;
4022 generations[page].alloc_large_unboxed_start_page = 0;
4023 generations[page].bytes_allocated = 0;
4024 generations[page].gc_trigger = 2000000;
4025 generations[page].num_gc = 0;
4026 generations[page].cum_sum_bytes_allocated = 0;
4029 if (gencgc_verbose > 1)
4030 print_generation_stats();
4032 /* Initialize gc_alloc(). */
4033 gc_alloc_generation = 0;
4035 gc_set_region_empty(&boxed_region);
4036 gc_set_region_empty(&unboxed_region);
4039 set_alloc_pointer((lispobj)((char *)heap_base));
4041 if (verify_after_free_heap) {
4042 /* Check whether purify has left any bad pointers. */
4043 FSHOW((stderr, "checking after free_heap\n"));
4053 #if defined(LISP_FEATURE_SB_SAFEPOINT)
4057 /* Compute the number of pages needed for the dynamic space.
4058 * Dynamic space size should be aligned on page size. */
4059 page_table_pages = dynamic_space_size/GENCGC_CARD_BYTES;
4060 gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4062 /* Default nursery size to 5% of the total dynamic space size,
4064 bytes_consed_between_gcs = dynamic_space_size/(os_vm_size_t)20;
4065 if (bytes_consed_between_gcs < (1024*1024))
4066 bytes_consed_between_gcs = 1024*1024;
4068 /* The page_table must be allocated using "calloc" to initialize
4069 * the page structures correctly. There used to be a separate
4070 * initialization loop (now commented out; see below) but that was
4071 * unnecessary and did hurt startup time. */
4072 page_table = calloc(page_table_pages, sizeof(struct page));
4073 gc_assert(page_table);
4076 scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4077 transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4079 heap_base = (void*)DYNAMIC_SPACE_START;
4081 /* The page structures are initialized implicitly when page_table
4082 * is allocated with "calloc" above. Formerly we had the following
4083 * explicit initialization here (comments converted to C99 style
4084 * for readability as C's block comments don't nest):
4086 * // Initialize each page structure.
4087 * for (i = 0; i < page_table_pages; i++) {
4088 * // Initialize all pages as free.
4089 * page_table[i].allocated = FREE_PAGE_FLAG;
4090 * page_table[i].bytes_used = 0;
4092 * // Pages are not write-protected at startup.
4093 * page_table[i].write_protected = 0;
4096 * Without this loop the image starts up much faster when dynamic
4097 * space is large -- which it is on 64-bit platforms already by
4098 * default -- and when "calloc" for large arrays is implemented
4099 * using copy-on-write of a page of zeroes -- which it is at least
4100 * on Linux. In this case the pages that page_table_pages is stored
4101 * in are mapped and cleared not before the corresponding part of
4102 * dynamic space is used. For example, this saves clearing 16 MB of
4103 * memory at startup if the page size is 4 KB and the size of
4104 * dynamic space is 4 GB.
4105 * FREE_PAGE_FLAG must be 0 for this to work correctly which is
4106 * asserted below: */
4108 /* Compile time assertion: If triggered, declares an array
4109 * of dimension -1 forcing a syntax error. The intent of the
4110 * assignment is to avoid an "unused variable" warning. */
4111 char assert_free_page_flag_0[(FREE_PAGE_FLAG) ? -1 : 1];
4112 assert_free_page_flag_0[0] = assert_free_page_flag_0[0];
4115 bytes_allocated = 0;
4117 /* Initialize the generations.
4119 * FIXME: very similar to code in gc_free_heap(), should be shared */
4120 for (i = 0; i < NUM_GENERATIONS; i++) {
4121 generations[i].alloc_start_page = 0;
4122 generations[i].alloc_unboxed_start_page = 0;
4123 generations[i].alloc_large_start_page = 0;
4124 generations[i].alloc_large_unboxed_start_page = 0;
4125 generations[i].bytes_allocated = 0;
4126 generations[i].gc_trigger = 2000000;
4127 generations[i].num_gc = 0;
4128 generations[i].cum_sum_bytes_allocated = 0;
4129 /* the tune-able parameters */
4130 generations[i].bytes_consed_between_gc
4131 = bytes_consed_between_gcs/(os_vm_size_t)HIGHEST_NORMAL_GENERATION;
4132 generations[i].number_of_gcs_before_promotion = 1;
4133 generations[i].minimum_age_before_gc = 0.75;
4136 /* Initialize gc_alloc. */
4137 gc_alloc_generation = 0;
4138 gc_set_region_empty(&boxed_region);
4139 gc_set_region_empty(&unboxed_region);
4144 /* Pick up the dynamic space from after a core load.
4146 * The ALLOCATION_POINTER points to the end of the dynamic space.
4150 gencgc_pickup_dynamic(void)
4152 page_index_t page = 0;
4153 void *alloc_ptr = (void *)get_alloc_pointer();
4154 lispobj *prev=(lispobj *)page_address(page);
4155 generation_index_t gen = PSEUDO_STATIC_GENERATION;
4157 bytes_allocated = 0;
4160 lispobj *first,*ptr= (lispobj *)page_address(page);
4162 if (!gencgc_partial_pickup || page_allocated_p(page)) {
4163 /* It is possible, though rare, for the saved page table
4164 * to contain free pages below alloc_ptr. */
4165 page_table[page].gen = gen;
4166 page_table[page].bytes_used = GENCGC_CARD_BYTES;
4167 page_table[page].large_object = 0;
4168 page_table[page].write_protected = 0;
4169 page_table[page].write_protected_cleared = 0;
4170 page_table[page].dont_move = 0;
4171 page_table[page].need_to_zero = 1;
4173 bytes_allocated += GENCGC_CARD_BYTES;
4176 if (!gencgc_partial_pickup) {
4177 page_table[page].allocated = BOXED_PAGE_FLAG;
4178 first=gc_search_space(prev,(ptr+2)-prev,ptr);
4181 page_table[page].scan_start_offset =
4182 page_address(page) - (void *)prev;
4185 } while (page_address(page) < alloc_ptr);
4187 last_free_page = page;
4189 generations[gen].bytes_allocated = bytes_allocated;
4191 gc_alloc_update_all_page_tables();
4192 write_protect_generation_pages(gen);
4196 gc_initialize_pointers(void)
4198 gencgc_pickup_dynamic();
4202 /* alloc(..) is the external interface for memory allocation. It
4203 * allocates to generation 0. It is not called from within the garbage
4204 * collector as it is only external uses that need the check for heap
4205 * size (GC trigger) and to disable the interrupts (interrupts are
4206 * always disabled during a GC).
4208 * The vops that call alloc(..) assume that the returned space is zero-filled.
4209 * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4211 * The check for a GC trigger is only performed when the current
4212 * region is full, so in most cases it's not needed. */
4214 static inline lispobj *
4215 general_alloc_internal(sword_t nbytes, int page_type_flag, struct alloc_region *region,
4216 struct thread *thread)
4218 #ifndef LISP_FEATURE_WIN32
4219 lispobj alloc_signal;
4222 void *new_free_pointer;
4223 os_vm_size_t trigger_bytes = 0;
4225 gc_assert(nbytes>0);
4227 /* Check for alignment allocation problems. */
4228 gc_assert((((uword_t)region->free_pointer & LOWTAG_MASK) == 0)
4229 && ((nbytes & LOWTAG_MASK) == 0));
4231 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
4232 /* Must be inside a PA section. */
4233 gc_assert(get_pseudo_atomic_atomic(thread));
4236 if (nbytes > large_allocation)
4237 large_allocation = nbytes;
4239 /* maybe we can do this quickly ... */
4240 new_free_pointer = region->free_pointer + nbytes;
4241 if (new_free_pointer <= region->end_addr) {
4242 new_obj = (void*)(region->free_pointer);
4243 region->free_pointer = new_free_pointer;
4244 return(new_obj); /* yup */
4247 /* We don't want to count nbytes against auto_gc_trigger unless we
4248 * have to: it speeds up the tenuring of objects and slows down
4249 * allocation. However, unless we do so when allocating _very_
4250 * large objects we are in danger of exhausting the heap without
4251 * running sufficient GCs.
4253 if (nbytes >= bytes_consed_between_gcs)
4254 trigger_bytes = nbytes;
4256 /* we have to go the long way around, it seems. Check whether we
4257 * should GC in the near future
4259 if (auto_gc_trigger && (bytes_allocated+trigger_bytes > auto_gc_trigger)) {
4260 /* Don't flood the system with interrupts if the need to gc is
4261 * already noted. This can happen for example when SUB-GC
4262 * allocates or after a gc triggered in a WITHOUT-GCING. */
4263 if (SymbolValue(GC_PENDING,thread) == NIL) {
4264 /* set things up so that GC happens when we finish the PA
4266 SetSymbolValue(GC_PENDING,T,thread);
4267 if (SymbolValue(GC_INHIBIT,thread) == NIL) {
4268 #ifdef LISP_FEATURE_SB_SAFEPOINT
4269 thread_register_gc_trigger();
4271 set_pseudo_atomic_interrupted(thread);
4272 #ifdef GENCGC_IS_PRECISE
4273 /* PPC calls alloc() from a trap or from pa_alloc(),
4274 * look up the most context if it's from a trap. */
4276 os_context_t *context =
4277 thread->interrupt_data->allocation_trap_context;
4278 maybe_save_gc_mask_and_block_deferrables
4279 (context ? os_context_sigmask_addr(context) : NULL);
4282 maybe_save_gc_mask_and_block_deferrables(NULL);
4288 new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4290 #ifndef LISP_FEATURE_WIN32
4291 /* for sb-prof, and not supported on Windows yet */
4292 alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4293 if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4294 if ((sword_t) alloc_signal <= 0) {
4295 SetSymbolValue(ALLOC_SIGNAL, T, thread);
4298 SetSymbolValue(ALLOC_SIGNAL,
4299 alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4309 general_alloc(sword_t nbytes, int page_type_flag)
4311 struct thread *thread = arch_os_get_current_thread();
4312 /* Select correct region, and call general_alloc_internal with it.
4313 * For other then boxed allocation we must lock first, since the
4314 * region is shared. */
4315 if (BOXED_PAGE_FLAG & page_type_flag) {
4316 #ifdef LISP_FEATURE_SB_THREAD
4317 struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4319 struct alloc_region *region = &boxed_region;
4321 return general_alloc_internal(nbytes, page_type_flag, region, thread);
4322 } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4324 gc_assert(0 == thread_mutex_lock(&allocation_lock));
4325 obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4326 gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4329 lose("bad page type flag: %d", page_type_flag);
4333 lispobj AMD64_SYSV_ABI *
4336 #ifdef LISP_FEATURE_SB_SAFEPOINT_STRICTLY
4337 struct thread *self = arch_os_get_current_thread();
4338 int was_pseudo_atomic = get_pseudo_atomic_atomic(self);
4339 if (!was_pseudo_atomic)
4340 set_pseudo_atomic_atomic(self);
4342 gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4345 lispobj *result = general_alloc(nbytes, BOXED_PAGE_FLAG);
4347 #ifdef LISP_FEATURE_SB_SAFEPOINT_STRICTLY
4348 if (!was_pseudo_atomic)
4349 clear_pseudo_atomic_atomic(self);
4356 * shared support for the OS-dependent signal handlers which
4357 * catch GENCGC-related write-protect violations
4359 void unhandled_sigmemoryfault(void* addr);
4361 /* Depending on which OS we're running under, different signals might
4362 * be raised for a violation of write protection in the heap. This
4363 * function factors out the common generational GC magic which needs
4364 * to invoked in this case, and should be called from whatever signal
4365 * handler is appropriate for the OS we're running under.
4367 * Return true if this signal is a normal generational GC thing that
4368 * we were able to handle, or false if it was abnormal and control
4369 * should fall through to the general SIGSEGV/SIGBUS/whatever logic.
4371 * We have two control flags for this: one causes us to ignore faults
4372 * on unprotected pages completely, and the second complains to stderr
4373 * but allows us to continue without losing.
4375 extern boolean ignore_memoryfaults_on_unprotected_pages;
4376 boolean ignore_memoryfaults_on_unprotected_pages = 0;
4378 extern boolean continue_after_memoryfault_on_unprotected_pages;
4379 boolean continue_after_memoryfault_on_unprotected_pages = 0;
4382 gencgc_handle_wp_violation(void* fault_addr)
4384 page_index_t page_index = find_page_index(fault_addr);
4387 FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4388 fault_addr, page_index));
4391 /* Check whether the fault is within the dynamic space. */
4392 if (page_index == (-1)) {
4394 /* It can be helpful to be able to put a breakpoint on this
4395 * case to help diagnose low-level problems. */
4396 unhandled_sigmemoryfault(fault_addr);
4398 /* not within the dynamic space -- not our responsibility */
4403 ret = thread_mutex_lock(&free_pages_lock);
4404 gc_assert(ret == 0);
4405 if (page_table[page_index].write_protected) {
4406 /* Unprotect the page. */
4407 os_protect(page_address(page_index), GENCGC_CARD_BYTES, OS_VM_PROT_ALL);
4408 page_table[page_index].write_protected_cleared = 1;
4409 page_table[page_index].write_protected = 0;
4410 } else if (!ignore_memoryfaults_on_unprotected_pages) {
4411 /* The only acceptable reason for this signal on a heap
4412 * access is that GENCGC write-protected the page.
4413 * However, if two CPUs hit a wp page near-simultaneously,
4414 * we had better not have the second one lose here if it
4415 * does this test after the first one has already set wp=0
4417 if(page_table[page_index].write_protected_cleared != 1) {
4418 void lisp_backtrace(int frames);
4421 "Fault @ %p, page %"PAGE_INDEX_FMT" not marked as write-protected:\n"
4422 " boxed_region.first_page: %"PAGE_INDEX_FMT","
4423 " boxed_region.last_page %"PAGE_INDEX_FMT"\n"
4424 " page.scan_start_offset: %"OS_VM_SIZE_FMT"\n"
4425 " page.bytes_used: %"PAGE_BYTES_FMT"\n"
4426 " page.allocated: %d\n"
4427 " page.write_protected: %d\n"
4428 " page.write_protected_cleared: %d\n"
4429 " page.generation: %d\n",
4432 boxed_region.first_page,
4433 boxed_region.last_page,
4434 page_table[page_index].scan_start_offset,
4435 page_table[page_index].bytes_used,
4436 page_table[page_index].allocated,
4437 page_table[page_index].write_protected,
4438 page_table[page_index].write_protected_cleared,
4439 page_table[page_index].gen);
4440 if (!continue_after_memoryfault_on_unprotected_pages)
4444 ret = thread_mutex_unlock(&free_pages_lock);
4445 gc_assert(ret == 0);
4446 /* Don't worry, we can handle it. */
4450 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4451 * it's not just a case of the program hitting the write barrier, and
4452 * are about to let Lisp deal with it. It's basically just a
4453 * convenient place to set a gdb breakpoint. */
4455 unhandled_sigmemoryfault(void *addr)
4458 void gc_alloc_update_all_page_tables(void)
4460 /* Flush the alloc regions updating the tables. */
4462 for_each_thread(th) {
4463 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4464 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
4465 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->sprof_alloc_region);
4468 gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4469 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4473 gc_set_region_empty(struct alloc_region *region)
4475 region->first_page = 0;
4476 region->last_page = -1;
4477 region->start_addr = page_address(0);
4478 region->free_pointer = page_address(0);
4479 region->end_addr = page_address(0);
4483 zero_all_free_pages()
4487 for (i = 0; i < last_free_page; i++) {
4488 if (page_free_p(i)) {
4489 #ifdef READ_PROTECT_FREE_PAGES
4490 os_protect(page_address(i),
4499 /* Things to do before doing a final GC before saving a core (without
4502 * + Pages in large_object pages aren't moved by the GC, so we need to
4503 * unset that flag from all pages.
4504 * + The pseudo-static generation isn't normally collected, but it seems
4505 * reasonable to collect it at least when saving a core. So move the
4506 * pages to a normal generation.
4509 prepare_for_final_gc ()
4512 for (i = 0; i < last_free_page; i++) {
4513 page_table[i].large_object = 0;
4514 if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4515 int used = page_table[i].bytes_used;
4516 page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4517 generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4518 generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4524 /* Do a non-conservative GC, and then save a core with the initial
4525 * function being set to the value of the static symbol
4526 * SB!VM:RESTART-LISP-FUNCTION */
4528 gc_and_save(char *filename, boolean prepend_runtime,
4529 boolean save_runtime_options,
4530 boolean compressed, int compression_level)
4533 void *runtime_bytes = NULL;
4534 size_t runtime_size;
4536 file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4541 conservative_stack = 0;
4543 /* The filename might come from Lisp, and be moved by the now
4544 * non-conservative GC. */
4545 filename = strdup(filename);
4547 /* Collect twice: once into relatively high memory, and then back
4548 * into low memory. This compacts the retained data into the lower
4549 * pages, minimizing the size of the core file.
4551 prepare_for_final_gc();
4552 gencgc_alloc_start_page = last_free_page;
4553 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4555 prepare_for_final_gc();
4556 gencgc_alloc_start_page = -1;
4557 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4559 if (prepend_runtime)
4560 save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
4562 /* The dumper doesn't know that pages need to be zeroed before use. */
4563 zero_all_free_pages();
4564 save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4565 prepend_runtime, save_runtime_options,
4566 compressed ? compression_level : COMPRESSION_LEVEL_NONE);
4567 /* Oops. Save still managed to fail. Since we've mangled the stack
4568 * beyond hope, there's not much we can do.
4569 * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4570 * going to be rather unsatisfactory too... */
4571 lose("Attempt to save core after non-conservative GC failed.\n");