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>.
33 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
34 #include "pthreads_win32.h"
42 #include "interrupt.h"
47 #include "gc-internal.h"
49 #include "pseudo-atomic.h"
51 #include "genesis/gc-tables.h"
52 #include "genesis/vector.h"
53 #include "genesis/weak-pointer.h"
54 #include "genesis/fdefn.h"
55 #include "genesis/simple-fun.h"
57 #include "genesis/hash-table.h"
58 #include "genesis/instance.h"
59 #include "genesis/layout.h"
61 #include "hopscotch.h"
62 #include "genesis/cons.h"
63 #include "forwarding-ptr.h"
65 /* forward declarations */
66 page_index_t
gc_find_freeish_pages(page_index_t
*restart_page_ptr
, sword_t nbytes
,
74 /* As usually configured, generations 0-5 are normal collected generations,
75 6 is pseudo-static (the objects in which are never moved nor reclaimed),
76 and 7 is scratch space used when collecting a generation without promotion,
77 wherein it is moved to generation 7 and back again.
80 SCRATCH_GENERATION
= PSEUDO_STATIC_GENERATION
+1,
84 /* Largest allocation seen since last GC. */
85 os_vm_size_t large_allocation
= 0;
92 /* the verbosity level. All non-error messages are disabled at level 0;
93 * and only a few rare messages are printed at level 1. */
95 boolean gencgc_verbose
= 1;
97 boolean gencgc_verbose
= 0;
100 /* FIXME: At some point enable the various error-checking things below
101 * and see what they say. */
103 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
104 * Set verify_gens to HIGHEST_NORMAL_GENERATION + 1 to disable this kind of
106 generation_index_t verify_gens
= HIGHEST_NORMAL_GENERATION
+ 1;
108 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
109 boolean pre_verify_gen_0
= 0;
111 /* Should we check that newly allocated regions are zero filled? */
112 boolean gencgc_zero_check
= 0;
114 /* Should we check that the free space is zero filled? */
115 /* Don't use this - you'll get more mileage out of READ_PROTECT_FREE_PAGES,
116 * because we zero-fill lazily. This switch should probably be removed. */
117 boolean gencgc_enable_verify_zero_fill
= 0;
119 /* When loading a core, don't do a full scan of the memory for the
120 * memory region boundaries. (Set to true by coreparse.c if the core
121 * contained a pagetable entry).
123 boolean gencgc_partial_pickup
= 0;
125 /* If defined, free pages are read-protected to ensure that nothing
129 /* #define READ_PROTECT_FREE_PAGES */
133 * GC structures and variables
136 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
137 os_vm_size_t bytes_allocated
= 0;
138 os_vm_size_t auto_gc_trigger
= 0;
140 /* the source and destination generations. These are set before a GC starts
142 generation_index_t from_space
;
143 generation_index_t new_space
;
145 /* Set to 1 when in GC */
146 boolean gc_active_p
= 0;
148 /* should the GC be conservative on stack. If false (only right before
149 * saving a core), don't scan the stack / mark pages dont_move. */
150 static boolean conservative_stack
= 1;
152 /* An array of page structures is allocated on gc initialization.
153 * This helps to quickly map between an address and its page structure.
154 * page_table_pages is set from the size of the dynamic space. */
155 page_index_t page_table_pages
;
156 struct page
*page_table
;
157 #ifdef LISP_FEATURE_SB_TRACEROOT
158 lispobj gc_object_watcher
;
159 int gc_traceroot_criterion
;
161 #ifdef PIN_GRANULARITY_LISPOBJ
163 struct hopscotch_table pinned_objects
;
166 /* This is always 0 except during gc_and_save() */
167 lispobj lisp_init_function
;
169 /// Constants defined in gc-internal:
170 /// #define BOXED_PAGE_FLAG 1
171 /// #define UNBOXED_PAGE_FLAG 2
172 /// #define OPEN_REGION_PAGE_FLAG 4
174 /// Return true if 'allocated' bits are: {001, 010, 011}, false if 1zz or 000.
175 static inline boolean
page_allocated_no_region_p(page_index_t page
) {
176 return (page_table
[page
].allocated
^ OPEN_REGION_PAGE_FLAG
) > OPEN_REGION_PAGE_FLAG
;
179 static inline boolean
page_free_p(page_index_t page
) {
180 return (page_table
[page
].allocated
== FREE_PAGE_FLAG
);
183 static inline boolean
page_boxed_p(page_index_t page
) {
184 return (page_table
[page
].allocated
& BOXED_PAGE_FLAG
);
187 /// Return true if 'allocated' bits are: {001, 011}, false otherwise.
188 /// i.e. true of pages which could hold boxed or partially boxed objects.
189 static inline boolean
page_boxed_no_region_p(page_index_t page
) {
190 return (page_table
[page
].allocated
& 5) == BOXED_PAGE_FLAG
;
193 /// Return true if page MUST NOT hold boxed objects (including code).
194 static inline boolean
page_unboxed_p(page_index_t page
) {
195 /* Both flags set == boxed code page */
196 return (page_table
[page
].allocated
& 3) == UNBOXED_PAGE_FLAG
;
199 static inline boolean
protect_page_p(page_index_t page
, generation_index_t generation
) {
200 return (page_boxed_no_region_p(page
)
201 && (page_bytes_used(page
) != 0)
202 && !page_table
[page
].dont_move
203 && (page_table
[page
].gen
== generation
));
206 /* Calculate the start address for the given page number. */
208 page_address(page_index_t page_num
)
210 return (void*)(DYNAMIC_SPACE_START
+ (page_num
* GENCGC_CARD_BYTES
));
213 /* Calculate the address where the allocation region associated with
214 * the page starts. */
216 page_scan_start(page_index_t page_index
)
218 return page_address(page_index
)-page_scan_start_offset(page_index
);
221 /* True if the page starts a contiguous block. */
222 static inline boolean
223 page_starts_contiguous_block_p(page_index_t page_index
)
225 // Don't use the preprocessor macro: 0 means 0.
226 return page_table
[page_index
].scan_start_offset_
== 0;
229 /* True if the page is the last page in a contiguous block. */
230 static inline boolean
231 page_ends_contiguous_block_p(page_index_t page_index
, generation_index_t gen
)
235 (/* page doesn't fill block */
236 (page_bytes_used(page_index
) < GENCGC_CARD_BYTES
)
237 /* page is last allocated page */
238 || ((page_index
+ 1) >= last_free_page
)
239 /* next page contains no data */
240 || !page_bytes_used(page_index
+ 1)
241 /* next page is in different generation */
242 || (page_table
[page_index
+ 1].gen
!= gen
)
243 /* next page starts its own contiguous block */
244 || (page_starts_contiguous_block_p(page_index
+ 1)));
245 gc_assert(page_starts_contiguous_block_p(page_index
+1) == answer
);
247 return page_starts_contiguous_block_p(page_index
+1);
250 /* We maintain the invariant that pages with FREE_PAGE_FLAG have
251 * scan_start of zero, to optimize page_ends_contiguous_block_p().
252 * Clear all other flags as well, since they don't mean anything,
253 * and a store is simpler than a bitwise operation */
254 static inline void reset_page_flags(page_index_t page
) {
255 page_table
[page
].scan_start_offset_
= 0;
256 // Any C compiler worth its salt should merge these into one store
257 page_table
[page
].allocated
= page_table
[page
].write_protected
258 = page_table
[page
].write_protected_cleared
259 = page_table
[page
].dont_move
= page_table
[page
].has_pins
260 = page_table
[page
].large_object
= 0;
263 /// External function for calling from Lisp.
264 page_index_t
ext_find_page_index(void *addr
) { return find_page_index(addr
); }
267 npage_bytes(page_index_t npages
)
269 gc_assert(npages
>=0);
270 return ((os_vm_size_t
)npages
)*GENCGC_CARD_BYTES
;
273 /* Check that X is a higher address than Y and return offset from Y to
275 static inline os_vm_size_t
276 addr_diff(void *x
, void *y
)
279 return (uintptr_t)x
- (uintptr_t)y
;
282 /* a structure to hold the state of a generation
284 * CAUTION: If you modify this, make sure to touch up the alien
285 * definition in src/code/gc.lisp accordingly. ...or better yes,
286 * deal with the FIXME there...
290 #ifdef LISP_FEATURE_SEGREGATED_CODE
291 // A distinct start page per nonzero value of 'page_type_flag'.
292 // The zeroth index is the large object start page.
293 page_index_t alloc_start_page_
[4];
294 #define alloc_large_start_page alloc_start_page_[0]
295 #define alloc_start_page alloc_start_page_[BOXED_PAGE_FLAG]
296 #define alloc_unboxed_start_page alloc_start_page_[UNBOXED_PAGE_FLAG]
298 /* the first page that gc_alloc_large (boxed) considers on its next
299 * call. (Although it always allocates after the boxed_region.) */
300 page_index_t alloc_large_start_page
;
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
;
309 /* the bytes allocated to this generation */
310 os_vm_size_t bytes_allocated
;
312 /* the number of bytes at which to trigger a GC */
313 os_vm_size_t gc_trigger
;
315 /* to calculate a new level for gc_trigger */
316 os_vm_size_t bytes_consed_between_gc
;
318 /* the number of GCs since the last raise */
321 /* the number of GCs to run on the generations before raising objects to the
323 int number_of_gcs_before_promotion
;
325 /* the cumulative sum of the bytes allocated to this generation. It is
326 * cleared after a GC on this generations, and update before new
327 * objects are added from a GC of a younger generation. Dividing by
328 * the bytes_allocated will give the average age of the memory in
329 * this generation since its last GC. */
330 os_vm_size_t cum_sum_bytes_allocated
;
332 /* a minimum average memory age before a GC will occur helps
333 * prevent a GC when a large number of new live objects have been
334 * added, in which case a GC could be a waste of time */
335 double minimum_age_before_gc
;
338 /* an array of generation structures. There needs to be one more
339 * generation structure than actual generations as the oldest
340 * generation is temporarily raised then lowered. */
341 struct generation generations
[NUM_GENERATIONS
];
343 /* the oldest generation that is will currently be GCed by default.
344 * Valid values are: 0, 1, ... HIGHEST_NORMAL_GENERATION
346 * The default of HIGHEST_NORMAL_GENERATION enables GC on all generations.
348 * Setting this to 0 effectively disables the generational nature of
349 * the GC. In some applications generational GC may not be useful
350 * because there are no long-lived objects.
352 * An intermediate value could be handy after moving long-lived data
353 * into an older generation so an unnecessary GC of this long-lived
354 * data can be avoided. */
355 generation_index_t gencgc_oldest_gen_to_gc
= HIGHEST_NORMAL_GENERATION
;
357 /* META: Is nobody aside from me bothered by this especially misleading
358 * use of the word "last"? It could mean either "ultimate" or "prior",
359 * but in fact means neither. It is the *FIRST* page that should be grabbed
360 * for more space, so it is min free page, or 1+ the max used page. */
361 /* The maximum free page in the heap is maintained and used to update
362 * ALLOCATION_POINTER which is used by the room function to limit its
363 * search of the heap. XX Gencgc obviously needs to be better
364 * integrated with the Lisp code. */
366 page_index_t last_free_page
;
368 #ifdef LISP_FEATURE_SB_THREAD
369 /* This lock is to prevent multiple threads from simultaneously
370 * allocating new regions which overlap each other. Note that the
371 * majority of GC is single-threaded, but alloc() may be called from
372 * >1 thread at a time and must be thread-safe. This lock must be
373 * seized before all accesses to generations[] or to parts of
374 * page_table[] that other threads may want to see */
375 static pthread_mutex_t free_pages_lock
= PTHREAD_MUTEX_INITIALIZER
;
376 /* This lock is used to protect non-thread-local allocation. */
377 static pthread_mutex_t allocation_lock
= PTHREAD_MUTEX_INITIALIZER
;
380 extern os_vm_size_t gencgc_release_granularity
;
381 os_vm_size_t gencgc_release_granularity
= GENCGC_RELEASE_GRANULARITY
;
383 extern os_vm_size_t gencgc_alloc_granularity
;
384 os_vm_size_t gencgc_alloc_granularity
= GENCGC_ALLOC_GRANULARITY
;
388 * miscellaneous heap functions
391 /* Count the number of pages which are write-protected within the
392 * given generation. */
394 count_write_protect_generation_pages(generation_index_t generation
)
396 page_index_t i
, count
= 0;
398 for (i
= 0; i
< last_free_page
; i
++)
400 && (page_table
[i
].gen
== generation
)
401 && page_table
[i
].write_protected
)
406 /* Count the number of pages within the given generation. */
408 count_generation_pages(generation_index_t generation
)
411 page_index_t count
= 0;
413 for (i
= 0; i
< last_free_page
; i
++)
414 if (!page_free_p(i
) && page_table
[i
].gen
== generation
)
421 count_dont_move_pages(void)
424 page_index_t count
= 0;
425 for (i
= 0; i
< last_free_page
; i
++) {
426 if (!page_free_p(i
) && page_table
[i
].dont_move
) {
434 /* Work through the pages and add up the number of bytes used for the
435 * given generation. */
436 static __attribute__((unused
)) os_vm_size_t
437 count_generation_bytes_allocated (generation_index_t gen
)
440 os_vm_size_t result
= 0;
441 for (i
= 0; i
< last_free_page
; i
++) {
442 if (!page_free_p(i
) && page_table
[i
].gen
== gen
)
443 result
+= page_bytes_used(i
);
448 /* Return the average age of the memory in a generation. */
450 generation_average_age(generation_index_t gen
)
452 if (generations
[gen
].bytes_allocated
== 0)
456 ((double)generations
[gen
].cum_sum_bytes_allocated
)
457 / ((double)generations
[gen
].bytes_allocated
);
460 #ifdef LISP_FEATURE_X86
461 extern void fpu_save(void *);
462 extern void fpu_restore(void *);
465 #define PAGE_INDEX_FMT PRIdPTR
468 write_generation_stats(FILE *file
)
470 generation_index_t i
;
472 #ifdef LISP_FEATURE_X86
475 /* Can end up here after calling alloc_tramp which doesn't prepare
476 * the x87 state, and the C ABI uses a different mode */
480 /* Print the heap stats. */
482 " Gen StaPg UbSta LaSta Boxed Unbox LB LUB !move Alloc Waste Trig WP GCs Mem-age\n");
484 for (i
= 0; i
<= SCRATCH_GENERATION
; i
++) {
486 page_index_t boxed_cnt
= 0;
487 page_index_t unboxed_cnt
= 0;
488 page_index_t large_boxed_cnt
= 0;
489 page_index_t large_unboxed_cnt
= 0;
490 page_index_t pinned_cnt
=0;
492 for (j
= 0; j
< last_free_page
; j
++)
493 if (page_table
[j
].gen
== i
) {
495 /* Count the number of boxed pages within the given
497 if (page_boxed_p(j
)) {
498 if (page_table
[j
].large_object
)
503 if(page_table
[j
].dont_move
) pinned_cnt
++;
504 /* Count the number of unboxed pages within the given
506 if (page_unboxed_p(j
)) {
507 if (page_table
[j
].large_object
)
514 gc_assert(generations
[i
].bytes_allocated
515 == count_generation_bytes_allocated(i
));
517 " %1d: %5ld %5ld %5ld",
519 (long)generations
[i
].alloc_start_page
,
520 (long)generations
[i
].alloc_unboxed_start_page
,
521 (long)generations
[i
].alloc_large_start_page
);
523 " %5"PAGE_INDEX_FMT
" %5"PAGE_INDEX_FMT
" %5"PAGE_INDEX_FMT
524 " %5"PAGE_INDEX_FMT
" %5"PAGE_INDEX_FMT
,
525 boxed_cnt
, unboxed_cnt
, large_boxed_cnt
,
526 large_unboxed_cnt
, pinned_cnt
);
531 " %4"PAGE_INDEX_FMT
" %3d %7.4f\n",
532 generations
[i
].bytes_allocated
,
533 (npage_bytes(count_generation_pages(i
)) - generations
[i
].bytes_allocated
),
534 generations
[i
].gc_trigger
,
535 count_write_protect_generation_pages(i
),
536 generations
[i
].num_gc
,
537 generation_average_age(i
));
539 fprintf(file
," Total bytes allocated = %"OS_VM_SIZE_FMT
"\n", bytes_allocated
);
540 fprintf(file
," Dynamic-space-size bytes = %"OS_VM_SIZE_FMT
"\n", dynamic_space_size
);
542 #ifdef LISP_FEATURE_X86
543 fpu_restore(fpu_state
);
548 write_heap_exhaustion_report(FILE *file
, long available
, long requested
,
549 struct thread
*thread
)
552 "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
553 gc_active_p
? "garbage collection" : "allocation",
556 write_generation_stats(file
);
557 fprintf(file
, "GC control variables:\n");
558 fprintf(file
, " *GC-INHIBIT* = %s\n *GC-PENDING* = %s\n",
559 read_TLS(GC_INHIBIT
,thread
)==NIL
? "false" : "true",
560 (read_TLS(GC_PENDING
, thread
) == T
) ?
561 "true" : ((read_TLS(GC_PENDING
, thread
) == NIL
) ?
562 "false" : "in progress"));
563 #ifdef LISP_FEATURE_SB_THREAD
564 fprintf(file
, " *STOP-FOR-GC-PENDING* = %s\n",
565 read_TLS(STOP_FOR_GC_PENDING
,thread
)==NIL
? "false" : "true");
570 print_generation_stats(void)
572 write_generation_stats(stderr
);
575 extern char* gc_logfile
;
576 char * gc_logfile
= NULL
;
579 log_generation_stats(char *logfile
, char *header
)
582 FILE * log
= fopen(logfile
, "a");
584 fprintf(log
, "%s\n", header
);
585 write_generation_stats(log
);
588 fprintf(stderr
, "Could not open gc logfile: %s\n", logfile
);
595 report_heap_exhaustion(long available
, long requested
, struct thread
*th
)
598 FILE * log
= fopen(gc_logfile
, "a");
600 write_heap_exhaustion_report(log
, available
, requested
, th
);
603 fprintf(stderr
, "Could not open gc logfile: %s\n", gc_logfile
);
607 /* Always to stderr as well. */
608 write_heap_exhaustion_report(stderr
, available
, requested
, th
);
612 #if defined(LISP_FEATURE_X86)
613 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
616 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
617 * if zeroing it ourselves, i.e. in practice give the memory back to the
618 * OS. Generally done after a large GC.
620 void zero_pages_with_mmap(page_index_t start
, page_index_t end
) {
622 void *addr
= page_address(start
), *new_addr
;
623 os_vm_size_t length
= npage_bytes(1+end
-start
);
628 gc_assert(length
>= gencgc_release_granularity
);
629 gc_assert((length
% gencgc_release_granularity
) == 0);
631 #ifdef LISP_FEATURE_LINUX
632 // We use MADV_DONTNEED only on Linux due to differing semantics from BSD.
633 // Linux treats it as a demand that the memory be 0-filled, or refreshed
634 // from a file that backs the range. BSD takes it as a hint that you don't
635 // care if the memory has to brought in from swap when next accessed,
636 // i.e. it's not a request to make a user-visible alteration to memory.
637 // So in theory this can bring a page in from the core file, if we happen
638 // to hit a page that resides in the portion of memory mapped by coreparse.
639 // In practice this should not happen because objects from a core file can't
640 // become garbage. Except in save-lisp-and-die they can, and we must be
641 // cautious not to resurrect bytes that originally came from the file.
642 if ((os_vm_address_t
)addr
>= anon_dynamic_space_start
) {
643 if (madvise(addr
, length
, MADV_DONTNEED
) != 0)
644 lose("madvise failed\n");
648 os_invalidate(addr
, length
);
649 new_addr
= os_validate(NOT_MOVABLE
, addr
, length
);
650 if (new_addr
== NULL
|| new_addr
!= addr
) {
651 lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
656 for (i
= start
; i
<= end
; i
++)
657 set_page_need_to_zero(i
, 0);
660 /* Zero the pages from START to END (inclusive). Generally done just after
661 * a new region has been allocated.
664 zero_pages(page_index_t start
, page_index_t end
) {
668 #if defined(LISP_FEATURE_X86)
669 fast_bzero(page_address(start
), npage_bytes(1+end
-start
));
671 bzero(page_address(start
), npage_bytes(1+end
-start
));
677 zero_and_mark_pages(page_index_t start
, page_index_t end
) {
680 zero_pages(start
, end
);
681 for (i
= start
; i
<= end
; i
++)
682 set_page_need_to_zero(i
, 0);
685 /* Zero the pages from START to END (inclusive), except for those
686 * pages that are known to already zeroed. Mark all pages in the
687 * ranges as non-zeroed.
690 zero_dirty_pages(page_index_t start
, page_index_t end
) {
693 #ifdef READ_PROTECT_FREE_PAGES
694 os_protect(page_address(start
), npage_bytes(1+end
-start
), OS_VM_PROT_ALL
);
696 for (i
= start
; i
<= end
; i
++) {
697 if (!page_need_to_zero(i
)) continue;
698 for (j
= i
+1; (j
<= end
) && page_need_to_zero(j
) ; j
++)
704 for (i
= start
; i
<= end
; i
++) {
705 set_page_need_to_zero(i
, 1);
711 * To support quick and inline allocation, regions of memory can be
712 * allocated and then allocated from with just a free pointer and a
713 * check against an end address.
715 * Since objects can be allocated to spaces with different properties
716 * e.g. boxed/unboxed, generation, ages; there may need to be many
717 * allocation regions.
719 * Each allocation region may start within a partly used page. Many
720 * features of memory use are noted on a page wise basis, e.g. the
721 * generation; so if a region starts within an existing allocated page
722 * it must be consistent with this page.
724 * During the scavenging of the newspace, objects will be transported
725 * into an allocation region, and pointers updated to point to this
726 * allocation region. It is possible that these pointers will be
727 * scavenged again before the allocation region is closed, e.g. due to
728 * trans_list which jumps all over the place to cleanup the list. It
729 * is important to be able to determine properties of all objects
730 * pointed to when scavenging, e.g to detect pointers to the oldspace.
731 * Thus it's important that the allocation regions have the correct
732 * properties set when allocated, and not just set when closed. The
733 * region allocation routines return regions with the specified
734 * properties, and grab all the pages, setting their properties
735 * appropriately, except that the amount used is not known.
737 * These regions are used to support quicker allocation using just a
738 * free pointer. The actual space used by the region is not reflected
739 * in the pages tables until it is closed. It can't be scavenged until
742 * When finished with the region it should be closed, which will
743 * update the page tables for the actual space used returning unused
744 * space. Further it may be noted in the new regions which is
745 * necessary when scavenging the newspace.
747 * Large objects may be allocated directly without an allocation
748 * region, the page tables are updated immediately.
750 * Unboxed objects don't contain pointers to other objects and so
751 * don't need scavenging. Further they can't contain pointers to
752 * younger generations so WP is not needed. By allocating pages to
753 * unboxed objects the whole page never needs scavenging or
754 * write-protecting. */
756 /* We use either two or three regions for the current newspace generation. */
757 #ifdef LISP_FEATURE_SEGREGATED_CODE
758 struct alloc_region gc_alloc_regions
[3];
759 #define boxed_region gc_alloc_regions[BOXED_PAGE_FLAG-1]
760 #define unboxed_region gc_alloc_regions[UNBOXED_PAGE_FLAG-1]
761 #define code_region gc_alloc_regions[CODE_PAGE_FLAG-1]
763 struct alloc_region boxed_region
;
764 struct alloc_region unboxed_region
;
767 /* The generation currently being allocated to. */
768 static generation_index_t gc_alloc_generation
;
770 static inline page_index_t
771 generation_alloc_start_page(generation_index_t generation
, int page_type_flag
, int large
)
773 if (!(page_type_flag
>= 1 && page_type_flag
<= 3))
774 lose("bad page_type_flag: %d", page_type_flag
);
776 return generations
[generation
].alloc_large_start_page
;
777 #ifdef LISP_FEATURE_SEGREGATED_CODE
778 return generations
[generation
].alloc_start_page_
[page_type_flag
];
780 if (UNBOXED_PAGE_FLAG
== page_type_flag
)
781 return generations
[generation
].alloc_unboxed_start_page
;
782 /* Both code and data. */
783 return generations
[generation
].alloc_start_page
;
788 set_generation_alloc_start_page(generation_index_t generation
, int page_type_flag
, int large
,
791 if (!(page_type_flag
>= 1 && page_type_flag
<= 3))
792 lose("bad page_type_flag: %d", page_type_flag
);
794 generations
[generation
].alloc_large_start_page
= page
;
795 #ifdef LISP_FEATURE_SEGREGATED_CODE
797 generations
[generation
].alloc_start_page_
[page_type_flag
] = page
;
799 else if (UNBOXED_PAGE_FLAG
== page_type_flag
)
800 generations
[generation
].alloc_unboxed_start_page
= page
;
801 else /* Both code and data. */
802 generations
[generation
].alloc_start_page
= page
;
806 /* Find a new region with room for at least the given number of bytes.
808 * It starts looking at the current generation's alloc_start_page. So
809 * may pick up from the previous region if there is enough space. This
810 * keeps the allocation contiguous when scavenging the newspace.
812 * The alloc_region should have been closed by a call to
813 * gc_alloc_update_page_tables(), and will thus be in an empty state.
815 * To assist the scavenging functions write-protected pages are not
816 * used. Free pages should not be write-protected.
818 * It is critical to the conservative GC that the start of regions be
819 * known. To help achieve this only small regions are allocated at a
822 * During scavenging, pointers may be found to within the current
823 * region and the page generation must be set so that pointers to the
824 * from space can be recognized. Therefore the generation of pages in
825 * the region are set to gc_alloc_generation. To prevent another
826 * allocation call using the same pages, all the pages in the region
827 * are allocated, although they will initially be empty.
830 gc_alloc_new_region(sword_t nbytes
, int page_type_flag
, struct alloc_region
*alloc_region
)
832 page_index_t first_page
;
833 page_index_t last_page
;
839 "/alloc_new_region for %d bytes from gen %d\n",
840 nbytes, gc_alloc_generation));
843 /* Check that the region is in a reset state. */
844 gc_assert((alloc_region
->first_page
== 0)
845 && (alloc_region
->last_page
== -1)
846 && (alloc_region
->free_pointer
== alloc_region
->end_addr
));
847 ret
= thread_mutex_lock(&free_pages_lock
);
849 first_page
= generation_alloc_start_page(gc_alloc_generation
, page_type_flag
, 0);
850 last_page
=gc_find_freeish_pages(&first_page
, nbytes
, page_type_flag
);
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_address(first_page
) + page_bytes_used(first_page
);
856 alloc_region
->free_pointer
= alloc_region
->start_addr
;
857 alloc_region
->end_addr
= page_address(last_page
+1);
859 /* Set up the pages. */
861 /* The first page may have already been in use. */
862 /* If so, just assert that it's consistent, otherwise, set it up. */
863 if (page_bytes_used(first_page
)) {
864 gc_assert(page_table
[first_page
].allocated
== page_type_flag
);
865 gc_assert(page_table
[first_page
].gen
== gc_alloc_generation
);
866 gc_assert(page_table
[first_page
].large_object
== 0);
868 page_table
[first_page
].allocated
= page_type_flag
;
869 page_table
[first_page
].gen
= gc_alloc_generation
;
870 page_table
[first_page
].large_object
= 0;
871 set_page_scan_start_offset(first_page
, 0);
873 page_table
[first_page
].allocated
|= OPEN_REGION_PAGE_FLAG
;
875 for (i
= first_page
+1; i
<= last_page
; i
++) {
876 page_table
[i
].allocated
= page_type_flag
;
877 page_table
[i
].gen
= gc_alloc_generation
;
878 page_table
[i
].large_object
= 0;
879 /* This may not be necessary for unboxed regions (think it was
881 set_page_scan_start_offset(i
,
882 addr_diff(page_address(i
), alloc_region
->start_addr
));
883 page_table
[i
].allocated
|= OPEN_REGION_PAGE_FLAG
;
885 /* Bump up last_free_page. */
886 if (last_page
+1 > last_free_page
) {
887 last_free_page
= last_page
+1;
888 /* do we only want to call this on special occasions? like for
890 set_alloc_pointer((lispobj
)page_address(last_free_page
));
892 ret
= thread_mutex_unlock(&free_pages_lock
);
895 /* If the first page was only partial, don't check whether it's
896 * zeroed (it won't be) and don't zero it (since the parts that
897 * we're interested in are guaranteed to be zeroed).
899 if (page_bytes_used(first_page
)) {
903 zero_dirty_pages(first_page
, last_page
);
905 /* we can do this after releasing free_pages_lock */
906 if (gencgc_zero_check
) {
908 for (p
= alloc_region
->start_addr
;
909 (void*)p
< alloc_region
->end_addr
; p
++) {
911 lose("The new region is not zero at %p (start=%p, end=%p).\n",
912 p
, alloc_region
->start_addr
, alloc_region
->end_addr
);
918 /* If the record_new_objects flag is 2 then all new regions created
921 * If it's 1 then then it is only recorded if the first page of the
922 * current region is <= new_areas_ignore_page. This helps avoid
923 * unnecessary recording when doing full scavenge pass.
925 * The new_object structure holds the page, byte offset, and size of
926 * new regions of objects. Each new area is placed in the array of
927 * these structures pointer to by new_areas. new_areas_index holds the
928 * offset into new_areas.
930 * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
931 * later code must detect this and handle it, probably by doing a full
932 * scavenge of a generation. */
933 #define NUM_NEW_AREAS 512
934 static int record_new_objects
= 0;
935 static page_index_t new_areas_ignore_page
;
941 static struct new_area (*new_areas
)[];
942 static size_t new_areas_index
;
943 size_t max_new_areas
;
945 /* Add a new area to new_areas. */
947 add_new_area(page_index_t first_page
, size_t offset
, size_t size
)
949 size_t new_area_start
, c
;
952 /* Ignore if full. */
953 if (new_areas_index
>= NUM_NEW_AREAS
)
956 switch (record_new_objects
) {
960 if (first_page
> new_areas_ignore_page
)
969 new_area_start
= npage_bytes(first_page
) + offset
;
971 /* Search backwards for a prior area that this follows from. If
972 found this will save adding a new area. */
973 for (i
= new_areas_index
-1, c
= 0; (i
>= 0) && (c
< 8); i
--, c
++) {
975 npage_bytes((*new_areas
)[i
].page
)
976 + (*new_areas
)[i
].offset
977 + (*new_areas
)[i
].size
;
979 "/add_new_area S1 %d %d %d %d\n",
980 i, c, new_area_start, area_end));*/
981 if (new_area_start
== area_end
) {
983 "/adding to [%d] %d %d %d with %d %d %d:\n",
985 (*new_areas)[i].page,
986 (*new_areas)[i].offset,
987 (*new_areas)[i].size,
991 (*new_areas
)[i
].size
+= size
;
996 (*new_areas
)[new_areas_index
].page
= first_page
;
997 (*new_areas
)[new_areas_index
].offset
= offset
;
998 (*new_areas
)[new_areas_index
].size
= size
;
1000 "/new_area %d page %d offset %d size %d\n",
1001 new_areas_index, first_page, offset, size));*/
1004 /* Note the max new_areas used. */
1005 if (new_areas_index
> max_new_areas
)
1006 max_new_areas
= new_areas_index
;
1009 /* Update the tables for the alloc_region. The region may be added to
1012 * When done the alloc_region is set up so that the next quick alloc
1013 * will fail safely and thus a new region will be allocated. Further
1014 * it is safe to try to re-update the page table of this reset
1017 gc_alloc_update_page_tables(int page_type_flag
, struct alloc_region
*alloc_region
)
1020 page_index_t first_page
;
1021 page_index_t next_page
;
1022 os_vm_size_t bytes_used
;
1023 os_vm_size_t region_size
;
1024 os_vm_size_t byte_cnt
;
1025 page_bytes_t orig_first_page_bytes_used
;
1029 first_page
= alloc_region
->first_page
;
1031 /* Catch an unused alloc_region. */
1032 if ((first_page
== 0) && (alloc_region
->last_page
== -1))
1035 next_page
= first_page
+1;
1037 ret
= thread_mutex_lock(&free_pages_lock
);
1038 gc_assert(ret
== 0);
1039 if (alloc_region
->free_pointer
!= alloc_region
->start_addr
) {
1040 /* some bytes were allocated in the region */
1041 orig_first_page_bytes_used
= page_bytes_used(first_page
);
1043 gc_assert(alloc_region
->start_addr
==
1044 (page_address(first_page
) + page_bytes_used(first_page
)));
1046 /* All the pages used need to be updated */
1048 /* Update the first page. */
1050 /* If the page was free then set up the gen, and
1051 * scan_start_offset. */
1052 if (page_bytes_used(first_page
) == 0)
1053 gc_assert(page_starts_contiguous_block_p(first_page
));
1054 page_table
[first_page
].allocated
&= ~(OPEN_REGION_PAGE_FLAG
);
1056 #ifdef LISP_FEATURE_SEGREGATED_CODE
1057 gc_assert(page_table
[first_page
].allocated
== page_type_flag
);
1059 gc_assert(page_table
[first_page
].allocated
& page_type_flag
);
1061 gc_assert(page_table
[first_page
].gen
== gc_alloc_generation
);
1062 gc_assert(page_table
[first_page
].large_object
== 0);
1066 /* Calculate the number of bytes used in this page. This is not
1067 * always the number of new bytes, unless it was free. */
1069 if ((bytes_used
= addr_diff(alloc_region
->free_pointer
,
1070 page_address(first_page
)))
1071 >GENCGC_CARD_BYTES
) {
1072 bytes_used
= GENCGC_CARD_BYTES
;
1075 set_page_bytes_used(first_page
, bytes_used
);
1076 byte_cnt
+= bytes_used
;
1079 /* All the rest of the pages should be free. We need to set
1080 * their scan_start_offset pointer to the start of the
1081 * region, and set the bytes_used. */
1083 page_table
[next_page
].allocated
&= ~(OPEN_REGION_PAGE_FLAG
);
1084 #ifdef LISP_FEATURE_SEGREGATED_CODE
1085 gc_assert(page_table
[next_page
].allocated
== page_type_flag
);
1087 gc_assert(page_table
[next_page
].allocated
& page_type_flag
);
1089 gc_assert(page_bytes_used(next_page
) == 0);
1090 gc_assert(page_table
[next_page
].gen
== gc_alloc_generation
);
1091 gc_assert(page_table
[next_page
].large_object
== 0);
1092 gc_assert(page_scan_start_offset(next_page
) ==
1093 addr_diff(page_address(next_page
),
1094 alloc_region
->start_addr
));
1096 /* Calculate the number of bytes used in this page. */
1098 if ((bytes_used
= addr_diff(alloc_region
->free_pointer
,
1099 page_address(next_page
)))>GENCGC_CARD_BYTES
) {
1100 bytes_used
= GENCGC_CARD_BYTES
;
1103 set_page_bytes_used(next_page
, bytes_used
);
1104 byte_cnt
+= bytes_used
;
1109 region_size
= addr_diff(alloc_region
->free_pointer
,
1110 alloc_region
->start_addr
);
1111 bytes_allocated
+= region_size
;
1112 generations
[gc_alloc_generation
].bytes_allocated
+= region_size
;
1114 gc_assert((byte_cnt
- orig_first_page_bytes_used
) == region_size
);
1116 /* Set the generations alloc restart page to the last page of
1118 set_generation_alloc_start_page(gc_alloc_generation
, page_type_flag
, 0, next_page
-1);
1120 /* Add the region to the new_areas if requested. */
1121 if (BOXED_PAGE_FLAG
& page_type_flag
)
1122 add_new_area(first_page
,orig_first_page_bytes_used
, region_size
);
1126 "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1128 gc_alloc_generation));
1131 /* There are no bytes allocated. Unallocate the first_page if
1132 * there are 0 bytes_used. */
1133 page_table
[first_page
].allocated
&= ~(OPEN_REGION_PAGE_FLAG
);
1134 if (page_bytes_used(first_page
) == 0)
1135 reset_page_flags(first_page
);
1138 /* Unallocate any unused pages. */
1139 while (next_page
<= alloc_region
->last_page
) {
1140 gc_assert(page_bytes_used(next_page
) == 0);
1141 reset_page_flags(next_page
);
1144 ret
= thread_mutex_unlock(&free_pages_lock
);
1145 gc_assert(ret
== 0);
1147 /* alloc_region is per-thread, we're ok to do this unlocked */
1148 gc_set_region_empty(alloc_region
);
1151 /* Allocate a possibly large object. */
1153 gc_alloc_large(sword_t nbytes
, int page_type_flag
, struct alloc_region
*alloc_region
)
1156 page_index_t first_page
, next_page
, last_page
;
1157 os_vm_size_t byte_cnt
;
1158 os_vm_size_t bytes_used
;
1161 ret
= thread_mutex_lock(&free_pages_lock
);
1162 gc_assert(ret
== 0);
1164 first_page
= generation_alloc_start_page(gc_alloc_generation
, page_type_flag
, 1);
1165 // FIXME: really we want to try looking for space following the highest of
1166 // the last page of all other small object regions. That's impossible - there's
1167 // not enough information. At best we can skip some work in only the case where
1168 // the supplied region was the one most recently created. To do this right
1169 // would entail a malloc-like allocator at the page granularity.
1170 if (first_page
<= alloc_region
->last_page
) {
1171 first_page
= alloc_region
->last_page
+1;
1174 last_page
=gc_find_freeish_pages(&first_page
,nbytes
, page_type_flag
);
1176 gc_assert(first_page
> alloc_region
->last_page
);
1178 set_generation_alloc_start_page(gc_alloc_generation
, page_type_flag
, 1, last_page
);
1180 /* Large objects don't share pages with other objects. */
1181 gc_assert(page_bytes_used(first_page
) == 0);
1183 /* Set up the pages. */
1184 page_table
[first_page
].allocated
= page_type_flag
;
1185 page_table
[first_page
].gen
= gc_alloc_generation
;
1186 page_table
[first_page
].large_object
= 1;
1187 set_page_scan_start_offset(first_page
, 0);
1191 /* Calc. the number of bytes used in this page. This is not
1192 * always the number of new bytes, unless it was free. */
1194 if ((bytes_used
= nbytes
) > GENCGC_CARD_BYTES
) {
1195 bytes_used
= GENCGC_CARD_BYTES
;
1198 set_page_bytes_used(first_page
, bytes_used
);
1199 byte_cnt
+= bytes_used
;
1201 next_page
= first_page
+1;
1203 /* All the rest of the pages should be free. We need to set their
1204 * scan_start_offset pointer to the start of the region, and set
1205 * the bytes_used. */
1207 gc_assert(page_free_p(next_page
));
1208 gc_assert(page_bytes_used(next_page
) == 0);
1209 page_table
[next_page
].allocated
= page_type_flag
;
1210 page_table
[next_page
].gen
= gc_alloc_generation
;
1211 page_table
[next_page
].large_object
= 1;
1213 set_page_scan_start_offset(next_page
, npage_bytes(next_page
-first_page
));
1215 /* Calculate the number of bytes used in this page. */
1217 bytes_used
= nbytes
- byte_cnt
;
1218 if (bytes_used
> GENCGC_CARD_BYTES
) {
1219 bytes_used
= GENCGC_CARD_BYTES
;
1222 set_page_bytes_used(next_page
, bytes_used
);
1223 page_table
[next_page
].write_protected
=0;
1224 page_table
[next_page
].dont_move
=0;
1225 byte_cnt
+= bytes_used
;
1229 gc_assert(byte_cnt
== (size_t)nbytes
);
1231 bytes_allocated
+= nbytes
;
1232 generations
[gc_alloc_generation
].bytes_allocated
+= nbytes
;
1234 /* Add the region to the new_areas if requested. */
1235 if (BOXED_PAGE_FLAG
& page_type_flag
)
1236 add_new_area(first_page
, 0, nbytes
);
1238 /* Bump up last_free_page */
1239 if (last_page
+1 > last_free_page
) {
1240 last_free_page
= last_page
+1;
1241 set_alloc_pointer((lispobj
)(page_address(last_free_page
)));
1243 ret
= thread_mutex_unlock(&free_pages_lock
);
1244 gc_assert(ret
== 0);
1246 zero_dirty_pages(first_page
, last_page
);
1248 return page_address(first_page
);
1251 static page_index_t gencgc_alloc_start_page
= -1;
1254 gc_heap_exhausted_error_or_lose (sword_t available
, sword_t requested
)
1256 struct thread
*thread
= arch_os_get_current_thread();
1257 /* Write basic information before doing anything else: if we don't
1258 * call to lisp this is a must, and even if we do there is always
1259 * the danger that we bounce back here before the error has been
1260 * handled, or indeed even printed.
1262 report_heap_exhaustion(available
, requested
, thread
);
1263 if (gc_active_p
|| (available
== 0)) {
1264 /* If we are in GC, or totally out of memory there is no way
1265 * to sanely transfer control to the lisp-side of things.
1267 lose("Heap exhausted, game over.");
1270 /* FIXME: assert free_pages_lock held */
1271 (void)thread_mutex_unlock(&free_pages_lock
);
1272 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
1273 gc_assert(get_pseudo_atomic_atomic(thread
));
1274 clear_pseudo_atomic_atomic(thread
);
1275 if (get_pseudo_atomic_interrupted(thread
))
1276 do_pending_interrupt();
1278 /* Another issue is that signalling HEAP-EXHAUSTED error leads
1279 * to running user code at arbitrary places, even in a
1280 * WITHOUT-INTERRUPTS which may lead to a deadlock without
1281 * running out of the heap. So at this point all bets are
1283 if (read_TLS(INTERRUPTS_ENABLED
,thread
) == NIL
)
1284 corruption_warning_and_maybe_lose
1285 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1286 /* available and requested should be double word aligned, thus
1287 they can passed as fixnums and shifted later. */
1288 funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR
), available
, requested
);
1289 lose("HEAP-EXHAUSTED-ERROR fell through");
1294 gc_find_freeish_pages(page_index_t
*restart_page_ptr
, sword_t bytes
,
1297 page_index_t most_bytes_found_from
= 0, most_bytes_found_to
= 0;
1298 page_index_t first_page
, last_page
, restart_page
= *restart_page_ptr
;
1299 os_vm_size_t nbytes
= bytes
;
1300 os_vm_size_t nbytes_goal
= nbytes
;
1301 os_vm_size_t bytes_found
= 0;
1302 os_vm_size_t most_bytes_found
= 0;
1303 boolean small_object
= nbytes
< GENCGC_CARD_BYTES
;
1304 /* FIXME: assert(free_pages_lock is held); */
1306 if (nbytes_goal
< gencgc_alloc_granularity
)
1307 nbytes_goal
= gencgc_alloc_granularity
;
1309 /* Toggled by gc_and_save for heap compaction, normally -1. */
1310 if (gencgc_alloc_start_page
!= -1) {
1311 restart_page
= gencgc_alloc_start_page
;
1314 /* FIXME: This is on bytes instead of nbytes pending cleanup of
1315 * long from the interface. */
1316 gc_assert(bytes
>=0);
1317 /* Search for a page with at least nbytes of space. We prefer
1318 * not to split small objects on multiple pages, to reduce the
1319 * number of contiguous allocation regions spaning multiple
1320 * pages: this helps avoid excessive conservativism.
1322 * For other objects, we guarantee that they start on their own
1325 first_page
= restart_page
;
1326 while (first_page
< page_table_pages
) {
1328 if (page_free_p(first_page
)) {
1329 gc_assert(0 == page_bytes_used(first_page
));
1330 bytes_found
= GENCGC_CARD_BYTES
;
1331 } else if (small_object
&&
1332 (page_table
[first_page
].allocated
== page_type_flag
) &&
1333 (!page_table
[first_page
].large_object
) &&
1334 (page_table
[first_page
].gen
== gc_alloc_generation
) &&
1335 (!page_table
[first_page
].write_protected
) &&
1336 (!page_table
[first_page
].dont_move
)) {
1337 bytes_found
= GENCGC_CARD_BYTES
- page_bytes_used(first_page
);
1338 if (bytes_found
< nbytes
) {
1339 if (bytes_found
> most_bytes_found
)
1340 most_bytes_found
= bytes_found
;
1349 gc_assert(!page_table
[first_page
].write_protected
);
1350 for (last_page
= first_page
+1;
1351 ((last_page
< page_table_pages
) &&
1352 page_free_p(last_page
) &&
1353 (bytes_found
< nbytes_goal
));
1355 bytes_found
+= GENCGC_CARD_BYTES
;
1356 gc_assert(0 == page_bytes_used(last_page
));
1357 gc_assert(!page_table
[last_page
].write_protected
);
1360 if (bytes_found
> most_bytes_found
) {
1361 most_bytes_found
= bytes_found
;
1362 most_bytes_found_from
= first_page
;
1363 most_bytes_found_to
= last_page
;
1365 if (bytes_found
>= nbytes_goal
)
1368 first_page
= last_page
;
1371 bytes_found
= most_bytes_found
;
1372 restart_page
= first_page
+ 1;
1374 /* Check for a failure */
1375 if (bytes_found
< nbytes
) {
1376 gc_assert(restart_page
>= page_table_pages
);
1377 gc_heap_exhausted_error_or_lose(most_bytes_found
, nbytes
);
1380 gc_assert(most_bytes_found_to
);
1381 *restart_page_ptr
= most_bytes_found_from
;
1382 return most_bytes_found_to
-1;
1385 /* Allocate bytes. All the rest of the special-purpose allocation
1386 * functions will eventually call this */
1389 gc_alloc_with_region(sword_t nbytes
,int page_type_flag
, struct alloc_region
*my_region
,
1392 void *new_free_pointer
;
1394 if (nbytes
>=LARGE_OBJECT_SIZE
)
1395 return gc_alloc_large(nbytes
, page_type_flag
, my_region
);
1397 /* Check whether there is room in the current alloc region. */
1398 new_free_pointer
= (char*)my_region
->free_pointer
+ nbytes
;
1400 /* fprintf(stderr, "alloc %d bytes from %p to %p\n", nbytes,
1401 my_region->free_pointer, new_free_pointer); */
1403 if (new_free_pointer
<= my_region
->end_addr
) {
1404 /* If so then allocate from the current alloc region. */
1405 void *new_obj
= my_region
->free_pointer
;
1406 my_region
->free_pointer
= new_free_pointer
;
1408 /* Unless a `quick' alloc was requested, check whether the
1409 alloc region is almost empty. */
1411 addr_diff(my_region
->end_addr
,my_region
->free_pointer
) <= 32) {
1412 /* If so, finished with the current region. */
1413 gc_alloc_update_page_tables(page_type_flag
, my_region
);
1414 /* Set up a new region. */
1415 gc_alloc_new_region(32 /*bytes*/, page_type_flag
, my_region
);
1418 return((void *)new_obj
);
1421 /* Else not enough free space in the current region: retry with a
1424 gc_alloc_update_page_tables(page_type_flag
, my_region
);
1425 gc_alloc_new_region(nbytes
, page_type_flag
, my_region
);
1426 return gc_alloc_with_region(nbytes
, page_type_flag
, my_region
,0);
1429 /* Copy a large object. If the object is in a large object region then
1430 * it is simply promoted, else it is copied. If it's large enough then
1431 * it's copied to a large object region.
1433 * Bignums and vectors may have shrunk. If the object is not copied
1434 * the space needs to be reclaimed, and the page_tables corrected. */
1436 general_copy_large_object(lispobj object
, sword_t nwords
, boolean boxedp
)
1439 page_index_t first_page
;
1441 CHECK_COPY_PRECONDITIONS(object
, nwords
);
1443 if ((nwords
> 1024*1024) && gencgc_verbose
) {
1444 FSHOW((stderr
, "/general_copy_large_object: %d bytes\n",
1445 nwords
*N_WORD_BYTES
));
1448 /* Check whether it's a large object. */
1449 first_page
= find_page_index((void *)object
);
1450 gc_assert(first_page
>= 0);
1452 if (page_table
[first_page
].large_object
) {
1453 /* Promote the object. Note: Unboxed objects may have been
1454 * allocated to a BOXED region so it may be necessary to
1455 * change the region to UNBOXED. */
1456 os_vm_size_t remaining_bytes
;
1457 os_vm_size_t bytes_freed
;
1458 page_index_t next_page
;
1459 page_bytes_t old_bytes_used
;
1461 /* FIXME: This comment is somewhat stale.
1463 * Note: Any page write-protection must be removed, else a
1464 * later scavenge_newspace may incorrectly not scavenge these
1465 * pages. This would not be necessary if they are added to the
1466 * new areas, but let's do it for them all (they'll probably
1467 * be written anyway?). */
1469 gc_assert(page_starts_contiguous_block_p(first_page
));
1470 next_page
= first_page
;
1471 remaining_bytes
= nwords
*N_WORD_BYTES
;
1473 /* FIXME: can we share code with maybe_adjust_large_object ? */
1474 while (remaining_bytes
> GENCGC_CARD_BYTES
) {
1475 gc_assert(page_table
[next_page
].gen
== from_space
);
1476 gc_assert(page_table
[next_page
].large_object
);
1477 gc_assert(page_scan_start_offset(next_page
) ==
1478 npage_bytes(next_page
-first_page
));
1479 gc_assert(page_bytes_used(next_page
) == GENCGC_CARD_BYTES
);
1480 /* Should have been unprotected by unprotect_oldspace()
1481 * for boxed objects, and after promotion unboxed ones
1482 * should not be on protected pages at all. */
1483 gc_assert(!page_table
[next_page
].write_protected
);
1486 gc_assert(page_boxed_p(next_page
));
1488 gc_assert(page_allocated_no_region_p(next_page
));
1489 page_table
[next_page
].allocated
= UNBOXED_PAGE_FLAG
;
1491 page_table
[next_page
].gen
= new_space
;
1493 remaining_bytes
-= GENCGC_CARD_BYTES
;
1497 /* Now only one page remains, but the object may have shrunk so
1498 * there may be more unused pages which will be freed. */
1500 /* Object may have shrunk but shouldn't have grown - check. */
1501 gc_assert(page_bytes_used(next_page
) >= remaining_bytes
);
1503 page_table
[next_page
].gen
= new_space
;
1506 gc_assert(page_boxed_p(next_page
));
1508 page_table
[next_page
].allocated
= UNBOXED_PAGE_FLAG
;
1510 /* Adjust the bytes_used. */
1511 old_bytes_used
= page_bytes_used(next_page
);
1512 set_page_bytes_used(next_page
, remaining_bytes
);
1514 bytes_freed
= old_bytes_used
- remaining_bytes
;
1516 /* Free any remaining pages; needs care. */
1518 while ((old_bytes_used
== GENCGC_CARD_BYTES
) &&
1519 (page_table
[next_page
].gen
== from_space
) &&
1520 /* FIXME: It is not obvious to me why this is necessary
1521 * as a loop condition: it seems to me that the
1522 * scan_start_offset test should be sufficient, but
1523 * experimentally that is not the case. --NS
1526 page_boxed_p(next_page
) :
1527 page_allocated_no_region_p(next_page
)) &&
1528 page_table
[next_page
].large_object
&&
1529 (page_scan_start_offset(next_page
) ==
1530 npage_bytes(next_page
- first_page
))) {
1531 /* Checks out OK, free the page. Don't need to both zeroing
1532 * pages as this should have been done before shrinking the
1533 * object. These pages shouldn't be write-protected, even if
1534 * boxed they should be zero filled. */
1535 gc_assert(!page_table
[next_page
].write_protected
);
1537 old_bytes_used
= page_bytes_used(next_page
);
1538 reset_page_flags(next_page
);
1539 set_page_bytes_used(next_page
, 0);
1540 bytes_freed
+= old_bytes_used
;
1544 if ((bytes_freed
> 0) && gencgc_verbose
) {
1546 "/general_copy_large_object bytes_freed=%"OS_VM_SIZE_FMT
"\n",
1550 generations
[from_space
].bytes_allocated
-= nwords
*N_WORD_BYTES
1552 generations
[new_space
].bytes_allocated
+= nwords
*N_WORD_BYTES
;
1553 bytes_allocated
-= bytes_freed
;
1555 /* Add the region to the new_areas if requested. */
1557 add_new_area(first_page
,0,nwords
*N_WORD_BYTES
);
1562 /* Allocate space. */
1563 new = gc_general_alloc(nwords
*N_WORD_BYTES
,
1564 (boxedp
? BOXED_PAGE_FLAG
: UNBOXED_PAGE_FLAG
),
1567 /* Copy the object. */
1568 memcpy(new,native_pointer(object
),nwords
*N_WORD_BYTES
);
1570 /* Return Lisp pointer of new object. */
1571 return make_lispobj(new, lowtag_of(object
));
1576 copy_large_object(lispobj object
, sword_t nwords
)
1578 return general_copy_large_object(object
, nwords
, 1);
1582 copy_large_unboxed_object(lispobj object
, sword_t nwords
)
1584 return general_copy_large_object(object
, nwords
, 0);
1587 /* to copy unboxed objects */
1589 copy_unboxed_object(lispobj object
, sword_t nwords
)
1591 return gc_general_copy_object(object
, nwords
, UNBOXED_PAGE_FLAG
);
1598 /* XX This is a hack adapted from cgc.c. These don't work too
1599 * efficiently with the gencgc as a list of the weak pointers is
1600 * maintained within the objects which causes writes to the pages. A
1601 * limited attempt is made to avoid unnecessary writes, but this needs
1603 /* FIXME: now that we have non-Lisp hashtables in the GC, it might make sense
1604 * to stop chaining weak pointers through a slot in the object, as a remedy to
1605 * the above concern. It would also shorten the object by 2 words. */
1607 scav_weak_pointer(lispobj
*where
, lispobj object
)
1609 struct weak_pointer
* wp
= (struct weak_pointer
*)where
;
1611 if (!wp
->next
&& weak_pointer_breakable_p(wp
))
1612 add_to_weak_pointer_list(wp
);
1614 /* Do not let GC scavenge the value slot of the weak pointer.
1615 * (That is why it is a weak pointer.) */
1617 return WEAK_POINTER_NWORDS
;
1622 search_read_only_space(void *pointer
)
1624 lispobj
*start
= (lispobj
*) READ_ONLY_SPACE_START
;
1625 lispobj
*end
= read_only_space_free_pointer
;
1626 if ((pointer
< (void *)start
) || (pointer
>= (void *)end
))
1628 return gc_search_space(start
, pointer
);
1632 search_static_space(void *pointer
)
1634 lispobj
*start
= (lispobj
*)STATIC_SPACE_START
;
1635 lispobj
*end
= static_space_free_pointer
;
1636 if ((pointer
< (void *)start
) || (pointer
>= (void *)end
))
1638 return gc_search_space(start
, pointer
);
1641 /* a faster version for searching the dynamic space. This will work even
1642 * if the object is in a current allocation region. */
1644 search_dynamic_space(void *pointer
)
1646 page_index_t page_index
= find_page_index(pointer
);
1649 /* The address may be invalid, so do some checks. */
1650 if ((page_index
== -1) || page_free_p(page_index
))
1652 start
= (lispobj
*)page_scan_start(page_index
);
1653 return gc_search_space(start
, pointer
);
1656 #if !GENCGC_IS_PRECISE
1657 // Return the starting address of the object containing 'addr'
1658 // if and only if the object is one which would be evacuated from 'from_space'
1659 // were it allowed to be either discarded as garbage or moved.
1660 // 'addr_page_index' is the page containing 'addr' and must not be -1.
1661 // Return 0 if there is no such object - that is, if addr is past the
1662 // end of the used bytes, or its pages are not in 'from_space' etc.
1664 conservative_root_p(void *addr
, page_index_t addr_page_index
)
1666 /* quick check 1: Address is quite likely to have been invalid. */
1667 struct page
* page
= &page_table
[addr_page_index
];
1668 if (((uword_t
)addr
& (GENCGC_CARD_BYTES
- 1)) > page_bytes_used(addr_page_index
) ||
1669 #ifdef LISP_FEATURE_SEGREGATED_CODE
1670 (!is_lisp_pointer((lispobj
)addr
) && page
->allocated
!= CODE_PAGE_FLAG
) ||
1672 (compacting_p() && (page
->gen
!= from_space
||
1673 (page
->large_object
&& page
->dont_move
))))
1675 gc_assert(!(page
->allocated
& OPEN_REGION_PAGE_FLAG
));
1677 #ifdef LISP_FEATURE_SEGREGATED_CODE
1678 /* quick check 2: Unless the page can hold code, the pointer's lowtag must
1679 * correspond to the widetag of the object. The object header can safely
1680 * be read even if it turns out that the pointer is not valid,
1681 * because the pointer was in bounds for the page.
1682 * Note that this can falsely pass if looking at the interior of an unboxed
1683 * array that masquerades as a Lisp object header by pure luck.
1684 * But if this doesn't pass, there's no point in proceeding to the
1685 * definitive test which involves searching for the containing object. */
1687 if (page
->allocated
!= CODE_PAGE_FLAG
) {
1688 lispobj
* obj
= native_pointer((lispobj
)addr
);
1689 if (lowtag_of((lispobj
)addr
) == LIST_POINTER_LOWTAG
) {
1690 if (!is_cons_half(obj
[0]) || !is_cons_half(obj
[1]))
1693 unsigned char widetag
= widetag_of(*obj
);
1694 if (!other_immediate_lowtag_p(widetag
) ||
1695 lowtag_of((lispobj
)addr
) != lowtag_for_widetag
[widetag
>>2])
1701 /* Filter out anything which can't be a pointer to a Lisp object
1702 * (or, as a special case which also requires dont_move, a return
1703 * address referring to something in a CodeObject). This is
1704 * expensive but important, since it vastly reduces the
1705 * probability that random garbage will be bogusly interpreted as
1706 * a pointer which prevents a page from moving. */
1707 lispobj
* object_start
= search_dynamic_space(addr
);
1708 if (!object_start
) return 0;
1710 /* If the containing object is a code object and 'addr' points
1711 * anywhere beyond the boxed words,
1712 * presume it to be a valid unboxed return address. */
1713 if (instruction_ptr_p(addr
, object_start
))
1714 return object_start
;
1716 /* Large object pages only contain ONE object, and it will never
1717 * be a CONS. However, arrays and bignums can be allocated larger
1718 * than necessary and then shrunk to fit, leaving what look like
1719 * (0 . 0) CONSes at the end. These appear valid to
1720 * properly_tagged_descriptor_p(), so pick them off here. */
1721 if (((lowtag_of((lispobj
)addr
) == LIST_POINTER_LOWTAG
) &&
1722 page_table
[addr_page_index
].large_object
)
1723 || !properly_tagged_descriptor_p(addr
, object_start
))
1726 return object_start
;
1730 /* Adjust large bignum and vector objects. This will adjust the
1731 * allocated region if the size has shrunk, and move unboxed objects
1732 * into unboxed pages. The pages are not promoted here, and the
1733 * promoted region is not added to the new_regions; this is really
1734 * only designed to be called from preserve_pointer(). Shouldn't fail
1735 * if this is missed, just may delay the moving of objects to unboxed
1736 * pages, and the freeing of pages. */
1738 maybe_adjust_large_object(page_index_t first_page
)
1740 lispobj
* where
= (lispobj
*)page_address(first_page
);
1741 page_index_t next_page
;
1743 uword_t remaining_bytes
;
1744 uword_t bytes_freed
;
1745 uword_t old_bytes_used
;
1749 /* Check whether it's a vector or bignum object. */
1750 lispobj widetag
= widetag_of(where
[0]);
1751 if (widetag
== SIMPLE_VECTOR_WIDETAG
)
1752 page_type_flag
= BOXED_PAGE_FLAG
;
1753 else if (specialized_vector_widetag_p(widetag
) || widetag
== BIGNUM_WIDETAG
)
1754 page_type_flag
= UNBOXED_PAGE_FLAG
;
1758 /* Find its current size. */
1759 sword_t nwords
= sizetab
[widetag
](where
);
1761 /* Note: Any page write-protection must be removed, else a later
1762 * scavenge_newspace may incorrectly not scavenge these pages.
1763 * This would not be necessary if they are added to the new areas,
1764 * but lets do it for them all (they'll probably be written
1767 gc_assert(page_starts_contiguous_block_p(first_page
));
1769 next_page
= first_page
;
1770 remaining_bytes
= nwords
*N_WORD_BYTES
;
1771 while (remaining_bytes
> GENCGC_CARD_BYTES
) {
1772 gc_assert(page_table
[next_page
].gen
== from_space
);
1773 // We can't assert that page_table[next_page].allocated is correct,
1774 // because unboxed objects are initially allocated on boxed pages.
1775 gc_assert(page_allocated_no_region_p(next_page
));
1776 gc_assert(page_table
[next_page
].large_object
);
1777 gc_assert(page_scan_start_offset(next_page
) ==
1778 npage_bytes(next_page
-first_page
));
1779 gc_assert(page_bytes_used(next_page
) == GENCGC_CARD_BYTES
);
1781 // This affects only one object, since large objects don't share pages.
1782 page_table
[next_page
].allocated
= page_type_flag
;
1784 /* Shouldn't be write-protected at this stage. Essential that the
1786 gc_assert(!page_table
[next_page
].write_protected
);
1787 remaining_bytes
-= GENCGC_CARD_BYTES
;
1791 /* Now only one page remains, but the object may have shrunk so
1792 * there may be more unused pages which will be freed. */
1794 /* Object may have shrunk but shouldn't have grown - check. */
1795 gc_assert(page_bytes_used(next_page
) >= remaining_bytes
);
1797 page_table
[next_page
].allocated
= page_type_flag
;
1799 /* Adjust the bytes_used. */
1800 old_bytes_used
= page_bytes_used(next_page
);
1801 set_page_bytes_used(next_page
, remaining_bytes
);
1803 bytes_freed
= old_bytes_used
- remaining_bytes
;
1805 /* Free any remaining pages; needs care. */
1807 while ((old_bytes_used
== GENCGC_CARD_BYTES
) &&
1808 (page_table
[next_page
].gen
== from_space
) &&
1809 page_allocated_no_region_p(next_page
) &&
1810 page_table
[next_page
].large_object
&&
1811 (page_scan_start_offset(next_page
) ==
1812 npage_bytes(next_page
- first_page
))) {
1813 /* It checks out OK, free the page. We don't need to bother zeroing
1814 * pages as this should have been done before shrinking the
1815 * object. These pages shouldn't be write protected as they
1816 * should be zero filled. */
1817 gc_assert(!page_table
[next_page
].write_protected
);
1819 old_bytes_used
= page_bytes_used(next_page
);
1820 reset_page_flags(next_page
);
1821 set_page_bytes_used(next_page
, 0);
1822 bytes_freed
+= old_bytes_used
;
1826 if ((bytes_freed
> 0) && gencgc_verbose
) {
1828 "/maybe_adjust_large_object() freed %d\n",
1832 generations
[from_space
].bytes_allocated
-= bytes_freed
;
1833 bytes_allocated
-= bytes_freed
;
1838 #ifdef PIN_GRANULARITY_LISPOBJ
1839 /* After scavenging of the roots is done, we go back to the pinned objects
1840 * and look within them for pointers. While heap_scavenge() could certainly
1841 * do this, it would potentially lead to extra work, since we can't know
1842 * whether any given object has been examined at least once, since there is
1843 * no telltale forwarding-pointer. The easiest thing to do is defer all
1844 * pinned objects to a subsequent pass, as is done here.
1847 scavenge_pinned_ranges()
1851 for_each_hopscotch_key(i
, key
, pinned_objects
) {
1852 lispobj
* obj
= native_pointer(key
);
1853 lispobj header
= *obj
;
1854 // Never invoke scavenger on a simple-fun, just code components.
1855 if (is_cons_half(header
))
1857 else if (widetag_of(header
) != SIMPLE_FUN_WIDETAG
)
1858 scavtab
[widetag_of(header
)](obj
, header
);
1862 /* Create an array of fixnum to consume the space between 'from' and 'to' */
1863 static void deposit_filler(uword_t from
, uword_t to
)
1866 lispobj
* where
= (lispobj
*)from
;
1867 sword_t nwords
= (to
- from
) >> WORD_SHIFT
;
1868 where
[0] = SIMPLE_ARRAY_WORD_WIDETAG
;
1869 where
[1] = make_fixnum(nwords
- 2);
1873 /* Zero out the byte ranges on small object pages marked dont_move,
1874 * carefully skipping over objects in the pin hashtable.
1875 * TODO: by recording an additional bit per page indicating whether
1876 * there is more than one pinned object on it, we could avoid qsort()
1877 * except in the case where there is more than one. */
1879 wipe_nonpinned_words()
1881 void gc_heapsort_uwords(uword_t
*, int);
1882 // Loop over the keys in pinned_objects and pack them densely into
1883 // the same array - pinned_objects.keys[] - but skip any simple-funs.
1884 // Admittedly this is abstraction breakage.
1885 int limit
= hopscotch_max_key_index(pinned_objects
);
1887 for (i
= 0; i
<= limit
; ++i
) {
1888 lispobj key
= pinned_objects
.keys
[i
];
1890 lispobj
* obj
= native_pointer(key
);
1891 // No need to check for is_cons_half() - it will be false
1892 // on a simple-fun header, and that's the correct answer.
1893 if (widetag_of(*obj
) != SIMPLE_FUN_WIDETAG
)
1894 pinned_objects
.keys
[n_pins
++] = (uword_t
)obj
;
1897 // Store a sentinel at the end. Even if n_pins = table capacity (unlikely),
1898 // it is safe to write one more word, because the hops[] array immediately
1899 // follows the keys[] array in memory. At worst, 2 elements of hops[]
1900 // are clobbered, which is irrelevant since the table has already been
1901 // rendered unusable by stealing its key array for a different purpose.
1902 pinned_objects
.keys
[n_pins
] = 0;
1903 // Don't touch pinned_objects.count in case the reset function uses it
1904 // to decide how to resize for next use (which it doesn't, but could).
1905 gc_n_stack_pins
= n_pins
;
1906 // Order by ascending address, stopping short of the sentinel.
1907 gc_heapsort_uwords(pinned_objects
.keys
, n_pins
);
1910 printf("Sorted pin list:\n");
1911 for (i
= 0; i
< n_pins
; ++i
) {
1912 lispobj
* obj
= (lispobj
*)pinned_objects
.keys
[i
];
1913 lispobj word
= *obj
;
1914 int widetag
= widetag_of(word
);
1915 if (is_cons_half(word
))
1916 printf("%p: (cons)\n", obj
);
1918 printf("%p: %d words (%s)\n", obj
,
1919 (int)sizetab
[widetag
](obj
), widetag_names
[widetag
>>2]);
1922 // Each entry in the pinned objects demarcates two ranges to be cleared:
1923 // - the range preceding it back to either the page start, or prior object.
1924 // - the range after it, up to the lesser of page bytes used or next object.
1925 uword_t preceding_object
= 0;
1926 uword_t this_page_end
= 0;
1927 #define page_base_address(x) (x&~(GENCGC_CARD_BYTES-1))
1928 for (i
= 0; i
< n_pins
; ++i
) {
1929 // Handle the preceding range. If this object is on the same page as
1930 // its predecessor, then intervening bytes were already zeroed.
1931 // If not, then start a new page and do some bookkeeping.
1932 lispobj
* obj
= (lispobj
*)pinned_objects
.keys
[i
];
1933 uword_t this_page_base
= page_base_address((uword_t
)obj
);
1934 /* printf("i=%d obj=%p base=%p\n", i, obj, (void*)this_page_base); */
1935 if (this_page_base
> page_base_address(preceding_object
)) {
1936 deposit_filler(this_page_base
, (lispobj
)obj
);
1937 // Move the page to newspace
1938 page_index_t page
= find_page_index(obj
);
1939 int used
= page_bytes_used(page
);
1940 this_page_end
= this_page_base
+ used
;
1941 /* printf(" Clearing %p .. %p (limit=%p)\n",
1942 (void*)this_page_base, obj, (void*)this_page_end); */
1943 generations
[new_space
].bytes_allocated
+= used
;
1944 generations
[page_table
[page
].gen
].bytes_allocated
-= used
;
1945 page_table
[page
].gen
= new_space
;
1946 page_table
[page
].has_pins
= 0;
1948 // Handle the following range.
1949 lispobj word
= *obj
;
1950 size_t nwords
= OBJECT_SIZE(word
, obj
);
1951 uword_t range_start
= (uword_t
)(obj
+ nwords
);
1952 uword_t range_end
= this_page_end
;
1953 // There is always an i+1'th key due to the sentinel value.
1954 if (page_base_address(pinned_objects
.keys
[i
+1]) == this_page_base
)
1955 range_end
= pinned_objects
.keys
[i
+1];
1956 /* printf(" Clearing %p .. %p\n", (void*)range_start, (void*)range_end); */
1957 deposit_filler(range_start
, range_end
);
1958 preceding_object
= (uword_t
)obj
;
1962 /* Add 'object' to the hashtable, and if the object is a code component,
1963 * then also add all of the embedded simple-funs.
1964 * The rationale for the extra work on code components is that without it,
1965 * every test of pinned_p() on an object would have to check if the pointer
1966 * is to a simple-fun - entailing an extra read of the header - and mapping
1967 * to its code component if so. Since more calls to pinned_p occur than to
1968 * pin_object, the extra burden should be on this function.
1969 * Experimentation bears out that this is the better technique.
1970 * Also, we wouldn't often expect code components in the collected generation
1971 * so the extra work here is quite minimal, even if it can generally add to
1972 * the number of keys in the hashtable.
1975 pin_object(lispobj
* base_addr
)
1977 lispobj object
= compute_lispobj(base_addr
);
1978 if (!hopscotch_containsp(&pinned_objects
, object
)) {
1979 hopscotch_insert(&pinned_objects
, object
, 1);
1980 struct code
* maybe_code
= (struct code
*)native_pointer(object
);
1981 if (widetag_of(maybe_code
->header
) == CODE_HEADER_WIDETAG
) {
1982 for_each_simple_fun(i
, fun
, maybe_code
, 0, {
1983 hopscotch_insert(&pinned_objects
,
1984 make_lispobj(fun
, FUN_POINTER_LOWTAG
),
1991 # define scavenge_pinned_ranges()
1992 # define wipe_nonpinned_words()
1995 /* Take a possible pointer to a Lisp object and mark its page in the
1996 * page_table so that it will not be relocated during a GC.
1998 * This involves locating the page it points to, then backing up to
1999 * the start of its region, then marking all pages dont_move from there
2000 * up to the first page that's not full or has a different generation
2002 * It is assumed that all the page static flags have been cleared at
2003 * the start of a GC.
2005 * It is also assumed that the current gc_alloc() region has been
2006 * flushed and the tables updated. */
2008 // TODO: there's probably a way to be a little more efficient here.
2009 // As things are, we start by finding the object that encloses 'addr',
2010 // then we see if 'addr' was a "valid" Lisp pointer to that object
2011 // - meaning we expect the correct lowtag on the pointer - except
2012 // that for code objects we don't require a correct lowtag
2013 // and we allow a pointer to anywhere in the object.
2015 // It should be possible to avoid calling search_dynamic_space
2016 // more of the time. First, check if the page pointed to might hold code.
2017 // If it does, then we continue regardless of the pointer's lowtag
2018 // (because of the special allowance). If the page definitely does *not*
2019 // hold code, then we require up front that the lowtake make sense,
2020 // by doing the same checks that are in properly_tagged_descriptor_p.
2022 // Problem: when code is allocated from a per-thread region,
2023 // does it ensure that the occupied pages are flagged as having code?
2025 #if defined(__GNUC__) && defined(MEMORY_SANITIZER)
2026 #define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
2028 #define NO_SANITIZE_MEMORY
2031 static void NO_SANITIZE_MEMORY
2032 preserve_pointer(void *addr
)
2034 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2035 /* Immobile space MUST be lower than dynamic space,
2036 or else this test needs to be revised */
2037 if (addr
< (void*)IMMOBILE_SPACE_END
) {
2038 extern void immobile_space_preserve_pointer(void*);
2039 immobile_space_preserve_pointer(addr
);
2043 page_index_t page
= find_page_index(addr
);
2044 lispobj
*object_start
;
2046 #if GENCGC_IS_PRECISE
2047 /* If we're in precise gencgc (non-x86oid as of this writing) then
2048 * we are only called on valid object pointers in the first place,
2049 * so we just have to do a bounds-check against the heap, a
2050 * generation check, and the already-pinned check. */
2052 (compacting_p() && (page_table
[page
].gen
!= from_space
||
2053 (page_table
[page
].large_object
&&
2054 page_table
[page
].dont_move
))))
2056 object_start
= native_pointer((lispobj
)addr
);
2057 switch (widetag_of(*object_start
)) {
2058 case SIMPLE_FUN_WIDETAG
:
2059 #ifdef RETURN_PC_WIDETAG
2060 case RETURN_PC_WIDETAG
:
2062 object_start
= fun_code_header(object_start
);
2065 if (page
< 0 || (object_start
= conservative_root_p(addr
, page
)) == NULL
)
2067 if (!compacting_p()) {
2068 /* Just mark it. No distinction between large and small objects. */
2069 gc_mark_obj(compute_lispobj(object_start
));
2074 unsigned int region_allocation
= page_table
[page
].allocated
;
2076 /* Find the beginning of the region. Note that there may be
2077 * objects in the region preceding the one that we were passed a
2078 * pointer to: if this is the case, we will write-protect all the
2079 * previous objects' pages too. */
2082 /* I think this'd work just as well, but without the assertions.
2083 * -dan 2004.01.01 */
2084 page_index_t first_page
= find_page_index(page_scan_start(page
))
2086 page_index_t first_page
= page
;
2087 while (!page_starts_contiguous_block_p(first_page
)) {
2089 /* Do some checks. */
2090 gc_assert(page_bytes_used(first_page
) == GENCGC_CARD_BYTES
);
2091 gc_assert(page_table
[first_page
].gen
== from_space
);
2092 gc_assert(page_table
[first_page
].allocated
== region_allocation
);
2096 /* Adjust any large objects before promotion as they won't be
2097 * copied after promotion. */
2098 if (page_table
[first_page
].large_object
) {
2099 maybe_adjust_large_object(first_page
);
2100 /* It may have moved to unboxed pages. */
2101 region_allocation
= page_table
[first_page
].allocated
;
2104 /* Now work forward until the end of this contiguous area is found,
2105 * marking all pages as dont_move. */
2107 for (i
= first_page
; ;i
++) {
2108 gc_assert(page_table
[i
].allocated
== region_allocation
);
2110 /* Mark the page static. */
2111 page_table
[i
].dont_move
= 1;
2113 /* It is essential that the pages are not write protected as
2114 * they may have pointers into the old-space which need
2115 * scavenging. They shouldn't be write protected at this
2117 gc_assert(!page_table
[i
].write_protected
);
2119 /* Check whether this is the last page in this contiguous block.. */
2120 if (page_ends_contiguous_block_p(i
, from_space
))
2124 #ifdef PIN_GRANULARITY_LISPOBJ
2125 /* Do not do this for multi-page objects. Those pages do not need
2126 * object wipeout anyway. */
2127 if (i
== first_page
) { // single-page object
2128 pin_object(object_start
);
2129 page_table
[i
].has_pins
= 1;
2133 /* Check that the page is now static. */
2134 gc_assert(page_table
[page
].dont_move
!= 0);
2138 #define IN_REGION_P(a,kind) (kind##_region.start_addr<=a && a<=kind##_region.free_pointer)
2139 #ifdef LISP_FEATURE_SEGREGATED_CODE
2140 #define IN_BOXED_REGION_P(a) IN_REGION_P(a,boxed)||IN_REGION_P(a,code)
2142 #define IN_BOXED_REGION_P(a) IN_REGION_P(a,boxed)
2145 /* If the given page is not write-protected, then scan it for pointers
2146 * to younger generations or the top temp. generation, if no
2147 * suspicious pointers are found then the page is write-protected.
2149 * Care is taken to check for pointers to the current gc_alloc()
2150 * region if it is a younger generation or the temp. generation. This
2151 * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2152 * the gc_alloc_generation does not need to be checked as this is only
2153 * called from scavenge_generation() when the gc_alloc generation is
2154 * younger, so it just checks if there is a pointer to the current
2157 * We return 1 if the page was write-protected, else 0. */
2159 update_page_write_prot(page_index_t page
)
2161 generation_index_t gen
= page_table
[page
].gen
;
2164 void **page_addr
= (void **)page_address(page
);
2165 sword_t num_words
= page_bytes_used(page
) / N_WORD_BYTES
;
2167 /* Shouldn't be a free page. */
2168 gc_assert(!page_free_p(page
));
2169 gc_assert(page_bytes_used(page
) != 0);
2171 if (!ENABLE_PAGE_PROTECTION
) return 0;
2173 /* Skip if it's already write-protected, pinned, or unboxed */
2174 if (page_table
[page
].write_protected
2175 /* FIXME: What's the reason for not write-protecting pinned pages? */
2176 || page_table
[page
].dont_move
2177 || page_unboxed_p(page
))
2180 /* Scan the page for pointers to younger generations or the
2181 * top temp. generation. */
2183 /* This is conservative: any word satisfying is_lisp_pointer() is
2184 * assumed to be a pointer. To do otherwise would require a family
2185 * of scavenge-like functions. */
2186 for (j
= 0; j
< num_words
; j
++) {
2187 void *ptr
= *(page_addr
+j
);
2189 lispobj
__attribute__((unused
)) header
;
2191 if (!is_lisp_pointer((lispobj
)ptr
))
2193 /* Check that it's in the dynamic space */
2194 if ((index
= find_page_index(ptr
)) != -1) {
2195 if (/* Does it point to a younger or the temp. generation? */
2196 ((page_bytes_used(index
) != 0)
2197 && ((page_table
[index
].gen
< gen
)
2198 || (page_table
[index
].gen
== SCRATCH_GENERATION
)))
2200 /* Or does it point within a current gc_alloc() region? */
2201 || (IN_BOXED_REGION_P(ptr
) || IN_REGION_P(ptr
,unboxed
))) {
2206 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2207 else if ((index
= find_immobile_page_index(ptr
)) >= 0 &&
2208 other_immediate_lowtag_p(header
= *native_pointer((lispobj
)ptr
))) {
2209 // This is *possibly* a pointer to an object in immobile space,
2210 // given that above two conditions were satisfied.
2211 // But unlike in the dynamic space case, we need to read a byte
2212 // from the object to determine its generation, which requires care.
2213 // Consider an unboxed word that looks like a pointer to a word that
2214 // looks like fun-header-widetag. We can't naively back up to the
2215 // underlying code object since the alleged header might not be one.
2216 int obj_gen
= gen
; // Make comparison fail if we fall through
2217 if (lowtag_of((lispobj
)ptr
) == FUN_POINTER_LOWTAG
&&
2218 widetag_of(header
) == SIMPLE_FUN_WIDETAG
) {
2219 lispobj
* code
= fun_code_header((lispobj
)ptr
- FUN_POINTER_LOWTAG
);
2220 // This is a heuristic, since we're not actually looking for
2221 // an object boundary. Precise scanning of 'page' would obviate
2222 // the guard conditions here.
2223 if ((lispobj
)code
>= IMMOBILE_VARYOBJ_SUBSPACE_START
2224 && widetag_of(*code
) == CODE_HEADER_WIDETAG
)
2225 obj_gen
= __immobile_obj_generation(code
);
2227 obj_gen
= __immobile_obj_generation(native_pointer((lispobj
)ptr
));
2229 // A bogus generation number implies a not-really-pointer,
2230 // but it won't cause misbehavior.
2231 if (obj_gen
< gen
|| obj_gen
== SCRATCH_GENERATION
) {
2240 /* Write-protect the page. */
2241 /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2243 os_protect((void *)page_addr
,
2245 OS_VM_PROT_READ
|OS_VM_PROT_EXECUTE
);
2247 /* Note the page as protected in the page tables. */
2248 page_table
[page
].write_protected
= 1;
2254 /* Is this page holding a normal (non-hashtable) large-object
2256 static inline boolean
large_simple_vector_p(page_index_t page
) {
2257 if (!page_table
[page
].large_object
)
2259 lispobj object
= *(lispobj
*)page_address(page
);
2260 return widetag_of(object
) == SIMPLE_VECTOR_WIDETAG
&&
2261 (HeaderValue(object
) & 0xFF) == subtype_VectorNormal
;
2265 /* Scavenge all generations from FROM to TO, inclusive, except for
2266 * new_space which needs special handling, as new objects may be
2267 * added which are not checked here - use scavenge_newspace generation.
2269 * Write-protected pages should not have any pointers to the
2270 * from_space so do need scavenging; thus write-protected pages are
2271 * not always scavenged. There is some code to check that these pages
2272 * are not written; but to check fully the write-protected pages need
2273 * to be scavenged by disabling the code to skip them.
2275 * Under the current scheme when a generation is GCed the younger
2276 * generations will be empty. So, when a generation is being GCed it
2277 * is only necessary to scavenge the older generations for pointers
2278 * not the younger. So a page that does not have pointers to younger
2279 * generations does not need to be scavenged.
2281 * The write-protection can be used to note pages that don't have
2282 * pointers to younger pages. But pages can be written without having
2283 * pointers to younger generations. After the pages are scavenged here
2284 * they can be scanned for pointers to younger generations and if
2285 * there are none the page can be write-protected.
2287 * One complication is when the newspace is the top temp. generation.
2289 * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2290 * that none were written, which they shouldn't be as they should have
2291 * no pointers to younger generations. This breaks down for weak
2292 * pointers as the objects contain a link to the next and are written
2293 * if a weak pointer is scavenged. Still it's a useful check. */
2295 scavenge_generations(generation_index_t from
, generation_index_t to
)
2298 page_index_t num_wp
= 0;
2302 /* Clear the write_protected_cleared flags on all pages. */
2303 for (i
= 0; i
< page_table_pages
; i
++)
2304 page_table
[i
].write_protected_cleared
= 0;
2307 for (i
= 0; i
< last_free_page
; i
++) {
2308 generation_index_t generation
= page_table
[i
].gen
;
2310 && (page_bytes_used(i
) != 0)
2311 && (generation
!= new_space
)
2312 && (generation
>= from
)
2313 && (generation
<= to
)) {
2314 page_index_t last_page
,j
;
2315 int write_protected
=1;
2317 /* This should be the start of a region */
2318 gc_assert(page_starts_contiguous_block_p(i
));
2320 if (large_simple_vector_p(i
)) {
2321 /* Scavenge only the unprotected pages of a
2322 * large-object vector, other large objects could be
2323 * handled as well, but vectors are easier to deal
2324 * with and are more likely to grow to very large
2325 * sizes where avoiding scavenging the whole thing is
2327 if (!page_table
[i
].write_protected
) {
2328 scavenge((lispobj
*)page_address(i
) + 2,
2329 GENCGC_CARD_BYTES
/ N_WORD_BYTES
- 2);
2330 update_page_write_prot(i
);
2332 for (last_page
= i
+ 1; ; last_page
++) {
2333 lispobj
* start
= (lispobj
*)page_address(last_page
);
2334 write_protected
= page_table
[last_page
].write_protected
;
2335 if (page_ends_contiguous_block_p(last_page
, generation
)) {
2336 if (!write_protected
) {
2337 scavenge(start
, page_bytes_used(last_page
) / N_WORD_BYTES
);
2338 update_page_write_prot(last_page
);
2342 if (!write_protected
) {
2343 scavenge(start
, GENCGC_CARD_BYTES
/ N_WORD_BYTES
);
2344 update_page_write_prot(last_page
);
2348 /* Now work forward until the end of the region */
2349 for (last_page
= i
; ; last_page
++) {
2351 write_protected
&& page_table
[last_page
].write_protected
;
2352 if (page_ends_contiguous_block_p(last_page
, generation
))
2355 if (!write_protected
) {
2356 heap_scavenge((lispobj
*)page_address(i
),
2357 (lispobj
*)(page_address(last_page
)
2358 + page_bytes_used(last_page
)));
2360 /* Now scan the pages and write protect those that
2361 * don't have pointers to younger generations. */
2362 if (ENABLE_PAGE_PROTECTION
) {
2363 for (j
= i
; j
<= last_page
; j
++) {
2364 num_wp
+= update_page_write_prot(j
);
2367 if ((gencgc_verbose
> 1) && (num_wp
!= 0)) {
2369 "/write protected %d pages within generation %d\n",
2370 num_wp
, generation
));
2379 /* Check that none of the write_protected pages in this generation
2380 * have been written to. */
2381 for (i
= 0; i
< page_table_pages
; i
++) {
2382 if ((page_bytes_used(i
) != 0)
2383 && (page_table
[i
].gen
== generation
)
2384 && (page_table
[i
].write_protected_cleared
!= 0)) {
2385 FSHOW((stderr
, "/scavenge_generation() %d\n", generation
));
2387 "/page bytes_used=%d scan_start_offset=%lu dont_move=%d\n",
2389 scan_start_offset(page_table
[i
]),
2390 page_table
[i
].dont_move
));
2391 lose("write to protected page %d in scavenge_generation()\n", i
);
2398 /* Scavenge a newspace generation. As it is scavenged new objects may
2399 * be allocated to it; these will also need to be scavenged. This
2400 * repeats until there are no more objects unscavenged in the
2401 * newspace generation.
2403 * To help improve the efficiency, areas written are recorded by
2404 * gc_alloc() and only these scavenged. Sometimes a little more will be
2405 * scavenged, but this causes no harm. An easy check is done that the
2406 * scavenged bytes equals the number allocated in the previous
2409 * Write-protected pages are not scanned except if they are marked
2410 * dont_move in which case they may have been promoted and still have
2411 * pointers to the from space.
2413 * Write-protected pages could potentially be written by alloc however
2414 * to avoid having to handle re-scavenging of write-protected pages
2415 * gc_alloc() does not write to write-protected pages.
2417 * New areas of objects allocated are recorded alternatively in the two
2418 * new_areas arrays below. */
2419 static struct new_area new_areas_1
[NUM_NEW_AREAS
];
2420 static struct new_area new_areas_2
[NUM_NEW_AREAS
];
2422 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2423 extern unsigned int immobile_scav_queue_count
;
2425 update_immobile_nursery_bits(),
2426 scavenge_immobile_roots(generation_index_t
,generation_index_t
),
2427 scavenge_immobile_newspace(),
2428 sweep_immobile_space(int raise
),
2429 write_protect_immobile_space();
2431 #define immobile_scav_queue_count 0
2434 /* Do one full scan of the new space generation. This is not enough to
2435 * complete the job as new objects may be added to the generation in
2436 * the process which are not scavenged. */
2438 scavenge_newspace_generation_one_scan(generation_index_t generation
)
2443 "/starting one full scan of newspace generation %d\n",
2445 for (i
= 0; i
< last_free_page
; i
++) {
2446 /* Note that this skips over open regions when it encounters them. */
2448 && (page_bytes_used(i
) != 0)
2449 && (page_table
[i
].gen
== generation
)
2450 && (!page_table
[i
].write_protected
2451 /* (This may be redundant as write_protected is now
2452 * cleared before promotion.) */
2453 || page_table
[i
].dont_move
)) {
2454 page_index_t last_page
;
2457 /* The scavenge will start at the scan_start_offset of
2460 * We need to find the full extent of this contiguous
2461 * block in case objects span pages.
2463 * Now work forward until the end of this contiguous area
2464 * is found. A small area is preferred as there is a
2465 * better chance of its pages being write-protected. */
2466 for (last_page
= i
; ;last_page
++) {
2467 /* If all pages are write-protected and movable,
2468 * then no need to scavenge */
2469 all_wp
=all_wp
&& page_table
[last_page
].write_protected
&&
2470 !page_table
[last_page
].dont_move
;
2472 /* Check whether this is the last page in this
2473 * contiguous block */
2474 if (page_ends_contiguous_block_p(last_page
, generation
))
2478 /* Do a limited check for write-protected pages. */
2480 new_areas_ignore_page
= last_page
;
2481 heap_scavenge(page_scan_start(i
),
2482 (lispobj
*)(page_address(last_page
)
2483 + page_bytes_used(last_page
)));
2489 "/done with one full scan of newspace generation %d\n",
2493 /* Do a complete scavenge of the newspace generation. */
2495 scavenge_newspace_generation(generation_index_t generation
)
2499 /* the new_areas array currently being written to by gc_alloc() */
2500 struct new_area (*current_new_areas
)[] = &new_areas_1
;
2501 size_t current_new_areas_index
;
2503 /* the new_areas created by the previous scavenge cycle */
2504 struct new_area (*previous_new_areas
)[] = NULL
;
2505 size_t previous_new_areas_index
;
2507 /* Flush the current regions updating the tables. */
2508 gc_alloc_update_all_page_tables(0);
2510 /* Turn on the recording of new areas by gc_alloc(). */
2511 new_areas
= current_new_areas
;
2512 new_areas_index
= 0;
2514 /* Don't need to record new areas that get scavenged anyway during
2515 * scavenge_newspace_generation_one_scan. */
2516 record_new_objects
= 1;
2518 /* Start with a full scavenge. */
2519 scavenge_newspace_generation_one_scan(generation
);
2521 /* Record all new areas now. */
2522 record_new_objects
= 2;
2524 /* Give a chance to weak hash tables to make other objects live.
2525 * FIXME: The algorithm implemented here for weak hash table gcing
2526 * is O(W^2+N) as Bruno Haible warns in
2527 * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
2528 * see "Implementation 2". */
2529 scav_weak_hash_tables(weak_ht_alivep_funs
, gc_scav_pair
);
2531 /* Flush the current regions updating the tables. */
2532 gc_alloc_update_all_page_tables(0);
2534 /* Grab new_areas_index. */
2535 current_new_areas_index
= new_areas_index
;
2538 "The first scan is finished; current_new_areas_index=%d.\n",
2539 current_new_areas_index));*/
2541 while (current_new_areas_index
> 0 || immobile_scav_queue_count
) {
2542 /* Move the current to the previous new areas */
2543 previous_new_areas
= current_new_areas
;
2544 previous_new_areas_index
= current_new_areas_index
;
2546 /* Scavenge all the areas in previous new areas. Any new areas
2547 * allocated are saved in current_new_areas. */
2549 /* Allocate an array for current_new_areas; alternating between
2550 * new_areas_1 and 2 */
2551 if (previous_new_areas
== &new_areas_1
)
2552 current_new_areas
= &new_areas_2
;
2554 current_new_areas
= &new_areas_1
;
2556 /* Set up for gc_alloc(). */
2557 new_areas
= current_new_areas
;
2558 new_areas_index
= 0;
2560 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2561 scavenge_immobile_newspace();
2563 /* Check whether previous_new_areas had overflowed. */
2564 if (previous_new_areas_index
>= NUM_NEW_AREAS
) {
2566 /* New areas of objects allocated have been lost so need to do a
2567 * full scan to be sure! If this becomes a problem try
2568 * increasing NUM_NEW_AREAS. */
2569 if (gencgc_verbose
) {
2570 SHOW("new_areas overflow, doing full scavenge");
2573 /* Don't need to record new areas that get scavenged
2574 * anyway during scavenge_newspace_generation_one_scan. */
2575 record_new_objects
= 1;
2577 scavenge_newspace_generation_one_scan(generation
);
2579 /* Record all new areas now. */
2580 record_new_objects
= 2;
2582 scav_weak_hash_tables(weak_ht_alivep_funs
, gc_scav_pair
);
2584 /* Flush the current regions updating the tables. */
2585 gc_alloc_update_all_page_tables(0);
2589 /* Work through previous_new_areas. */
2590 for (i
= 0; i
< previous_new_areas_index
; i
++) {
2591 page_index_t page
= (*previous_new_areas
)[i
].page
;
2592 size_t offset
= (*previous_new_areas
)[i
].offset
;
2593 size_t size
= (*previous_new_areas
)[i
].size
;
2594 gc_assert(size
% N_WORD_BYTES
== 0);
2595 lispobj
*start
= (lispobj
*)(page_address(page
) + offset
);
2596 heap_scavenge(start
, (lispobj
*)((char*)start
+ size
));
2599 scav_weak_hash_tables(weak_ht_alivep_funs
, gc_scav_pair
);
2601 /* Flush the current regions updating the tables. */
2602 gc_alloc_update_all_page_tables(0);
2605 current_new_areas_index
= new_areas_index
;
2608 "The re-scan has finished; current_new_areas_index=%d.\n",
2609 current_new_areas_index));*/
2612 /* Turn off recording of areas allocated by gc_alloc(). */
2613 record_new_objects
= 0;
2618 /* Check that none of the write_protected pages in this generation
2619 * have been written to. */
2620 for (i
= 0; i
< page_table_pages
; i
++) {
2621 if ((page_bytes_used(i
) != 0)
2622 && (page_table
[i
].gen
== generation
)
2623 && (page_table
[i
].write_protected_cleared
!= 0)
2624 && (page_table
[i
].dont_move
== 0)) {
2625 lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
2626 i
, generation
, page_table
[i
].dont_move
);
2633 /* Un-write-protect all the pages in from_space. This is done at the
2634 * start of a GC else there may be many page faults while scavenging
2635 * the newspace (I've seen drive the system time to 99%). These pages
2636 * would need to be unprotected anyway before unmapping in
2637 * free_oldspace; not sure what effect this has on paging.. */
2639 unprotect_oldspace(void)
2642 char *region_addr
= 0;
2643 char *page_addr
= 0;
2644 uword_t region_bytes
= 0;
2646 for (i
= 0; i
< last_free_page
; i
++) {
2647 if ((page_bytes_used(i
) != 0)
2648 && (page_table
[i
].gen
== from_space
)) {
2650 /* Remove any write-protection. We should be able to rely
2651 * on the write-protect flag to avoid redundant calls. */
2652 if (page_table
[i
].write_protected
) {
2653 page_table
[i
].write_protected
= 0;
2654 page_addr
= page_address(i
);
2657 region_addr
= page_addr
;
2658 region_bytes
= GENCGC_CARD_BYTES
;
2659 } else if (region_addr
+ region_bytes
== page_addr
) {
2660 /* Region continue. */
2661 region_bytes
+= GENCGC_CARD_BYTES
;
2663 /* Unprotect previous region. */
2664 os_protect(region_addr
, region_bytes
, OS_VM_PROT_ALL
);
2665 /* First page in new region. */
2666 region_addr
= page_addr
;
2667 region_bytes
= GENCGC_CARD_BYTES
;
2673 /* Unprotect last region. */
2674 os_protect(region_addr
, region_bytes
, OS_VM_PROT_ALL
);
2678 /* Work through all the pages and free any in from_space. This
2679 * assumes that all objects have been copied or promoted to an older
2680 * generation. Bytes_allocated and the generation bytes_allocated
2681 * counter are updated. The number of bytes freed is returned. */
2685 uword_t bytes_freed
= 0;
2686 page_index_t first_page
, last_page
;
2691 /* Find a first page for the next region of pages. */
2692 while ((first_page
< last_free_page
)
2693 && ((page_bytes_used(first_page
) == 0)
2694 || (page_table
[first_page
].gen
!= from_space
)))
2697 if (first_page
>= last_free_page
)
2700 /* Find the last page of this region. */
2701 last_page
= first_page
;
2704 /* Free the page. */
2705 bytes_freed
+= page_bytes_used(last_page
);
2706 generations
[page_table
[last_page
].gen
].bytes_allocated
-=
2707 page_bytes_used(last_page
);
2708 reset_page_flags(last_page
);
2709 set_page_bytes_used(last_page
, 0);
2710 /* Should already be unprotected by unprotect_oldspace(). */
2711 gc_assert(!page_table
[last_page
].write_protected
);
2714 while ((last_page
< last_free_page
)
2715 && (page_bytes_used(last_page
) != 0)
2716 && (page_table
[last_page
].gen
== from_space
));
2718 #ifdef TRAVERSE_FREED_OBJECTS
2719 /* At this point we could attempt to recycle unused TLS indices
2720 * as follows: For each now-garbage symbol that had a nonzero index,
2721 * return that index to a "free TLS index" pool, perhaps a linked list
2722 * or bitmap. Then either always try the free pool first (for better
2723 * locality) or if ALLOC-TLS-INDEX detects exhaustion (for speed). */
2725 lispobj
* where
= (lispobj
*)page_address(first_page
);
2726 lispobj
* end
= (lispobj
*)page_address(last_page
);
2727 while (where
< end
) {
2728 lispobj word
= *where
;
2729 if (forwarding_pointer_p(where
)) {
2730 word
= *native_pointer(forwarding_pointer_value(where
));
2731 where
+= OBJECT_SIZE(word
,
2732 native_pointer(forwarding_pointer_value(where
)));
2733 } else if (is_cons_half(word
)) {
2734 // Print something maybe
2737 // Print something maybe
2738 where
+= sizetab
[widetag_of(word
)](where
);
2744 #ifdef READ_PROTECT_FREE_PAGES
2745 os_protect(page_address(first_page
),
2746 npage_bytes(last_page
-first_page
),
2749 first_page
= last_page
;
2750 } while (first_page
< last_free_page
);
2752 bytes_allocated
-= bytes_freed
;
2757 /* Print some information about a pointer at the given address. */
2759 print_ptr(lispobj
*addr
)
2761 /* If addr is in the dynamic space then out the page information. */
2762 page_index_t pi1
= find_page_index((void*)addr
);
2765 fprintf(stderr
," %p: page %d alloc %d gen %d bytes_used %d offset %lu dont_move %d\n",
2768 page_table
[pi1
].allocated
,
2769 page_table
[pi1
].gen
,
2770 page_bytes_used(pi1
),
2771 scan_start_offset(page_table
[pi1
]),
2772 page_table
[pi1
].dont_move
);
2773 fprintf(stderr
," %x %x %x %x (%x) %x %x %x %x\n",
2787 is_in_stack_space(lispobj ptr
)
2789 /* For space verification: Pointers can be valid if they point
2790 * to a thread stack space. This would be faster if the thread
2791 * structures had page-table entries as if they were part of
2792 * the heap space. */
2793 /* Actually, no, how would that be faster?
2794 * If you have to examine thread structures, you have to examine
2795 * them all. This demands something like a binary search tree */
2797 for_each_thread(th
) {
2798 if ((th
->control_stack_start
<= (lispobj
*)ptr
) &&
2799 (th
->control_stack_end
>= (lispobj
*)ptr
)) {
2806 struct verify_state
{
2807 lispobj
*object_start
, *object_end
;
2808 lispobj
*virtual_where
;
2811 generation_index_t object_gen
;
2814 #define VERIFY_VERBOSE 1
2815 /* AGGRESSIVE = always call valid_lisp_pointer_p() on pointers.
2816 * Otherwise, do only a quick check that widetag/lowtag correspond */
2817 #define VERIFY_AGGRESSIVE 2
2818 /* VERIFYING_foo indicates internal state, not a caller's option */
2819 #define VERIFYING_HEAP_OBJECTS 8
2821 // NOTE: This function can produces false failure indications,
2822 // usually related to dynamic space pointing to the stack of a
2823 // dead thread, but there may be other reasons as well.
2825 verify_range(lispobj
*where
, sword_t nwords
, struct verify_state
*state
)
2827 extern int valid_lisp_pointer_p(lispobj
);
2828 boolean is_in_readonly_space
=
2829 (READ_ONLY_SPACE_START
<= (uword_t
)where
&&
2830 where
< read_only_space_free_pointer
);
2831 boolean is_in_immobile_space
= 0;
2832 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2833 is_in_immobile_space
=
2834 (IMMOBILE_SPACE_START
<= (uword_t
)where
&&
2835 where
< immobile_space_free_pointer
);
2838 lispobj
*end
= where
+ nwords
;
2840 for ( ; where
< end
; where
+= count
) {
2841 // Keep track of object boundaries, unless verifying a non-heap space.
2842 if (where
> state
->object_end
&& (state
->flags
& VERIFYING_HEAP_OBJECTS
)) {
2843 state
->object_start
= where
;
2844 state
->object_end
= where
+ OBJECT_SIZE(*where
, where
) - 1;
2847 lispobj thing
= *where
;
2850 if (is_lisp_pointer(thing
)) {
2851 page_index_t page_index
= find_page_index((void*)thing
);
2852 boolean to_immobile_space
= 0;
2853 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2855 (IMMOBILE_SPACE_START
<= thing
&&
2856 thing
< (lispobj
)immobile_fixedobj_free_pointer
) ||
2857 (IMMOBILE_VARYOBJ_SUBSPACE_START
<= thing
&&
2858 thing
< (lispobj
)immobile_space_free_pointer
);
2861 /* unlike lose(), fprintf detects format mismatch, hence the casts */
2862 #define FAIL_IF(what, why) if (what) { \
2863 if (++state->errors > 25) lose("Too many errors"); \
2864 else fprintf(stderr, "Ptr %p @ %"OBJ_FMTX" sees %s\n", \
2865 (void*)(uintptr_t)thing, \
2866 (lispobj)(state->virtual_where ? state->virtual_where : where), \
2869 /* Does it point to the dynamic space? */
2870 if (page_index
!= -1) {
2871 /* If it's within the dynamic space it should point to a used page. */
2872 FAIL_IF(page_free_p(page_index
), "free page");
2873 FAIL_IF(!(page_table
[page_index
].allocated
& OPEN_REGION_PAGE_FLAG
)
2874 && (thing
& (GENCGC_CARD_BYTES
-1)) >= page_bytes_used(page_index
),
2875 "unallocated space");
2876 /* Check that it doesn't point to a forwarding pointer! */
2877 FAIL_IF(*native_pointer(thing
) == 0x01, "forwarding ptr");
2878 /* Check that its not in the RO space as it would then be a
2879 * pointer from the RO to the dynamic space. */
2880 FAIL_IF(is_in_readonly_space
, "dynamic space from RO space");
2881 } else if (to_immobile_space
) {
2882 // the object pointed to must not have been discarded as garbage
2883 FAIL_IF(!other_immediate_lowtag_p(*native_pointer(thing
)) ||
2884 immobile_filler_p(native_pointer(thing
)),
2887 /* Any pointer that points to non-static space is examined further.
2888 * You might think this should scan stacks first as a quick out,
2889 * but that would take time proportional to the number of threads. */
2890 if (page_index
>= 0 || to_immobile_space
) {
2892 /* If aggressive, or to/from immobile space, do a full search
2893 * (as entailed by valid_lisp_pointer_p) */
2894 if ((state
->flags
& VERIFY_AGGRESSIVE
)
2895 || (is_in_immobile_space
|| to_immobile_space
))
2896 valid
= valid_lisp_pointer_p(thing
);
2898 /* Efficiently decide whether 'thing' is plausible.
2899 * This MUST NOT use properly_tagged_descriptor_p() which
2900 * assumes a known good object base address, and would
2901 * "dangerously" scan a code component for embedded funs. */
2902 int lowtag
= lowtag_of(thing
);
2903 if (lowtag
== LIST_POINTER_LOWTAG
)
2904 valid
= is_cons_half(CONS(thing
)->car
)
2905 && is_cons_half(CONS(thing
)->cdr
);
2907 lispobj word
= *native_pointer(thing
);
2908 valid
= other_immediate_lowtag_p(word
) &&
2909 lowtag_for_widetag
[widetag_of(word
)>>2] == lowtag
;
2912 /* If 'thing' points to a stack, we can only hope that the frame
2913 * not clobbered, or the object at 'where' is unreachable. */
2914 FAIL_IF(!valid
&& !is_in_stack_space(thing
), "junk");
2918 int widetag
= widetag_of(thing
);
2919 if (is_lisp_immediate(thing
) || widetag
== NO_TLS_VALUE_MARKER_WIDETAG
) {
2920 /* skip immediates */
2921 } else if (!(other_immediate_lowtag_p(widetag
)
2922 && lowtag_for_widetag
[widetag
>>2])) {
2923 lose("Unhandled widetag %p at %p\n", widetag
, where
);
2924 } else if (unboxed_obj_widetag_p(widetag
)) {
2925 count
= sizetab
[widetag
](where
);
2926 } else switch(widetag
) {
2927 /* boxed or partially boxed objects */
2928 // FIXME: x86-64 can have partially unboxed FINs. The raw words
2929 // are at the moment valid fixnums by blind luck.
2930 case INSTANCE_WIDETAG
:
2931 if (instance_layout(where
)) {
2932 sword_t nslots
= instance_length(thing
) | 1;
2933 lispobj bitmap
= LAYOUT(instance_layout(where
))->bitmap
;
2934 gc_assert(fixnump(bitmap
)
2935 || widetag_of(*native_pointer(bitmap
))==BIGNUM_WIDETAG
);
2936 instance_scan((void (*)(lispobj
*, sword_t
, uword_t
))verify_range
,
2937 where
+1, nslots
, bitmap
, (uintptr_t)state
);
2941 case CODE_HEADER_WIDETAG
:
2943 struct code
*code
= (struct code
*) where
;
2944 sword_t nheader_words
= code_header_words(code
->header
);
2945 /* Scavenge the boxed section of the code data block */
2946 verify_range(where
+ 1, nheader_words
- 1, state
);
2948 /* Scavenge the boxed section of each function
2949 * object in the code data block. */
2950 for_each_simple_fun(i
, fheaderp
, code
, 1, {
2951 #if defined(LISP_FEATURE_COMPACT_INSTANCE_HEADER)
2952 lispobj
__attribute__((unused
)) layout
=
2953 function_layout((lispobj
*)fheaderp
);
2954 gc_assert(!layout
|| layout
== SYMBOL(FUNCTION_LAYOUT
)->value
>> 32);
2956 verify_range(SIMPLE_FUN_SCAV_START(fheaderp
),
2957 SIMPLE_FUN_SCAV_NWORDS(fheaderp
),
2959 count
= nheader_words
+ code_instruction_words(code
->code_size
);
2963 verify_range(where
+ 1, 2, state
);
2964 callee
= fdefn_callee_lispobj((struct fdefn
*)where
);
2965 /* For a more intelligible error, don't say that the word that
2966 * contains an errant pointer is in stack space if it isn't. */
2967 state
->virtual_where
= where
+ 3;
2968 verify_range(&callee
, 1, state
);
2969 state
->virtual_where
= 0;
2970 count
= CEILING(sizeof (struct fdefn
)/sizeof(lispobj
), 2);
2975 static uword_t
verify_space(lispobj start
, lispobj
* end
, uword_t flags
) {
2976 struct verify_state state
;
2977 memset(&state
, 0, sizeof state
);
2978 state
.flags
= flags
;
2979 verify_range((lispobj
*)start
, end
-(lispobj
*)start
, &state
);
2980 if (state
.errors
) lose("verify failed: %d error(s)", state
.errors
);
2983 static uword_t
verify_gen_aux(lispobj start
, lispobj
* end
, struct verify_state
* state
)
2985 verify_range((lispobj
*)start
, end
-(lispobj
*)start
, state
);
2988 static void verify_generation(generation_index_t generation
, uword_t flags
)
2990 struct verify_state state
;
2991 memset(&state
, 0, sizeof state
);
2992 state
.flags
= flags
;
2993 walk_generation((uword_t(*)(lispobj
*,lispobj
*,uword_t
))verify_gen_aux
,
2994 generation
, (uword_t
)&state
);
2995 if (state
.errors
) lose("verify failed: %d error(s)", state
.errors
);
2998 void verify_gc(uword_t flags
)
3000 int verbose
= flags
& VERIFY_VERBOSE
;
3002 flags
|= VERIFYING_HEAP_OBJECTS
;
3004 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3006 // Try this verification if marknsweep was compiled with extra debugging.
3007 // But weak symbols don't work on macOS.
3008 extern void __attribute__((weak
)) check_varyobj_pages();
3009 if (&check_varyobj_pages
) check_varyobj_pages();
3012 printf("Verifying immobile space\n");
3013 verify_space(IMMOBILE_SPACE_START
, immobile_fixedobj_free_pointer
, flags
);
3014 verify_space(IMMOBILE_VARYOBJ_SUBSPACE_START
, immobile_space_free_pointer
, flags
);
3018 printf("Verifying binding stacks\n");
3019 for_each_thread(th
) {
3020 verify_space((lispobj
)th
->binding_stack_start
,
3021 (lispobj
*)get_binding_stack_pointer(th
),
3022 flags
^ VERIFYING_HEAP_OBJECTS
);
3023 #ifdef LISP_FEATURE_SB_THREAD
3024 verify_space((lispobj
)(th
+1),
3025 (lispobj
*)(SymbolValue(FREE_TLS_INDEX
,0)
3026 + (char*)((union per_thread_data
*)th
)->dynamic_values
),
3027 flags
^ VERIFYING_HEAP_OBJECTS
);
3031 printf("Verifying RO space\n");
3032 verify_space(READ_ONLY_SPACE_START
, read_only_space_free_pointer
, flags
);
3034 printf("Verifying static space\n");
3035 verify_space(STATIC_SPACE_START
, static_space_free_pointer
, flags
);
3037 printf("Verifying dynamic space\n");
3038 verify_generation(-1, flags
);
3041 /* Call 'proc' with pairs of addresses demarcating ranges in the
3042 * specified generation.
3043 * Stop if any invocation returns non-zero, and return that value */
3045 walk_generation(uword_t (*proc
)(lispobj
*,lispobj
*,uword_t
),
3046 generation_index_t generation
, uword_t extra
)
3049 int genmask
= generation
>= 0 ? 1 << generation
: ~0;
3051 for (i
= 0; i
< last_free_page
; i
++) {
3052 if ((page_bytes_used(i
) != 0) && ((1 << page_table
[i
].gen
) & genmask
)) {
3053 page_index_t last_page
;
3055 /* This should be the start of a contiguous block */
3056 gc_assert(page_starts_contiguous_block_p(i
));
3058 /* Need to find the full extent of this contiguous block in case
3059 objects span pages. */
3061 /* Now work forward until the end of this contiguous area is
3063 for (last_page
= i
; ;last_page
++)
3064 /* Check whether this is the last page in this contiguous
3066 if (page_ends_contiguous_block_p(last_page
, page_table
[i
].gen
))
3070 proc((lispobj
*)page_address(i
),
3071 (lispobj
*)(page_bytes_used(last_page
) + page_address(last_page
)),
3073 if (result
) return result
;
3081 /* Check that all the free space is zero filled. */
3083 verify_zero_fill(void)
3087 for (page
= 0; page
< last_free_page
; page
++) {
3088 if (page_free_p(page
)) {
3089 /* The whole page should be zero filled. */
3090 sword_t
*start_addr
= (sword_t
*)page_address(page
);
3092 for (i
= 0; i
< (sword_t
)GENCGC_CARD_BYTES
/N_WORD_BYTES
; i
++) {
3093 if (start_addr
[i
] != 0) {
3094 lose("free page not zero at %p\n", start_addr
+ i
);
3098 sword_t free_bytes
= GENCGC_CARD_BYTES
- page_bytes_used(page
);
3099 if (free_bytes
> 0) {
3100 sword_t
*start_addr
=
3101 (sword_t
*)(page_address(page
) + page_bytes_used(page
));
3102 sword_t size
= free_bytes
/ N_WORD_BYTES
;
3104 for (i
= 0; i
< size
; i
++) {
3105 if (start_addr
[i
] != 0) {
3106 lose("free region not zero at %p\n", start_addr
+ i
);
3114 /* External entry point for verify_zero_fill */
3116 gencgc_verify_zero_fill(void)
3118 /* Flush the alloc regions updating the tables. */
3119 gc_alloc_update_all_page_tables(1);
3120 SHOW("verifying zero fill");
3124 /* Write-protect all the dynamic boxed pages in the given generation. */
3126 write_protect_generation_pages(generation_index_t generation
)
3130 gc_assert(generation
< SCRATCH_GENERATION
);
3132 for (start
= 0; start
< last_free_page
; start
++) {
3133 if (protect_page_p(start
, generation
)) {
3137 /* Note the page as protected in the page tables. */
3138 page_table
[start
].write_protected
= 1;
3140 for (last
= start
+ 1; last
< last_free_page
; last
++) {
3141 if (!protect_page_p(last
, generation
))
3143 page_table
[last
].write_protected
= 1;
3146 page_start
= page_address(start
);
3148 os_protect(page_start
,
3149 npage_bytes(last
- start
),
3150 OS_VM_PROT_READ
| OS_VM_PROT_EXECUTE
);
3156 if (gencgc_verbose
> 1) {
3158 "/write protected %d of %d pages in generation %d\n",
3159 count_write_protect_generation_pages(generation
),
3160 count_generation_pages(generation
),
3165 #if !GENCGC_IS_PRECISE
3167 preserve_context_registers (void (*proc
)(os_context_register_t
), os_context_t
*c
)
3169 #ifdef LISP_FEATURE_SB_THREAD
3171 /* On Darwin the signal context isn't a contiguous block of memory,
3172 * so just preserve_pointering its contents won't be sufficient.
3174 #if defined(LISP_FEATURE_DARWIN)||defined(LISP_FEATURE_WIN32)
3175 #if defined LISP_FEATURE_X86
3176 proc(*os_context_register_addr(c
,reg_EAX
));
3177 proc(*os_context_register_addr(c
,reg_ECX
));
3178 proc(*os_context_register_addr(c
,reg_EDX
));
3179 proc(*os_context_register_addr(c
,reg_EBX
));
3180 proc(*os_context_register_addr(c
,reg_ESI
));
3181 proc(*os_context_register_addr(c
,reg_EDI
));
3182 proc(*os_context_pc_addr(c
));
3183 #elif defined LISP_FEATURE_X86_64
3184 proc(*os_context_register_addr(c
,reg_RAX
));
3185 proc(*os_context_register_addr(c
,reg_RCX
));
3186 proc(*os_context_register_addr(c
,reg_RDX
));
3187 proc(*os_context_register_addr(c
,reg_RBX
));
3188 proc(*os_context_register_addr(c
,reg_RSI
));
3189 proc(*os_context_register_addr(c
,reg_RDI
));
3190 proc(*os_context_register_addr(c
,reg_R8
));
3191 proc(*os_context_register_addr(c
,reg_R9
));
3192 proc(*os_context_register_addr(c
,reg_R10
));
3193 proc(*os_context_register_addr(c
,reg_R11
));
3194 proc(*os_context_register_addr(c
,reg_R12
));
3195 proc(*os_context_register_addr(c
,reg_R13
));
3196 proc(*os_context_register_addr(c
,reg_R14
));
3197 proc(*os_context_register_addr(c
,reg_R15
));
3198 proc(*os_context_pc_addr(c
));
3200 #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3203 #if !defined(LISP_FEATURE_WIN32)
3204 for(ptr
= ((void **)(c
+1))-1; ptr
>=(void **)c
; ptr
--) {
3205 proc((os_context_register_t
)*ptr
);
3208 #endif // LISP_FEATURE_SB_THREAD
3213 move_pinned_pages_to_newspace()
3217 /* scavenge() will evacuate all oldspace pages, but no newspace
3218 * pages. Pinned pages are precisely those pages which must not
3219 * be evacuated, so move them to newspace directly. */
3221 for (i
= 0; i
< last_free_page
; i
++) {
3222 if (page_table
[i
].dont_move
&&
3223 /* dont_move is cleared lazily, so test the 'gen' field as well. */
3224 page_table
[i
].gen
== from_space
) {
3225 if (page_table
[i
].has_pins
) {
3226 // do not move to newspace after all, this will be word-wiped
3229 page_table
[i
].gen
= new_space
;
3230 /* And since we're moving the pages wholesale, also adjust
3231 * the generation allocation counters. */
3232 int used
= page_bytes_used(i
);
3233 generations
[new_space
].bytes_allocated
+= used
;
3234 generations
[from_space
].bytes_allocated
-= used
;
3239 #if defined(__GNUC__) && defined(ADDRESS_SANITIZER)
3240 #define NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
3242 #define NO_SANITIZE_ADDRESS
3245 /* Garbage collect a generation. If raise is 0 then the remains of the
3246 * generation are not raised to the next generation. */
3247 static void NO_SANITIZE_ADDRESS
3248 garbage_collect_generation(generation_index_t generation
, int raise
)
3253 gc_assert(generation
<= PSEUDO_STATIC_GENERATION
);
3255 /* The oldest generation can't be raised. */
3256 gc_assert(!raise
|| generation
< HIGHEST_NORMAL_GENERATION
);
3258 /* Check if weak hash tables were processed in the previous GC. */
3259 gc_assert(weak_hash_tables
== NULL
);
3261 /* Initialize the weak pointer list. */
3262 weak_pointers
= NULL
;
3264 /* When a generation is not being raised it is transported to a
3265 * temporary generation (NUM_GENERATIONS), and lowered when
3266 * done. Set up this new generation. There should be no pages
3267 * allocated to it yet. */
3269 gc_assert(generations
[SCRATCH_GENERATION
].bytes_allocated
== 0);
3272 /* Set the global src and dest. generations */
3273 if (generation
< PSEUDO_STATIC_GENERATION
) {
3275 from_space
= generation
;
3277 new_space
= generation
+1;
3279 new_space
= SCRATCH_GENERATION
;
3281 /* Change to a new space for allocation, resetting the alloc_start_page */
3282 gc_alloc_generation
= new_space
;
3283 #ifdef LISP_FEATURE_SEGREGATED_CODE
3284 bzero(generations
[new_space
].alloc_start_page_
,
3285 sizeof generations
[new_space
].alloc_start_page_
);
3287 generations
[new_space
].alloc_start_page
= 0;
3288 generations
[new_space
].alloc_unboxed_start_page
= 0;
3289 generations
[new_space
].alloc_large_start_page
= 0;
3292 #ifdef PIN_GRANULARITY_LISPOBJ
3293 hopscotch_reset(&pinned_objects
);
3295 /* Before any pointers are preserved, the dont_move flags on the
3296 * pages need to be cleared. */
3297 /* FIXME: consider moving this bitmap into its own range of words,
3298 * out of the page table. Then we can just bzero() it.
3299 * This will also obviate the extra test at the comment
3300 * "dont_move is cleared lazily" in move_pinned_pages_to_newspace().
3302 for (i
= 0; i
< last_free_page
; i
++)
3303 if(page_table
[i
].gen
==from_space
)
3304 page_table
[i
].dont_move
= 0;
3306 /* Un-write-protect the old-space pages. This is essential for the
3307 * promoted pages as they may contain pointers into the old-space
3308 * which need to be scavenged. It also helps avoid unnecessary page
3309 * faults as forwarding pointers are written into them. They need to
3310 * be un-protected anyway before unmapping later. */
3311 if (ENABLE_PAGE_PROTECTION
)
3312 unprotect_oldspace();
3314 } else { // "full" [sic] GC
3316 extern void prepare_for_full_mark_phase();
3317 /* This is a full mark-and-sweep of all generations without compacting
3318 * and without returning free space to the allocator. The intent is to
3319 * break chains of objects causing accidental reachability.
3320 * Subsequent GC cycles will compact and reclaims space as usual. */
3321 if (ENABLE_PAGE_PROTECTION
) {
3322 // Unprotect everything
3323 for (i
= 0; i
< last_free_page
; i
++)
3324 if (page_bytes_used(i
))
3325 page_table
[i
].write_protected
= 0;
3326 os_protect(page_address(0), npage_bytes(last_free_page
),
3329 from_space
= new_space
= -1;
3330 // Allocate pages from dynamic space for the work queue.
3331 prepare_for_full_mark_phase();
3335 /* Scavenge the stacks' conservative roots. */
3337 /* there are potentially two stacks for each thread: the main
3338 * stack, which may contain Lisp pointers, and the alternate stack.
3339 * We don't ever run Lisp code on the altstack, but it may
3340 * host a sigcontext with lisp objects in it */
3342 /* what we need to do: (1) find the stack pointer for the main
3343 * stack; scavenge it (2) find the interrupt context on the
3344 * alternate stack that might contain lisp values, and scavenge
3347 /* we assume that none of the preceding applies to the thread that
3348 * initiates GC. If you ever call GC from inside an altstack
3349 * handler, you will lose. */
3351 #if !GENCGC_IS_PRECISE
3352 /* And if we're saving a core, there's no point in being conservative. */
3353 if (conservative_stack
) {
3354 for_each_thread(th
) {
3356 void **esp
=(void **)-1;
3357 if (th
->state
== STATE_DEAD
)
3359 # if defined(LISP_FEATURE_SB_SAFEPOINT)
3360 /* Conservative collect_garbage is always invoked with a
3361 * foreign C call or an interrupt handler on top of every
3362 * existing thread, so the stored SP in each thread
3363 * structure is valid, no matter which thread we are looking
3364 * at. For threads that were running Lisp code, the pitstop
3365 * and edge functions maintain this value within the
3366 * interrupt or exception handler. */
3367 esp
= os_get_csp(th
);
3368 assert_on_stack(th
, esp
);
3370 /* In addition to pointers on the stack, also preserve the
3371 * return PC, the only value from the context that we need
3372 * in addition to the SP. The return PC gets saved by the
3373 * foreign call wrapper, and removed from the control stack
3374 * into a register. */
3375 preserve_pointer(th
->pc_around_foreign_call
);
3377 /* And on platforms with interrupts: scavenge ctx registers. */
3379 /* Disabled on Windows, because it does not have an explicit
3380 * stack of `interrupt_contexts'. The reported CSP has been
3381 * chosen so that the current context on the stack is
3382 * covered by the stack scan. See also set_csp_from_context(). */
3383 # ifndef LISP_FEATURE_WIN32
3384 if (th
!= arch_os_get_current_thread()) {
3385 long k
= fixnum_value(
3386 read_TLS(FREE_INTERRUPT_CONTEXT_INDEX
,th
));
3388 preserve_context_registers((void(*)(os_context_register_t
))preserve_pointer
,
3389 th
->interrupt_contexts
[--k
]);
3392 # elif defined(LISP_FEATURE_SB_THREAD)
3394 if(th
==arch_os_get_current_thread()) {
3395 /* Somebody is going to burn in hell for this, but casting
3396 * it in two steps shuts gcc up about strict aliasing. */
3397 esp
= (void **)((void *)&raise
);
3400 free
=fixnum_value(read_TLS(FREE_INTERRUPT_CONTEXT_INDEX
,th
));
3401 for(i
=free
-1;i
>=0;i
--) {
3402 os_context_t
*c
=th
->interrupt_contexts
[i
];
3403 esp1
= (void **) *os_context_register_addr(c
,reg_SP
);
3404 if (esp1
>=(void **)th
->control_stack_start
&&
3405 esp1
<(void **)th
->control_stack_end
) {
3406 if(esp1
<esp
) esp
=esp1
;
3407 preserve_context_registers((void(*)(os_context_register_t
))preserve_pointer
,
3413 esp
= (void **)((void *)&raise
);
3415 if (!esp
|| esp
== (void*) -1)
3416 lose("garbage_collect: no SP known for thread %x (OS %x)",
3418 for (ptr
= ((void **)th
->control_stack_end
)-1; ptr
>= esp
; ptr
--) {
3419 preserve_pointer(*ptr
);
3424 /* Non-x86oid systems don't have "conservative roots" as such, but
3425 * the same mechanism is used for objects pinned for use by alien
3427 for_each_thread(th
) {
3428 lispobj pin_list
= read_TLS(PINNED_OBJECTS
,th
);
3429 while (pin_list
!= NIL
) {
3430 preserve_pointer((void*)(CONS(pin_list
)->car
));
3431 pin_list
= CONS(pin_list
)->cdr
;
3437 if (gencgc_verbose
> 1) {
3438 sword_t num_dont_move_pages
= count_dont_move_pages();
3440 "/non-movable pages due to conservative pointers = %ld (%lu bytes)\n",
3441 num_dont_move_pages
,
3442 npage_bytes(num_dont_move_pages
));
3446 /* Now that all of the pinned (dont_move) pages are known, and
3447 * before we start to scavenge (and thus relocate) objects,
3448 * relocate the pinned pages to newspace, so that the scavenger
3449 * will not attempt to relocate their contents. */
3451 move_pinned_pages_to_newspace();
3453 /* Scavenge all the rest of the roots. */
3455 #if GENCGC_IS_PRECISE
3457 * If not x86, we need to scavenge the interrupt context(s) and the
3462 for_each_thread(th
) {
3463 scavenge_interrupt_contexts(th
);
3464 scavenge_control_stack(th
);
3467 # ifdef LISP_FEATURE_SB_SAFEPOINT
3468 /* In this case, scrub all stacks right here from the GCing thread
3469 * instead of doing what the comment below says. Suboptimal, but
3472 scrub_thread_control_stack(th
);
3474 /* Scrub the unscavenged control stack space, so that we can't run
3475 * into any stale pointers in a later GC (this is done by the
3476 * stop-for-gc handler in the other threads). */
3477 scrub_control_stack();
3482 /* Scavenge the Lisp functions of the interrupt handlers, taking
3483 * care to avoid SIG_DFL and SIG_IGN. */
3484 for (i
= 0; i
< NSIG
; i
++) {
3485 union interrupt_handler handler
= interrupt_handlers
[i
];
3486 if (!ARE_SAME_HANDLER(handler
.c
, SIG_IGN
) &&
3487 !ARE_SAME_HANDLER(handler
.c
, SIG_DFL
) &&
3488 is_lisp_pointer(handler
.lisp
)) {
3490 scavenge((lispobj
*)(interrupt_handlers
+ i
), 1);
3492 gc_mark_obj(handler
.lisp
);
3495 /* Scavenge the binding stacks. */
3498 for_each_thread(th
) {
3499 scav_binding_stack((lispobj
*)th
->binding_stack_start
,
3500 (lispobj
*)get_binding_stack_pointer(th
),
3501 compacting_p() ? 0 : gc_mark_obj
);
3502 #ifdef LISP_FEATURE_SB_THREAD
3503 /* do the tls as well */
3505 len
=(SymbolValue(FREE_TLS_INDEX
,0) >> WORD_SHIFT
) -
3506 (sizeof (struct thread
))/(sizeof (lispobj
));
3508 scavenge((lispobj
*) (th
+1), len
);
3510 gc_mark_range((lispobj
*) (th
+1), len
);
3515 if (!compacting_p()) {
3516 extern void execute_full_mark_phase();
3517 extern void execute_full_sweep_phase();
3518 execute_full_mark_phase();
3519 execute_full_sweep_phase();
3523 /* Scavenge static space. */
3524 if (gencgc_verbose
> 1) {
3526 "/scavenge static space: %d bytes\n",
3527 (uword_t
)static_space_free_pointer
- STATIC_SPACE_START
));
3529 heap_scavenge((lispobj
*)STATIC_SPACE_START
, static_space_free_pointer
);
3531 /* All generations but the generation being GCed need to be
3532 * scavenged. The new_space generation needs special handling as
3533 * objects may be moved in - it is handled separately below. */
3534 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3535 scavenge_immobile_roots(generation
+1, SCRATCH_GENERATION
);
3537 scavenge_generations(generation
+1, PSEUDO_STATIC_GENERATION
);
3539 #ifdef LISP_FEATURE_SB_TRACEROOT
3540 if (gc_object_watcher
) scavenge(&gc_object_watcher
, 1);
3542 scavenge_pinned_ranges();
3543 /* The Lisp start function is stored in the core header, not a static
3544 * symbol. It is passed to gc_and_save() in this C variable */
3545 if (lisp_init_function
) scavenge(&lisp_init_function
, 1);
3547 /* Finally scavenge the new_space generation. Keep going until no
3548 * more objects are moved into the new generation */
3549 scavenge_newspace_generation(new_space
);
3551 /* FIXME: I tried reenabling this check when debugging unrelated
3552 * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3553 * Since the current GC code seems to work well, I'm guessing that
3554 * this debugging code is just stale, but I haven't tried to
3555 * figure it out. It should be figured out and then either made to
3556 * work or just deleted. */
3558 #define RESCAN_CHECK 0
3560 /* As a check re-scavenge the newspace once; no new objects should
3563 os_vm_size_t old_bytes_allocated
= bytes_allocated
;
3564 os_vm_size_t bytes_allocated
;
3566 /* Start with a full scavenge. */
3567 scavenge_newspace_generation_one_scan(new_space
);
3569 /* Flush the current regions, updating the tables. */
3570 gc_alloc_update_all_page_tables(1);
3572 bytes_allocated
= bytes_allocated
- old_bytes_allocated
;
3574 if (bytes_allocated
!= 0) {
3575 lose("Rescan of new_space allocated %d more bytes.\n",
3581 scan_binding_stack();
3582 scan_weak_hash_tables(weak_ht_alivep_funs
);
3583 scan_weak_pointers();
3584 wipe_nonpinned_words();
3585 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3586 // Do this last, because until wipe_nonpinned_words() happens,
3587 // not all page table entries have the 'gen' value updated,
3588 // which we need to correctly find all old->young pointers.
3589 sweep_immobile_space(raise
);
3592 /* Flush the current regions, updating the tables. */
3593 gc_alloc_update_all_page_tables(0);
3594 #ifdef PIN_GRANULARITY_LISPOBJ
3595 hopscotch_log_stats(&pinned_objects
, "pins");
3598 /* Free the pages in oldspace, but not those marked dont_move. */
3601 /* If the GC is not raising the age then lower the generation back
3602 * to its normal generation number */
3604 for (i
= 0; i
< last_free_page
; i
++)
3605 if ((page_bytes_used(i
) != 0)
3606 && (page_table
[i
].gen
== SCRATCH_GENERATION
))
3607 page_table
[i
].gen
= generation
;
3608 gc_assert(generations
[generation
].bytes_allocated
== 0);
3609 generations
[generation
].bytes_allocated
=
3610 generations
[SCRATCH_GENERATION
].bytes_allocated
;
3611 generations
[SCRATCH_GENERATION
].bytes_allocated
= 0;
3614 /* Reset the alloc_start_page for generation. */
3615 #ifdef LISP_FEATURE_SEGREGATED_CODE
3616 bzero(generations
[generation
].alloc_start_page_
,
3617 sizeof generations
[generation
].alloc_start_page_
);
3619 generations
[generation
].alloc_start_page
= 0;
3620 generations
[generation
].alloc_unboxed_start_page
= 0;
3621 generations
[generation
].alloc_large_start_page
= 0;
3624 /* Set the new gc trigger for the GCed generation. */
3625 generations
[generation
].gc_trigger
=
3626 generations
[generation
].bytes_allocated
3627 + generations
[generation
].bytes_consed_between_gc
;
3630 generations
[generation
].num_gc
= 0;
3632 ++generations
[generation
].num_gc
;
3635 if (generation
>= verify_gens
) {
3636 if (gencgc_verbose
) {
3643 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3645 update_dynamic_space_free_pointer(void)
3647 page_index_t last_page
= -1, i
;
3649 for (i
= 0; i
< last_free_page
; i
++)
3650 if (page_bytes_used(i
) != 0)
3653 last_free_page
= last_page
+1;
3655 set_alloc_pointer((lispobj
)(page_address(last_free_page
)));
3656 return 0; /* dummy value: return something ... */
3660 remap_page_range (page_index_t from
, page_index_t to
)
3662 /* There's a mysterious Solaris/x86 problem with using mmap
3663 * tricks for memory zeroing. See sbcl-devel thread
3664 * "Re: patch: standalone executable redux".
3666 #if defined(LISP_FEATURE_SUNOS)
3667 zero_and_mark_pages(from
, to
);
3670 release_granularity
= gencgc_release_granularity
/GENCGC_CARD_BYTES
,
3671 release_mask
= release_granularity
-1,
3673 aligned_from
= (from
+release_mask
)&~release_mask
,
3674 aligned_end
= (end
&~release_mask
);
3676 if (aligned_from
< aligned_end
) {
3677 zero_pages_with_mmap(aligned_from
, aligned_end
-1);
3678 if (aligned_from
!= from
)
3679 zero_and_mark_pages(from
, aligned_from
-1);
3680 if (aligned_end
!= end
)
3681 zero_and_mark_pages(aligned_end
, end
-1);
3683 zero_and_mark_pages(from
, to
);
3689 remap_free_pages (page_index_t from
, page_index_t to
)
3691 page_index_t first_page
, last_page
;
3693 for (first_page
= from
; first_page
<= to
; first_page
++) {
3694 if (!page_free_p(first_page
) || !page_need_to_zero(first_page
))
3697 last_page
= first_page
+ 1;
3698 while (page_free_p(last_page
) &&
3699 (last_page
<= to
) &&
3700 (page_need_to_zero(last_page
)))
3703 remap_page_range(first_page
, last_page
-1);
3705 first_page
= last_page
;
3709 generation_index_t small_generation_limit
= 1;
3711 /* GC all generations newer than last_gen, raising the objects in each
3712 * to the next older generation - we finish when all generations below
3713 * last_gen are empty. Then if last_gen is due for a GC, or if
3714 * last_gen==NUM_GENERATIONS (the scratch generation? eh?) we GC that
3715 * too. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3717 * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3718 * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3720 collect_garbage(generation_index_t last_gen
)
3722 generation_index_t gen
= 0, i
;
3723 boolean gc_mark_only
= 0;
3724 int raise
, more
= 0;
3726 /* The largest value of last_free_page seen since the time
3727 * remap_free_pages was called. */
3728 static page_index_t high_water_mark
= 0;
3730 FSHOW((stderr
, "/entering collect_garbage(%d)\n", last_gen
));
3731 log_generation_stats(gc_logfile
, "=== GC Start ===");
3735 if (last_gen
== 1+PSEUDO_STATIC_GENERATION
) {
3736 // Pseudostatic space undergoes a non-moving collection
3737 last_gen
= PSEUDO_STATIC_GENERATION
;
3739 } else if (last_gen
> 1+PSEUDO_STATIC_GENERATION
) {
3740 // This is a completely non-obvious thing to do, but whatever...
3742 "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3747 /* Flush the alloc regions updating the tables. */
3748 gc_alloc_update_all_page_tables(1);
3750 /* Verify the new objects created by Lisp code. */
3751 if (pre_verify_gen_0
) {
3752 FSHOW((stderr
, "pre-checking generation 0\n"));
3753 verify_generation(0, 0);
3756 if (gencgc_verbose
> 1)
3757 print_generation_stats();
3759 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3760 /* Immobile space generation bits are lazily updated for gen0
3761 (not touched on every object allocation) so do it now */
3762 update_immobile_nursery_bits();
3766 garbage_collect_generation(PSEUDO_STATIC_GENERATION
, 0);
3771 /* Collect the generation. */
3773 if (more
|| (gen
>= gencgc_oldest_gen_to_gc
)) {
3774 /* Never raise the oldest generation. Never raise the extra generation
3775 * collected due to more-flag. */
3781 || (generations
[gen
].num_gc
>= generations
[gen
].number_of_gcs_before_promotion
);
3782 /* If we would not normally raise this one, but we're
3783 * running low on space in comparison to the object-sizes
3784 * we've been seeing, raise it and collect the next one
3786 if (!raise
&& gen
== last_gen
) {
3787 more
= (2*large_allocation
) >= (dynamic_space_size
- bytes_allocated
);
3792 if (gencgc_verbose
> 1) {
3794 "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3797 generations
[gen
].bytes_allocated
,
3798 generations
[gen
].gc_trigger
,
3799 generations
[gen
].num_gc
));
3802 /* If an older generation is being filled, then update its
3805 generations
[gen
+1].cum_sum_bytes_allocated
+=
3806 generations
[gen
+1].bytes_allocated
;
3809 garbage_collect_generation(gen
, raise
);
3811 /* Reset the memory age cum_sum. */
3812 generations
[gen
].cum_sum_bytes_allocated
= 0;
3814 if (gencgc_verbose
> 1) {
3815 FSHOW((stderr
, "GC of generation %d finished:\n", gen
));
3816 print_generation_stats();
3820 } while ((gen
<= gencgc_oldest_gen_to_gc
)
3821 && ((gen
< last_gen
)
3824 && (generations
[gen
].bytes_allocated
3825 > generations
[gen
].gc_trigger
)
3826 && (generation_average_age(gen
)
3827 > generations
[gen
].minimum_age_before_gc
))));
3829 /* Now if gen-1 was raised all generations before gen are empty.
3830 * If it wasn't raised then all generations before gen-1 are empty.
3832 * Now objects within this gen's pages cannot point to younger
3833 * generations unless they are written to. This can be exploited
3834 * by write-protecting the pages of gen; then when younger
3835 * generations are GCed only the pages which have been written
3840 gen_to_wp
= gen
- 1;
3842 /* There's not much point in WPing pages in generation 0 as it is
3843 * never scavenged (except promoted pages). */
3844 if ((gen_to_wp
> 0) && ENABLE_PAGE_PROTECTION
) {
3845 /* Check that they are all empty. */
3846 for (i
= 0; i
< gen_to_wp
; i
++) {
3847 if (generations
[i
].bytes_allocated
)
3848 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
3851 write_protect_generation_pages(gen_to_wp
);
3854 /* Set gc_alloc() back to generation 0. The current regions should
3855 * be flushed after the above GCs. */
3856 gc_assert(boxed_region
.free_pointer
== boxed_region
.start_addr
);
3857 gc_alloc_generation
= 0;
3859 /* Save the high-water mark before updating last_free_page */
3860 if (last_free_page
> high_water_mark
)
3861 high_water_mark
= last_free_page
;
3863 update_dynamic_space_free_pointer();
3865 /* Update auto_gc_trigger. Make sure we trigger the next GC before
3866 * running out of heap! */
3867 if (bytes_consed_between_gcs
<= (dynamic_space_size
- bytes_allocated
))
3868 auto_gc_trigger
= bytes_allocated
+ bytes_consed_between_gcs
;
3870 auto_gc_trigger
= bytes_allocated
+ (dynamic_space_size
- bytes_allocated
)/2;
3872 if(gencgc_verbose
) {
3873 #define MESSAGE ("Next gc when %"OS_VM_SIZE_FMT" bytes have been consed\n")
3876 // fprintf() can - and does - cause deadlock here.
3877 // snprintf() seems to work fine.
3878 n
= snprintf(buf
, sizeof buf
, MESSAGE
, auto_gc_trigger
);
3879 ignore_value(write(2, buf
, n
));
3883 /* If we did a big GC (arbitrarily defined as gen > 1), release memory
3886 if (gen
> small_generation_limit
) {
3887 if (last_free_page
> high_water_mark
)
3888 high_water_mark
= last_free_page
;
3889 remap_free_pages(0, high_water_mark
);
3890 high_water_mark
= 0;
3893 large_allocation
= 0;
3895 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3896 write_protect_immobile_space();
3900 #ifdef LISP_FEATURE_SB_TRACEROOT
3901 if (gc_object_watcher
) {
3902 extern void gc_prove_liveness(void(*)(), lispobj
, int, uword_t
*, int);
3903 gc_prove_liveness(preserve_context_registers
,
3905 gc_n_stack_pins
, pinned_objects
.keys
,
3906 gc_traceroot_criterion
);
3910 log_generation_stats(gc_logfile
, "=== GC End ===");
3911 SHOW("returning from collect_garbage");
3914 /* Initialization of gencgc metadata is split into three steps:
3915 * 1. gc_init() - allocation of a fixed-address space via mmap(),
3916 * failing which there's no reason to go on. (safepoint only)
3917 * 2. gc_allocate_ptes() - page table entries
3918 * 3. gencgc_pickup_dynamic() - calculation of scan start offsets
3919 * Steps (2) and (3) are combined in self-build because there is
3920 * no PAGE_TABLE_CORE_ENTRY_TYPE_CODE core entry. */
3924 #if defined(LISP_FEATURE_SB_SAFEPOINT)
3929 void gc_allocate_ptes()
3933 /* Compute the number of pages needed for the dynamic space.
3934 * Dynamic space size should be aligned on page size. */
3935 page_table_pages
= dynamic_space_size
/GENCGC_CARD_BYTES
;
3936 gc_assert(dynamic_space_size
== npage_bytes(page_table_pages
));
3938 /* Default nursery size to 5% of the total dynamic space size,
3940 bytes_consed_between_gcs
= dynamic_space_size
/(os_vm_size_t
)20;
3941 if (bytes_consed_between_gcs
< (1024*1024))
3942 bytes_consed_between_gcs
= 1024*1024;
3944 /* The page_table is allocated using "calloc" to zero-initialize it.
3945 * The C library typically implements this efficiently with mmap() if the
3946 * size is large enough. To further avoid touching each page structure
3947 * until first use, FREE_PAGE_FLAG must be 0, statically asserted here:
3950 /* Compile time assertion: If triggered, declares an array
3951 * of dimension -1 forcing a syntax error. The intent of the
3952 * assignment is to avoid an "unused variable" warning. */
3953 char __attribute__((unused
)) assert_free_page_flag_0
[(FREE_PAGE_FLAG
) ? -1 : 1];
3955 /* An extra struct exists as the end as a sentinel. Its 'scan_start_offset'
3956 * and 'bytes_used' must be zero.
3957 * Doing so avoids testing in page_ends_contiguous_block_p() whether the
3958 * next page_index is within bounds, and whether that page contains data.
3960 page_table
= calloc(1+page_table_pages
, sizeof(struct page
));
3961 gc_assert(page_table
);
3964 #ifdef PIN_GRANULARITY_LISPOBJ
3965 hopscotch_create(&pinned_objects
, HOPSCOTCH_HASH_FUN_DEFAULT
, 0 /* hashset */,
3966 32 /* logical bin count */, 0 /* default range */);
3969 scavtab
[WEAK_POINTER_WIDETAG
] = scav_weak_pointer
;
3971 bytes_allocated
= 0;
3973 /* Initialize the generations. */
3974 for (i
= 0; i
< NUM_GENERATIONS
; i
++) {
3975 generations
[i
].alloc_start_page
= 0;
3976 generations
[i
].alloc_unboxed_start_page
= 0;
3977 generations
[i
].alloc_large_start_page
= 0;
3978 generations
[i
].bytes_allocated
= 0;
3979 generations
[i
].gc_trigger
= 2000000;
3980 generations
[i
].num_gc
= 0;
3981 generations
[i
].cum_sum_bytes_allocated
= 0;
3982 /* the tune-able parameters */
3983 generations
[i
].bytes_consed_between_gc
3984 = bytes_consed_between_gcs
/(os_vm_size_t
)HIGHEST_NORMAL_GENERATION
;
3985 generations
[i
].number_of_gcs_before_promotion
= 1;
3986 generations
[i
].minimum_age_before_gc
= 0.75;
3989 /* Initialize gc_alloc. */
3990 gc_alloc_generation
= 0;
3991 gc_set_region_empty(&boxed_region
);
3992 gc_set_region_empty(&unboxed_region
);
3993 #ifdef LISP_FEATURE_SEGREGATED_CODE
3994 gc_set_region_empty(&code_region
);
4000 /* Pick up the dynamic space from after a core load.
4002 * The ALLOCATION_POINTER points to the end of the dynamic space.
4006 gencgc_pickup_dynamic(void)
4008 page_index_t page
= 0;
4009 char *alloc_ptr
= (char *)get_alloc_pointer();
4010 lispobj
*prev
=(lispobj
*)page_address(page
);
4011 generation_index_t gen
= PSEUDO_STATIC_GENERATION
;
4013 bytes_allocated
= 0;
4016 lispobj
*first
,*ptr
= (lispobj
*)page_address(page
);
4018 if (!gencgc_partial_pickup
|| !page_free_p(page
)) {
4019 page_bytes_t bytes_used
= GENCGC_CARD_BYTES
;
4020 /* It is possible, though rare, for the saved page table
4021 * to contain free pages below alloc_ptr. */
4022 page_table
[page
].gen
= gen
;
4023 if (gencgc_partial_pickup
)
4024 bytes_used
= page_bytes_used(page
);
4026 set_page_bytes_used(page
, GENCGC_CARD_BYTES
);
4027 page_table
[page
].large_object
= 0;
4028 page_table
[page
].write_protected
= 0;
4029 page_table
[page
].write_protected_cleared
= 0;
4030 page_table
[page
].dont_move
= 0;
4031 set_page_need_to_zero(page
, 1);
4033 bytes_allocated
+= bytes_used
;
4036 if (!gencgc_partial_pickup
) {
4037 #ifdef LISP_FEATURE_SEGREGATED_CODE
4038 // Make the most general assumption: any page *might* contain code.
4039 page_table
[page
].allocated
= CODE_PAGE_FLAG
;
4041 page_table
[page
].allocated
= BOXED_PAGE_FLAG
;
4043 first
= gc_search_space3(ptr
, prev
, (ptr
+2));
4046 set_page_scan_start_offset(page
, page_address(page
) - (char*)prev
);
4049 } while (page_address(page
) < alloc_ptr
);
4051 last_free_page
= page
;
4053 generations
[gen
].bytes_allocated
= bytes_allocated
;
4055 gc_alloc_update_all_page_tables(1);
4056 if (ENABLE_PAGE_PROTECTION
)
4057 write_protect_generation_pages(gen
);
4061 gc_initialize_pointers(void)
4063 /* !page_table_pages happens once only in self-build and not again */
4064 if (!page_table_pages
)
4066 gencgc_pickup_dynamic();
4070 /* alloc(..) is the external interface for memory allocation. It
4071 * allocates to generation 0. It is not called from within the garbage
4072 * collector as it is only external uses that need the check for heap
4073 * size (GC trigger) and to disable the interrupts (interrupts are
4074 * always disabled during a GC).
4076 * The vops that call alloc(..) assume that the returned space is zero-filled.
4077 * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4079 * The check for a GC trigger is only performed when the current
4080 * region is full, so in most cases it's not needed. */
4082 static inline lispobj
*
4083 general_alloc_internal(sword_t nbytes
, int page_type_flag
, struct alloc_region
*region
,
4084 struct thread
*thread
)
4086 #ifndef LISP_FEATURE_WIN32
4087 lispobj alloc_signal
;
4090 void *new_free_pointer
;
4091 os_vm_size_t trigger_bytes
= 0;
4093 gc_assert(nbytes
> 0);
4095 /* Check for alignment allocation problems. */
4096 gc_assert((((uword_t
)region
->free_pointer
& LOWTAG_MASK
) == 0)
4097 && ((nbytes
& LOWTAG_MASK
) == 0));
4099 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
4100 /* Must be inside a PA section. */
4101 gc_assert(get_pseudo_atomic_atomic(thread
));
4104 if ((os_vm_size_t
) nbytes
> large_allocation
)
4105 large_allocation
= nbytes
;
4107 /* maybe we can do this quickly ... */
4108 new_free_pointer
= (char*)region
->free_pointer
+ nbytes
;
4109 if (new_free_pointer
<= region
->end_addr
) {
4110 new_obj
= (void*)(region
->free_pointer
);
4111 region
->free_pointer
= new_free_pointer
;
4112 return(new_obj
); /* yup */
4115 /* We don't want to count nbytes against auto_gc_trigger unless we
4116 * have to: it speeds up the tenuring of objects and slows down
4117 * allocation. However, unless we do so when allocating _very_
4118 * large objects we are in danger of exhausting the heap without
4119 * running sufficient GCs.
4121 if ((os_vm_size_t
) nbytes
>= bytes_consed_between_gcs
)
4122 trigger_bytes
= nbytes
;
4124 /* we have to go the long way around, it seems. Check whether we
4125 * should GC in the near future
4127 if (auto_gc_trigger
&& (bytes_allocated
+trigger_bytes
> auto_gc_trigger
)) {
4128 /* Don't flood the system with interrupts if the need to gc is
4129 * already noted. This can happen for example when SUB-GC
4130 * allocates or after a gc triggered in a WITHOUT-GCING. */
4131 if (read_TLS(GC_PENDING
,thread
) == NIL
) {
4132 /* set things up so that GC happens when we finish the PA
4134 write_TLS(GC_PENDING
,T
,thread
);
4135 if (read_TLS(GC_INHIBIT
,thread
) == NIL
) {
4136 #ifdef LISP_FEATURE_SB_SAFEPOINT
4137 thread_register_gc_trigger();
4139 set_pseudo_atomic_interrupted(thread
);
4140 #if GENCGC_IS_PRECISE
4141 /* PPC calls alloc() from a trap
4142 * look up the most context if it's from a trap. */
4144 os_context_t
*context
=
4145 thread
->interrupt_data
->allocation_trap_context
;
4146 maybe_save_gc_mask_and_block_deferrables
4147 (context
? os_context_sigmask_addr(context
) : NULL
);
4150 maybe_save_gc_mask_and_block_deferrables(NULL
);
4156 new_obj
= gc_alloc_with_region(nbytes
, page_type_flag
, region
, 0);
4158 #ifndef LISP_FEATURE_WIN32
4159 /* for sb-prof, and not supported on Windows yet */
4160 alloc_signal
= read_TLS(ALLOC_SIGNAL
,thread
);
4161 if ((alloc_signal
& FIXNUM_TAG_MASK
) == 0) {
4162 if ((sword_t
) alloc_signal
<= 0) {
4163 write_TLS(ALLOC_SIGNAL
, T
, thread
);
4166 write_TLS(ALLOC_SIGNAL
,
4167 alloc_signal
- (1 << N_FIXNUM_TAG_BITS
),
4177 general_alloc(sword_t nbytes
, int page_type_flag
)
4179 struct thread
*thread
= arch_os_get_current_thread();
4180 /* Select correct region, and call general_alloc_internal with it.
4181 * For other then boxed allocation we must lock first, since the
4182 * region is shared. */
4183 #ifdef LISP_FEATURE_SEGREGATED_CODE
4184 if (page_type_flag
== BOXED_PAGE_FLAG
) {
4186 if (BOXED_PAGE_FLAG
& page_type_flag
) {
4188 #ifdef LISP_FEATURE_SB_THREAD
4189 struct alloc_region
*region
= (thread
? &(thread
->alloc_region
) : &boxed_region
);
4191 struct alloc_region
*region
= &boxed_region
;
4193 return general_alloc_internal(nbytes
, page_type_flag
, region
, thread
);
4194 #ifdef LISP_FEATURE_SEGREGATED_CODE
4195 } else if (page_type_flag
== UNBOXED_PAGE_FLAG
||
4196 page_type_flag
== CODE_PAGE_FLAG
) {
4197 struct alloc_region
*region
=
4198 page_type_flag
== CODE_PAGE_FLAG
? &code_region
: &unboxed_region
;
4200 } else if (UNBOXED_PAGE_FLAG
== page_type_flag
) {
4201 struct alloc_region
*region
= &unboxed_region
;
4205 result
= thread_mutex_lock(&allocation_lock
);
4207 obj
= general_alloc_internal(nbytes
, page_type_flag
, region
, thread
);
4208 result
= thread_mutex_unlock(&allocation_lock
);
4212 lose("bad page type flag: %d", page_type_flag
);
4216 lispobj AMD64_SYSV_ABI
*
4217 alloc(sword_t nbytes
)
4219 #ifdef LISP_FEATURE_SB_SAFEPOINT_STRICTLY
4220 struct thread
*self
= arch_os_get_current_thread();
4221 int was_pseudo_atomic
= get_pseudo_atomic_atomic(self
);
4222 if (!was_pseudo_atomic
)
4223 set_pseudo_atomic_atomic(self
);
4225 gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4228 lispobj
*result
= general_alloc(nbytes
, BOXED_PAGE_FLAG
);
4230 #ifdef LISP_FEATURE_SB_SAFEPOINT_STRICTLY
4231 if (!was_pseudo_atomic
)
4232 clear_pseudo_atomic_atomic(self
);
4239 * shared support for the OS-dependent signal handlers which
4240 * catch GENCGC-related write-protect violations
4242 void unhandled_sigmemoryfault(void* addr
);
4244 /* Depending on which OS we're running under, different signals might
4245 * be raised for a violation of write protection in the heap. This
4246 * function factors out the common generational GC magic which needs
4247 * to invoked in this case, and should be called from whatever signal
4248 * handler is appropriate for the OS we're running under.
4250 * Return true if this signal is a normal generational GC thing that
4251 * we were able to handle, or false if it was abnormal and control
4252 * should fall through to the general SIGSEGV/SIGBUS/whatever logic.
4254 * We have two control flags for this: one causes us to ignore faults
4255 * on unprotected pages completely, and the second complains to stderr
4256 * but allows us to continue without losing.
4258 extern boolean ignore_memoryfaults_on_unprotected_pages
;
4259 boolean ignore_memoryfaults_on_unprotected_pages
= 0;
4261 extern boolean continue_after_memoryfault_on_unprotected_pages
;
4262 boolean continue_after_memoryfault_on_unprotected_pages
= 0;
4265 gencgc_handle_wp_violation(void* fault_addr
)
4267 page_index_t page_index
= find_page_index(fault_addr
);
4271 "heap WP violation? fault_addr=%p, page_index=%"PAGE_INDEX_FMT
"\n",
4272 fault_addr
, page_index
));
4275 /* Check whether the fault is within the dynamic space. */
4276 if (page_index
== (-1)) {
4277 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4278 extern int immobile_space_handle_wp_violation(void*);
4279 if (immobile_space_handle_wp_violation(fault_addr
))
4283 /* It can be helpful to be able to put a breakpoint on this
4284 * case to help diagnose low-level problems. */
4285 unhandled_sigmemoryfault(fault_addr
);
4287 /* not within the dynamic space -- not our responsibility */
4292 ret
= thread_mutex_lock(&free_pages_lock
);
4293 gc_assert(ret
== 0);
4294 if (page_table
[page_index
].write_protected
) {
4295 /* Unprotect the page. */
4296 os_protect(page_address(page_index
), GENCGC_CARD_BYTES
, OS_VM_PROT_ALL
);
4297 page_table
[page_index
].write_protected_cleared
= 1;
4298 page_table
[page_index
].write_protected
= 0;
4299 } else if (!ignore_memoryfaults_on_unprotected_pages
) {
4300 /* The only acceptable reason for this signal on a heap
4301 * access is that GENCGC write-protected the page.
4302 * However, if two CPUs hit a wp page near-simultaneously,
4303 * we had better not have the second one lose here if it
4304 * does this test after the first one has already set wp=0
4306 if(page_table
[page_index
].write_protected_cleared
!= 1) {
4307 void lisp_backtrace(int frames
);
4310 "Fault @ %p, page %"PAGE_INDEX_FMT
" not marked as write-protected:\n"
4311 " boxed_region.first_page: %"PAGE_INDEX_FMT
","
4312 " boxed_region.last_page %"PAGE_INDEX_FMT
"\n"
4313 " page.scan_start_offset: %"OS_VM_SIZE_FMT
"\n"
4314 " page.bytes_used: %u\n"
4315 " page.allocated: %d\n"
4316 " page.write_protected: %d\n"
4317 " page.write_protected_cleared: %d\n"
4318 " page.generation: %d\n",
4321 boxed_region
.first_page
,
4322 boxed_region
.last_page
,
4323 page_scan_start_offset(page_index
),
4324 page_bytes_used(page_index
),
4325 page_table
[page_index
].allocated
,
4326 page_table
[page_index
].write_protected
,
4327 page_table
[page_index
].write_protected_cleared
,
4328 page_table
[page_index
].gen
);
4329 if (!continue_after_memoryfault_on_unprotected_pages
)
4333 ret
= thread_mutex_unlock(&free_pages_lock
);
4334 gc_assert(ret
== 0);
4335 /* Don't worry, we can handle it. */
4339 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4340 * it's not just a case of the program hitting the write barrier, and
4341 * are about to let Lisp deal with it. It's basically just a
4342 * convenient place to set a gdb breakpoint. */
4344 unhandled_sigmemoryfault(void *addr
)
4348 update_thread_page_tables(struct thread
*th
)
4350 gc_alloc_update_page_tables(BOXED_PAGE_FLAG
, &th
->alloc_region
);
4351 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
4352 gc_alloc_update_page_tables(BOXED_PAGE_FLAG
, &th
->sprof_alloc_region
);
4356 /* GC is single-threaded and all memory allocations during a
4357 collection happen in the GC thread, so it is sufficient to update
4358 all the the page tables once at the beginning of a collection and
4359 update only page tables of the GC thread during the collection. */
4360 void gc_alloc_update_all_page_tables(int for_all_threads
)
4362 /* Flush the alloc regions updating the tables. */
4364 if (for_all_threads
) {
4365 for_each_thread(th
) {
4366 update_thread_page_tables(th
);
4370 th
= arch_os_get_current_thread();
4372 update_thread_page_tables(th
);
4375 #ifdef LISP_FEATURE_SEGREGATED_CODE
4376 gc_alloc_update_page_tables(CODE_PAGE_FLAG
, &code_region
);
4378 gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG
, &unboxed_region
);
4379 gc_alloc_update_page_tables(BOXED_PAGE_FLAG
, &boxed_region
);
4383 gc_set_region_empty(struct alloc_region
*region
)
4385 region
->first_page
= 0;
4386 region
->last_page
= -1;
4387 region
->start_addr
= page_address(0);
4388 region
->free_pointer
= page_address(0);
4389 region
->end_addr
= page_address(0);
4393 zero_all_free_pages() /* called only by gc_and_save() */
4397 for (i
= 0; i
< last_free_page
; i
++) {
4398 if (page_free_p(i
)) {
4399 #ifdef READ_PROTECT_FREE_PAGES
4400 os_protect(page_address(i
), GENCGC_CARD_BYTES
, OS_VM_PROT_ALL
);
4407 /* Things to do before doing a final GC before saving a core (without
4410 * + Pages in large_object pages aren't moved by the GC, so we need to
4411 * unset that flag from all pages.
4412 * + The pseudo-static generation isn't normally collected, but it seems
4413 * reasonable to collect it at least when saving a core. So move the
4414 * pages to a normal generation.
4417 prepare_for_final_gc ()
4421 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4422 extern void prepare_immobile_space_for_final_gc();
4423 prepare_immobile_space_for_final_gc ();
4425 for (i
= 0; i
< last_free_page
; i
++) {
4426 page_table
[i
].large_object
= 0;
4427 if (page_table
[i
].gen
== PSEUDO_STATIC_GENERATION
) {
4428 int used
= page_bytes_used(i
);
4429 page_table
[i
].gen
= HIGHEST_NORMAL_GENERATION
;
4430 generations
[PSEUDO_STATIC_GENERATION
].bytes_allocated
-= used
;
4431 generations
[HIGHEST_NORMAL_GENERATION
].bytes_allocated
+= used
;
4434 #ifdef PINNED_OBJECTS
4436 for_each_thread(th
) {
4437 write_TLS(PINNED_OBJECTS
, NIL
, th
);
4442 /* Set this switch to 1 for coalescing of strings dumped to fasl,
4443 * or 2 for coalescing of those,
4444 * plus literal strings in code compiled to memory. */
4445 char gc_coalesce_string_literals
= 0;
4447 /* Do a non-conservative GC, and then save a core with the initial
4448 * function being set to the value of 'lisp_init_function' */
4450 gc_and_save(char *filename
, boolean prepend_runtime
,
4451 boolean save_runtime_options
, boolean compressed
,
4452 int compression_level
, int application_type
)
4455 void *runtime_bytes
= NULL
;
4456 size_t runtime_size
;
4457 extern void coalesce_similar_objects();
4458 extern struct lisp_startup_options lisp_startup_options
;
4459 boolean verbose
= !lisp_startup_options
.noinform
;
4461 file
= prepare_to_save(filename
, prepend_runtime
, &runtime_bytes
,
4466 conservative_stack
= 0;
4468 /* The filename might come from Lisp, and be moved by the now
4469 * non-conservative GC. */
4470 filename
= strdup(filename
);
4472 /* We're committed to process death at this point, and interrupts can not
4473 * possibly be handled in Lisp. Let the installed handler closures become
4474 * garbage, since new ones will be made by ENABLE-INTERRUPT on restart */
4475 #ifndef LISP_FEATURE_WIN32
4478 for (i
=0; i
<NSIG
; ++i
)
4479 if (lowtag_of(interrupt_handlers
[i
].lisp
) == FUN_POINTER_LOWTAG
)
4480 interrupt_handlers
[i
].lisp
= 0;
4484 /* Collect twice: once into relatively high memory, and then back
4485 * into low memory. This compacts the retained data into the lower
4486 * pages, minimizing the size of the core file.
4488 prepare_for_final_gc();
4489 gencgc_alloc_start_page
= last_free_page
;
4490 collect_garbage(HIGHEST_NORMAL_GENERATION
+1);
4492 // We always coalesce copyable numbers. Addional coalescing is done
4493 // only on request, in which case a message is shown (unless verbose=0).
4494 if (gc_coalesce_string_literals
&& verbose
) {
4495 printf("[coalescing similar vectors... ");
4498 coalesce_similar_objects();
4499 if (gc_coalesce_string_literals
&& verbose
)
4502 /* FIXME: now that relocate_heap() works, can we just memmove() everything
4503 * down and perform a relocation instead of a collection? */
4504 prepare_for_final_gc();
4505 gencgc_alloc_start_page
= -1;
4506 collect_garbage(HIGHEST_NORMAL_GENERATION
+1);
4508 if (prepend_runtime
)
4509 save_runtime_to_filehandle(file
, runtime_bytes
, runtime_size
,
4512 /* The dumper doesn't know that pages need to be zeroed before use. */
4513 zero_all_free_pages();
4514 save_to_filehandle(file
, filename
, lisp_init_function
,
4515 prepend_runtime
, save_runtime_options
,
4516 compressed
? compression_level
: COMPRESSION_LEVEL_NONE
);
4517 /* Oops. Save still managed to fail. Since we've mangled the stack
4518 * beyond hope, there's not much we can do.
4519 * (beyond FUNCALLing lisp_init_function, but I suspect that's
4520 * going to be rather unsatisfactory too... */
4521 lose("Attempt to save core after non-conservative GC failed.\n");