Add :IMMOBILE-CODE feature.
[sbcl.git] / src / runtime / gencgc.c
blob6dc884992c3d821c11240c887f3adb12d4688f8b
1 /*
2 * GENerational Conservative Garbage Collector for SBCL
3 */
5 /*
6 * This software is part of the SBCL system. See the README file for
7 * more information.
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>
23 * as
24 * <ftp://ftp.cs.utexas.edu/pub/garbage/bigsurv.ps>.
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <errno.h>
30 #include <string.h>
31 #include "sbcl.h"
32 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
33 #include "pthreads_win32.h"
34 #else
35 #include <signal.h>
36 #endif
37 #include "runtime.h"
38 #include "os.h"
39 #include "interr.h"
40 #include "globals.h"
41 #include "interrupt.h"
42 #include "validate.h"
43 #include "lispregs.h"
44 #include "arch.h"
45 #include "gc.h"
46 #include "gc-internal.h"
47 #include "thread.h"
48 #include "pseudo-atomic.h"
49 #include "alloc.h"
50 #include "genesis/vector.h"
51 #include "genesis/weak-pointer.h"
52 #include "genesis/fdefn.h"
53 #include "genesis/simple-fun.h"
54 #include "save.h"
55 #include "genesis/hash-table.h"
56 #include "genesis/instance.h"
57 #include "genesis/layout.h"
58 #include "gencgc.h"
59 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
60 #include "genesis/cons.h"
61 #endif
63 /* forward declarations */
64 page_index_t gc_find_freeish_pages(page_index_t *restart_page_ptr, sword_t nbytes,
65 int page_type_flag);
69 * GC parameters
72 /* As usually configured, generations 0-5 are normal collected generations,
73 6 is pseudo-static (the objects in which are never moved nor reclaimed),
74 and 7 is scratch space used when collecting a generation without promotion,
75 wherein it is moved to generation 7 and back again.
77 enum {
78 SCRATCH_GENERATION = PSEUDO_STATIC_GENERATION+1,
79 NUM_GENERATIONS
82 /* Should we use page protection to help avoid the scavenging of pages
83 * that don't have pointers to younger generations? */
84 boolean enable_page_protection = 1;
86 /* Largest allocation seen since last GC. */
87 os_vm_size_t large_allocation = 0;
91 * debugging
94 /* the verbosity level. All non-error messages are disabled at level 0;
95 * and only a few rare messages are printed at level 1. */
96 #if QSHOW == 2
97 boolean gencgc_verbose = 1;
98 #else
99 boolean gencgc_verbose = 0;
100 #endif
102 /* FIXME: At some point enable the various error-checking things below
103 * and see what they say. */
105 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
106 * Set verify_gens to HIGHEST_NORMAL_GENERATION + 1 to disable this kind of
107 * check. */
108 generation_index_t verify_gens = HIGHEST_NORMAL_GENERATION + 1;
110 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
111 boolean pre_verify_gen_0 = 0;
113 /* Should we check for bad pointers after gc_free_heap is called
114 * from Lisp PURIFY? */
115 boolean verify_after_free_heap = 0;
117 /* Should we print a note when code objects are found in the dynamic space
118 * during a heap verify? */
119 boolean verify_dynamic_code_check = 0;
121 #ifdef LISP_FEATURE_X86
122 /* Should we check code objects for fixup errors after they are transported? */
123 boolean check_code_fixups = 0;
124 #endif
126 /* Should we check that newly allocated regions are zero filled? */
127 boolean gencgc_zero_check = 0;
129 /* Should we check that the free space is zero filled? */
130 boolean gencgc_enable_verify_zero_fill = 0;
132 /* Should we check that free pages are zero filled during gc_free_heap
133 * called after Lisp PURIFY? */
134 boolean gencgc_zero_check_during_free_heap = 0;
136 /* When loading a core, don't do a full scan of the memory for the
137 * memory region boundaries. (Set to true by coreparse.c if the core
138 * contained a pagetable entry).
140 boolean gencgc_partial_pickup = 0;
142 /* If defined, free pages are read-protected to ensure that nothing
143 * accesses them.
146 /* #define READ_PROTECT_FREE_PAGES */
150 * GC structures and variables
153 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
154 os_vm_size_t bytes_allocated = 0;
155 os_vm_size_t auto_gc_trigger = 0;
157 /* the source and destination generations. These are set before a GC starts
158 * scavenging. */
159 generation_index_t from_space;
160 generation_index_t new_space;
162 /* Set to 1 when in GC */
163 boolean gc_active_p = 0;
165 /* should the GC be conservative on stack. If false (only right before
166 * saving a core), don't scan the stack / mark pages dont_move. */
167 static boolean conservative_stack = 1;
169 /* An array of page structures is allocated on gc initialization.
170 * This helps to quickly map between an address and its page structure.
171 * page_table_pages is set from the size of the dynamic space. */
172 page_index_t page_table_pages;
173 struct page *page_table;
175 in_use_marker_t *page_table_pinned_dwords;
176 size_t pins_map_size_in_bytes;
178 /* In GC cards that have conservative pointers to them, should we wipe out
179 * dwords in there that are not used, so that they do not act as false
180 * root to other things in the heap from then on? This is a new feature
181 * but in testing it is both reliable and no noticeable slowdown. */
182 int do_wipe_p = 1;
184 static inline boolean page_allocated_p(page_index_t page) {
185 return (page_table[page].allocated != FREE_PAGE_FLAG);
188 static inline boolean page_no_region_p(page_index_t page) {
189 return !(page_table[page].allocated & OPEN_REGION_PAGE_FLAG);
192 static inline boolean page_allocated_no_region_p(page_index_t page) {
193 return ((page_table[page].allocated & (UNBOXED_PAGE_FLAG | BOXED_PAGE_FLAG))
194 && page_no_region_p(page));
197 static inline boolean page_free_p(page_index_t page) {
198 return (page_table[page].allocated == FREE_PAGE_FLAG);
201 static inline boolean page_boxed_p(page_index_t page) {
202 return (page_table[page].allocated & BOXED_PAGE_FLAG);
205 static inline boolean page_boxed_no_region_p(page_index_t page) {
206 return page_boxed_p(page) && page_no_region_p(page);
209 static inline boolean page_unboxed_p(page_index_t page) {
210 /* Both flags set == boxed code page */
211 return ((page_table[page].allocated & UNBOXED_PAGE_FLAG)
212 && !page_boxed_p(page));
215 static inline boolean protect_page_p(page_index_t page, generation_index_t generation) {
216 return (page_boxed_no_region_p(page)
217 && (page_table[page].bytes_used != 0)
218 && !page_table[page].dont_move
219 && (page_table[page].gen == generation));
222 /* To map addresses to page structures the address of the first page
223 * is needed. */
224 void *heap_base = NULL;
226 /* Calculate the start address for the given page number. */
227 inline void *
228 page_address(page_index_t page_num)
230 return (heap_base + (page_num * GENCGC_CARD_BYTES));
233 /* Calculate the address where the allocation region associated with
234 * the page starts. */
235 static inline void *
236 page_scan_start(page_index_t page_index)
238 return page_address(page_index)-page_table[page_index].scan_start_offset;
241 /* True if the page starts a contiguous block. */
242 static inline boolean
243 page_starts_contiguous_block_p(page_index_t page_index)
245 return page_table[page_index].scan_start_offset == 0;
248 /* True if the page is the last page in a contiguous block. */
249 static inline boolean
250 page_ends_contiguous_block_p(page_index_t page_index, generation_index_t gen)
252 return (/* page doesn't fill block */
253 (page_table[page_index].bytes_used < GENCGC_CARD_BYTES)
254 /* page is last allocated page */
255 || ((page_index + 1) >= last_free_page)
256 /* next page free */
257 || page_free_p(page_index + 1)
258 /* next page contains no data */
259 || (page_table[page_index + 1].bytes_used == 0)
260 /* next page is in different generation */
261 || (page_table[page_index + 1].gen != gen)
262 /* next page starts its own contiguous block */
263 || (page_starts_contiguous_block_p(page_index + 1)));
266 /* Find the page index within the page_table for the given
267 * address. Return -1 on failure. */
268 inline page_index_t
269 find_page_index(void *addr)
271 if (addr >= heap_base) {
272 page_index_t index = ((pointer_sized_uint_t)addr -
273 (pointer_sized_uint_t)heap_base) / GENCGC_CARD_BYTES;
274 if (index < page_table_pages)
275 return (index);
277 return (-1);
280 static os_vm_size_t
281 npage_bytes(page_index_t npages)
283 gc_assert(npages>=0);
284 return ((os_vm_size_t)npages)*GENCGC_CARD_BYTES;
287 /* Check that X is a higher address than Y and return offset from Y to
288 * X in bytes. */
289 static inline os_vm_size_t
290 void_diff(void *x, void *y)
292 gc_assert(x >= y);
293 return (pointer_sized_uint_t)x - (pointer_sized_uint_t)y;
296 /* a structure to hold the state of a generation
298 * CAUTION: If you modify this, make sure to touch up the alien
299 * definition in src/code/gc.lisp accordingly. ...or better yes,
300 * deal with the FIXME there...
302 struct generation {
304 /* the first page that gc_alloc() checks on its next call */
305 page_index_t alloc_start_page;
307 /* the first page that gc_alloc_unboxed() checks on its next call */
308 page_index_t alloc_unboxed_start_page;
310 /* the first page that gc_alloc_large (boxed) considers on its next
311 * call. (Although it always allocates after the boxed_region.) */
312 page_index_t alloc_large_start_page;
314 /* the first page that gc_alloc_large (unboxed) considers on its
315 * next call. (Although it always allocates after the
316 * current_unboxed_region.) */
317 page_index_t alloc_large_unboxed_start_page;
319 /* the bytes allocated to this generation */
320 os_vm_size_t bytes_allocated;
322 /* the number of bytes at which to trigger a GC */
323 os_vm_size_t gc_trigger;
325 /* to calculate a new level for gc_trigger */
326 os_vm_size_t bytes_consed_between_gc;
328 /* the number of GCs since the last raise */
329 int num_gc;
331 /* the number of GCs to run on the generations before raising objects to the
332 * next generation */
333 int number_of_gcs_before_promotion;
335 /* the cumulative sum of the bytes allocated to this generation. It is
336 * cleared after a GC on this generations, and update before new
337 * objects are added from a GC of a younger generation. Dividing by
338 * the bytes_allocated will give the average age of the memory in
339 * this generation since its last GC. */
340 os_vm_size_t cum_sum_bytes_allocated;
342 /* a minimum average memory age before a GC will occur helps
343 * prevent a GC when a large number of new live objects have been
344 * added, in which case a GC could be a waste of time */
345 double minimum_age_before_gc;
348 /* an array of generation structures. There needs to be one more
349 * generation structure than actual generations as the oldest
350 * generation is temporarily raised then lowered. */
351 struct generation generations[NUM_GENERATIONS];
353 /* the oldest generation that is will currently be GCed by default.
354 * Valid values are: 0, 1, ... HIGHEST_NORMAL_GENERATION
356 * The default of HIGHEST_NORMAL_GENERATION enables GC on all generations.
358 * Setting this to 0 effectively disables the generational nature of
359 * the GC. In some applications generational GC may not be useful
360 * because there are no long-lived objects.
362 * An intermediate value could be handy after moving long-lived data
363 * into an older generation so an unnecessary GC of this long-lived
364 * data can be avoided. */
365 generation_index_t gencgc_oldest_gen_to_gc = HIGHEST_NORMAL_GENERATION;
367 /* META: Is nobody aside from me bothered by this especially misleading
368 * use of the word "last"? It could mean either "ultimate" or "prior",
369 * but in fact means neither. It is the *FIRST* page that should be grabbed
370 * for more space, so it is min free page, or 1+ the max used page. */
371 /* The maximum free page in the heap is maintained and used to update
372 * ALLOCATION_POINTER which is used by the room function to limit its
373 * search of the heap. XX Gencgc obviously needs to be better
374 * integrated with the Lisp code. */
376 page_index_t last_free_page;
378 #ifdef LISP_FEATURE_SB_THREAD
379 /* This lock is to prevent multiple threads from simultaneously
380 * allocating new regions which overlap each other. Note that the
381 * majority of GC is single-threaded, but alloc() may be called from
382 * >1 thread at a time and must be thread-safe. This lock must be
383 * seized before all accesses to generations[] or to parts of
384 * page_table[] that other threads may want to see */
385 static pthread_mutex_t free_pages_lock = PTHREAD_MUTEX_INITIALIZER;
386 /* This lock is used to protect non-thread-local allocation. */
387 static pthread_mutex_t allocation_lock = PTHREAD_MUTEX_INITIALIZER;
388 #endif
390 extern os_vm_size_t gencgc_release_granularity;
391 os_vm_size_t gencgc_release_granularity = GENCGC_RELEASE_GRANULARITY;
393 extern os_vm_size_t gencgc_alloc_granularity;
394 os_vm_size_t gencgc_alloc_granularity = GENCGC_ALLOC_GRANULARITY;
398 * miscellaneous heap functions
401 /* Count the number of pages which are write-protected within the
402 * given generation. */
403 static page_index_t
404 count_write_protect_generation_pages(generation_index_t generation)
406 page_index_t i, count = 0;
408 for (i = 0; i < last_free_page; i++)
409 if (page_allocated_p(i)
410 && (page_table[i].gen == generation)
411 && (page_table[i].write_protected == 1))
412 count++;
413 return count;
416 /* Count the number of pages within the given generation. */
417 static page_index_t
418 count_generation_pages(generation_index_t generation)
420 page_index_t i;
421 page_index_t count = 0;
423 for (i = 0; i < last_free_page; i++)
424 if (page_allocated_p(i)
425 && (page_table[i].gen == generation))
426 count++;
427 return count;
430 #if QSHOW
431 static page_index_t
432 count_dont_move_pages(void)
434 page_index_t i;
435 page_index_t count = 0;
436 for (i = 0; i < last_free_page; i++) {
437 if (page_allocated_p(i)
438 && (page_table[i].dont_move != 0)) {
439 ++count;
442 return count;
444 #endif /* QSHOW */
446 /* Work through the pages and add up the number of bytes used for the
447 * given generation. */
448 static os_vm_size_t
449 count_generation_bytes_allocated (generation_index_t gen)
451 page_index_t i;
452 os_vm_size_t result = 0;
453 for (i = 0; i < last_free_page; i++) {
454 if (page_allocated_p(i)
455 && (page_table[i].gen == gen))
456 result += page_table[i].bytes_used;
458 return result;
461 /* Return the average age of the memory in a generation. */
462 extern double
463 generation_average_age(generation_index_t gen)
465 if (generations[gen].bytes_allocated == 0)
466 return 0.0;
468 return
469 ((double)generations[gen].cum_sum_bytes_allocated)
470 / ((double)generations[gen].bytes_allocated);
473 #ifdef LISP_FEATURE_X86
474 extern void fpu_save(void *);
475 extern void fpu_restore(void *);
476 #endif
478 extern void
479 write_generation_stats(FILE *file)
481 generation_index_t i;
483 #ifdef LISP_FEATURE_X86
484 int fpu_state[27];
486 /* Can end up here after calling alloc_tramp which doesn't prepare
487 * the x87 state, and the C ABI uses a different mode */
488 fpu_save(fpu_state);
489 #endif
491 /* Print the heap stats. */
492 fprintf(file,
493 " Gen StaPg UbSta LaSta LUbSt Boxed Unboxed LB LUB !move Alloc Waste Trig WP GCs Mem-age\n");
495 for (i = 0; i < SCRATCH_GENERATION; i++) {
496 page_index_t j;
497 page_index_t boxed_cnt = 0;
498 page_index_t unboxed_cnt = 0;
499 page_index_t large_boxed_cnt = 0;
500 page_index_t large_unboxed_cnt = 0;
501 page_index_t pinned_cnt=0;
503 for (j = 0; j < last_free_page; j++)
504 if (page_table[j].gen == i) {
506 /* Count the number of boxed pages within the given
507 * generation. */
508 if (page_boxed_p(j)) {
509 if (page_table[j].large_object)
510 large_boxed_cnt++;
511 else
512 boxed_cnt++;
514 if(page_table[j].dont_move) pinned_cnt++;
515 /* Count the number of unboxed pages within the given
516 * generation. */
517 if (page_unboxed_p(j)) {
518 if (page_table[j].large_object)
519 large_unboxed_cnt++;
520 else
521 unboxed_cnt++;
525 gc_assert(generations[i].bytes_allocated
526 == count_generation_bytes_allocated(i));
527 fprintf(file,
528 " %1d: %5ld %5ld %5ld %5ld",
530 generations[i].alloc_start_page,
531 generations[i].alloc_unboxed_start_page,
532 generations[i].alloc_large_start_page,
533 generations[i].alloc_large_unboxed_start_page);
534 fprintf(file,
535 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT
536 " %5"PAGE_INDEX_FMT" %5"PAGE_INDEX_FMT,
537 boxed_cnt, unboxed_cnt, large_boxed_cnt,
538 large_unboxed_cnt, pinned_cnt);
539 fprintf(file,
540 " %8"OS_VM_SIZE_FMT
541 " %5"OS_VM_SIZE_FMT
542 " %8"OS_VM_SIZE_FMT
543 " %4"PAGE_INDEX_FMT" %3d %7.4f\n",
544 generations[i].bytes_allocated,
545 (npage_bytes(count_generation_pages(i)) - generations[i].bytes_allocated),
546 generations[i].gc_trigger,
547 count_write_protect_generation_pages(i),
548 generations[i].num_gc,
549 generation_average_age(i));
551 fprintf(file," Total bytes allocated = %"OS_VM_SIZE_FMT"\n", bytes_allocated);
552 fprintf(file," Dynamic-space-size bytes = %"OS_VM_SIZE_FMT"\n", dynamic_space_size);
554 #ifdef LISP_FEATURE_X86
555 fpu_restore(fpu_state);
556 #endif
559 extern void
560 write_heap_exhaustion_report(FILE *file, long available, long requested,
561 struct thread *thread)
563 fprintf(file,
564 "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
565 gc_active_p ? "garbage collection" : "allocation",
566 available,
567 requested);
568 write_generation_stats(file);
569 fprintf(file, "GC control variables:\n");
570 fprintf(file, " *GC-INHIBIT* = %s\n *GC-PENDING* = %s\n",
571 SymbolValue(GC_INHIBIT,thread)==NIL ? "false" : "true",
572 (SymbolValue(GC_PENDING, thread) == T) ?
573 "true" : ((SymbolValue(GC_PENDING, thread) == NIL) ?
574 "false" : "in progress"));
575 #ifdef LISP_FEATURE_SB_THREAD
576 fprintf(file, " *STOP-FOR-GC-PENDING* = %s\n",
577 SymbolValue(STOP_FOR_GC_PENDING,thread)==NIL ? "false" : "true");
578 #endif
581 extern void
582 print_generation_stats(void)
584 write_generation_stats(stderr);
587 extern char* gc_logfile;
588 char * gc_logfile = NULL;
590 extern void
591 log_generation_stats(char *logfile, char *header)
593 if (logfile) {
594 FILE * log = fopen(logfile, "a");
595 if (log) {
596 fprintf(log, "%s\n", header);
597 write_generation_stats(log);
598 fclose(log);
599 } else {
600 fprintf(stderr, "Could not open gc logfile: %s\n", logfile);
601 fflush(stderr);
606 extern void
607 report_heap_exhaustion(long available, long requested, struct thread *th)
609 if (gc_logfile) {
610 FILE * log = fopen(gc_logfile, "a");
611 if (log) {
612 write_heap_exhaustion_report(log, available, requested, th);
613 fclose(log);
614 } else {
615 fprintf(stderr, "Could not open gc logfile: %s\n", gc_logfile);
616 fflush(stderr);
619 /* Always to stderr as well. */
620 write_heap_exhaustion_report(stderr, available, requested, th);
624 #if defined(LISP_FEATURE_X86)
625 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
626 #endif
628 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
629 * if zeroing it ourselves, i.e. in practice give the memory back to the
630 * OS. Generally done after a large GC.
632 void zero_pages_with_mmap(page_index_t start, page_index_t end) {
633 page_index_t i;
634 void *addr = page_address(start), *new_addr;
635 os_vm_size_t length = npage_bytes(1+end-start);
637 if (start > end)
638 return;
640 gc_assert(length >= gencgc_release_granularity);
641 gc_assert((length % gencgc_release_granularity) == 0);
643 os_invalidate(addr, length);
644 new_addr = os_validate(addr, length);
645 if (new_addr == NULL || new_addr != addr) {
646 lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
647 start, new_addr);
650 for (i = start; i <= end; i++) {
651 page_table[i].need_to_zero = 0;
655 /* Zero the pages from START to END (inclusive). Generally done just after
656 * a new region has been allocated.
658 static void
659 zero_pages(page_index_t start, page_index_t end) {
660 if (start > end)
661 return;
663 #if defined(LISP_FEATURE_X86)
664 fast_bzero(page_address(start), npage_bytes(1+end-start));
665 #else
666 bzero(page_address(start), npage_bytes(1+end-start));
667 #endif
671 static void
672 zero_and_mark_pages(page_index_t start, page_index_t end) {
673 page_index_t i;
675 zero_pages(start, end);
676 for (i = start; i <= end; i++)
677 page_table[i].need_to_zero = 0;
680 /* Zero the pages from START to END (inclusive), except for those
681 * pages that are known to already zeroed. Mark all pages in the
682 * ranges as non-zeroed.
684 static void
685 zero_dirty_pages(page_index_t start, page_index_t end) {
686 page_index_t i, j;
688 for (i = start; i <= end; i++) {
689 if (!page_table[i].need_to_zero) continue;
690 for (j = i+1; (j <= end) && (page_table[j].need_to_zero); j++);
691 zero_pages(i, j-1);
692 i = j;
695 for (i = start; i <= end; i++) {
696 page_table[i].need_to_zero = 1;
702 * To support quick and inline allocation, regions of memory can be
703 * allocated and then allocated from with just a free pointer and a
704 * check against an end address.
706 * Since objects can be allocated to spaces with different properties
707 * e.g. boxed/unboxed, generation, ages; there may need to be many
708 * allocation regions.
710 * Each allocation region may start within a partly used page. Many
711 * features of memory use are noted on a page wise basis, e.g. the
712 * generation; so if a region starts within an existing allocated page
713 * it must be consistent with this page.
715 * During the scavenging of the newspace, objects will be transported
716 * into an allocation region, and pointers updated to point to this
717 * allocation region. It is possible that these pointers will be
718 * scavenged again before the allocation region is closed, e.g. due to
719 * trans_list which jumps all over the place to cleanup the list. It
720 * is important to be able to determine properties of all objects
721 * pointed to when scavenging, e.g to detect pointers to the oldspace.
722 * Thus it's important that the allocation regions have the correct
723 * properties set when allocated, and not just set when closed. The
724 * region allocation routines return regions with the specified
725 * properties, and grab all the pages, setting their properties
726 * appropriately, except that the amount used is not known.
728 * These regions are used to support quicker allocation using just a
729 * free pointer. The actual space used by the region is not reflected
730 * in the pages tables until it is closed. It can't be scavenged until
731 * closed.
733 * When finished with the region it should be closed, which will
734 * update the page tables for the actual space used returning unused
735 * space. Further it may be noted in the new regions which is
736 * necessary when scavenging the newspace.
738 * Large objects may be allocated directly without an allocation
739 * region, the page tables are updated immediately.
741 * Unboxed objects don't contain pointers to other objects and so
742 * don't need scavenging. Further they can't contain pointers to
743 * younger generations so WP is not needed. By allocating pages to
744 * unboxed objects the whole page never needs scavenging or
745 * write-protecting. */
747 /* We are only using two regions at present. Both are for the current
748 * newspace generation. */
749 struct alloc_region boxed_region;
750 struct alloc_region unboxed_region;
752 /* The generation currently being allocated to. */
753 static generation_index_t gc_alloc_generation;
755 static inline page_index_t
756 generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large)
758 if (large) {
759 if (UNBOXED_PAGE_FLAG == page_type_flag) {
760 return generations[generation].alloc_large_unboxed_start_page;
761 } else if (BOXED_PAGE_FLAG & page_type_flag) {
762 /* Both code and data. */
763 return generations[generation].alloc_large_start_page;
764 } else {
765 lose("bad page type flag: %d", page_type_flag);
767 } else {
768 if (UNBOXED_PAGE_FLAG == page_type_flag) {
769 return generations[generation].alloc_unboxed_start_page;
770 } else if (BOXED_PAGE_FLAG & page_type_flag) {
771 /* Both code and data. */
772 return generations[generation].alloc_start_page;
773 } else {
774 lose("bad page_type_flag: %d", page_type_flag);
779 static inline void
780 set_generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large,
781 page_index_t page)
783 if (large) {
784 if (UNBOXED_PAGE_FLAG == page_type_flag) {
785 generations[generation].alloc_large_unboxed_start_page = page;
786 } else if (BOXED_PAGE_FLAG & page_type_flag) {
787 /* Both code and data. */
788 generations[generation].alloc_large_start_page = page;
789 } else {
790 lose("bad page type flag: %d", page_type_flag);
792 } else {
793 if (UNBOXED_PAGE_FLAG == page_type_flag) {
794 generations[generation].alloc_unboxed_start_page = page;
795 } else if (BOXED_PAGE_FLAG & page_type_flag) {
796 /* Both code and data. */
797 generations[generation].alloc_start_page = page;
798 } else {
799 lose("bad page type flag: %d", page_type_flag);
804 const int n_dwords_in_card = GENCGC_CARD_BYTES / N_WORD_BYTES / 2;
805 in_use_marker_t *
806 pinned_dwords(page_index_t page)
808 if (page_table[page].has_pin_map)
809 return &page_table_pinned_dwords[page * (n_dwords_in_card/N_WORD_BITS)];
810 return NULL;
813 /* Find a new region with room for at least the given number of bytes.
815 * It starts looking at the current generation's alloc_start_page. So
816 * may pick up from the previous region if there is enough space. This
817 * keeps the allocation contiguous when scavenging the newspace.
819 * The alloc_region should have been closed by a call to
820 * gc_alloc_update_page_tables(), and will thus be in an empty state.
822 * To assist the scavenging functions write-protected pages are not
823 * used. Free pages should not be write-protected.
825 * It is critical to the conservative GC that the start of regions be
826 * known. To help achieve this only small regions are allocated at a
827 * time.
829 * During scavenging, pointers may be found to within the current
830 * region and the page generation must be set so that pointers to the
831 * from space can be recognized. Therefore the generation of pages in
832 * the region are set to gc_alloc_generation. To prevent another
833 * allocation call using the same pages, all the pages in the region
834 * are allocated, although they will initially be empty.
836 static void
837 gc_alloc_new_region(sword_t nbytes, int page_type_flag, struct alloc_region *alloc_region)
839 page_index_t first_page;
840 page_index_t last_page;
841 os_vm_size_t bytes_found;
842 page_index_t i;
843 int ret;
846 FSHOW((stderr,
847 "/alloc_new_region for %d bytes from gen %d\n",
848 nbytes, gc_alloc_generation));
851 /* Check that the region is in a reset state. */
852 gc_assert((alloc_region->first_page == 0)
853 && (alloc_region->last_page == -1)
854 && (alloc_region->free_pointer == alloc_region->end_addr));
855 ret = thread_mutex_lock(&free_pages_lock);
856 gc_assert(ret == 0);
857 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0);
858 last_page=gc_find_freeish_pages(&first_page, nbytes, page_type_flag);
859 bytes_found=(GENCGC_CARD_BYTES - page_table[first_page].bytes_used)
860 + npage_bytes(last_page-first_page);
862 /* Set up the alloc_region. */
863 alloc_region->first_page = first_page;
864 alloc_region->last_page = last_page;
865 alloc_region->start_addr = page_table[first_page].bytes_used
866 + page_address(first_page);
867 alloc_region->free_pointer = alloc_region->start_addr;
868 alloc_region->end_addr = alloc_region->start_addr + bytes_found;
870 /* Set up the pages. */
872 /* The first page may have already been in use. */
873 if (page_table[first_page].bytes_used == 0) {
874 page_table[first_page].allocated = page_type_flag;
875 page_table[first_page].gen = gc_alloc_generation;
876 page_table[first_page].large_object = 0;
877 page_table[first_page].scan_start_offset = 0;
878 // wiping should have free()ed and :=NULL
879 gc_assert(pinned_dwords(first_page) == NULL);
882 gc_assert(page_table[first_page].allocated == page_type_flag);
883 page_table[first_page].allocated |= OPEN_REGION_PAGE_FLAG;
885 gc_assert(page_table[first_page].gen == gc_alloc_generation);
886 gc_assert(page_table[first_page].large_object == 0);
888 for (i = first_page+1; i <= last_page; i++) {
889 page_table[i].allocated = page_type_flag;
890 page_table[i].gen = gc_alloc_generation;
891 page_table[i].large_object = 0;
892 /* This may not be necessary for unboxed regions (think it was
893 * broken before!) */
894 page_table[i].scan_start_offset =
895 void_diff(page_address(i),alloc_region->start_addr);
896 page_table[i].allocated |= OPEN_REGION_PAGE_FLAG ;
898 /* Bump up last_free_page. */
899 if (last_page+1 > last_free_page) {
900 last_free_page = last_page+1;
901 /* do we only want to call this on special occasions? like for
902 * boxed_region? */
903 set_alloc_pointer((lispobj)page_address(last_free_page));
905 ret = thread_mutex_unlock(&free_pages_lock);
906 gc_assert(ret == 0);
908 #ifdef READ_PROTECT_FREE_PAGES
909 os_protect(page_address(first_page),
910 npage_bytes(1+last_page-first_page),
911 OS_VM_PROT_ALL);
912 #endif
914 /* If the first page was only partial, don't check whether it's
915 * zeroed (it won't be) and don't zero it (since the parts that
916 * we're interested in are guaranteed to be zeroed).
918 if (page_table[first_page].bytes_used) {
919 first_page++;
922 zero_dirty_pages(first_page, last_page);
924 /* we can do this after releasing free_pages_lock */
925 if (gencgc_zero_check) {
926 word_t *p;
927 for (p = (word_t *)alloc_region->start_addr;
928 p < (word_t *)alloc_region->end_addr; p++) {
929 if (*p != 0) {
930 lose("The new region is not zero at %p (start=%p, end=%p).\n",
931 p, alloc_region->start_addr, alloc_region->end_addr);
937 /* If the record_new_objects flag is 2 then all new regions created
938 * are recorded.
940 * If it's 1 then then it is only recorded if the first page of the
941 * current region is <= new_areas_ignore_page. This helps avoid
942 * unnecessary recording when doing full scavenge pass.
944 * The new_object structure holds the page, byte offset, and size of
945 * new regions of objects. Each new area is placed in the array of
946 * these structures pointer to by new_areas. new_areas_index holds the
947 * offset into new_areas.
949 * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
950 * later code must detect this and handle it, probably by doing a full
951 * scavenge of a generation. */
952 #define NUM_NEW_AREAS 512
953 static int record_new_objects = 0;
954 static page_index_t new_areas_ignore_page;
955 struct new_area {
956 page_index_t page;
957 size_t offset;
958 size_t size;
960 static struct new_area (*new_areas)[];
961 static size_t new_areas_index;
962 size_t max_new_areas;
964 /* Add a new area to new_areas. */
965 static void
966 add_new_area(page_index_t first_page, size_t offset, size_t size)
968 size_t new_area_start, c;
969 ssize_t i;
971 /* Ignore if full. */
972 if (new_areas_index >= NUM_NEW_AREAS)
973 return;
975 switch (record_new_objects) {
976 case 0:
977 return;
978 case 1:
979 if (first_page > new_areas_ignore_page)
980 return;
981 break;
982 case 2:
983 break;
984 default:
985 gc_abort();
988 new_area_start = npage_bytes(first_page) + offset;
990 /* Search backwards for a prior area that this follows from. If
991 found this will save adding a new area. */
992 for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
993 size_t area_end =
994 npage_bytes((*new_areas)[i].page)
995 + (*new_areas)[i].offset
996 + (*new_areas)[i].size;
997 /*FSHOW((stderr,
998 "/add_new_area S1 %d %d %d %d\n",
999 i, c, new_area_start, area_end));*/
1000 if (new_area_start == area_end) {
1001 /*FSHOW((stderr,
1002 "/adding to [%d] %d %d %d with %d %d %d:\n",
1004 (*new_areas)[i].page,
1005 (*new_areas)[i].offset,
1006 (*new_areas)[i].size,
1007 first_page,
1008 offset,
1009 size);*/
1010 (*new_areas)[i].size += size;
1011 return;
1015 (*new_areas)[new_areas_index].page = first_page;
1016 (*new_areas)[new_areas_index].offset = offset;
1017 (*new_areas)[new_areas_index].size = size;
1018 /*FSHOW((stderr,
1019 "/new_area %d page %d offset %d size %d\n",
1020 new_areas_index, first_page, offset, size));*/
1021 new_areas_index++;
1023 /* Note the max new_areas used. */
1024 if (new_areas_index > max_new_areas)
1025 max_new_areas = new_areas_index;
1028 /* Update the tables for the alloc_region. The region may be added to
1029 * the new_areas.
1031 * When done the alloc_region is set up so that the next quick alloc
1032 * will fail safely and thus a new region will be allocated. Further
1033 * it is safe to try to re-update the page table of this reset
1034 * alloc_region. */
1035 void
1036 gc_alloc_update_page_tables(int page_type_flag, struct alloc_region *alloc_region)
1038 boolean more;
1039 page_index_t first_page;
1040 page_index_t next_page;
1041 os_vm_size_t bytes_used;
1042 os_vm_size_t region_size;
1043 os_vm_size_t byte_cnt;
1044 page_bytes_t orig_first_page_bytes_used;
1045 int ret;
1048 first_page = alloc_region->first_page;
1050 /* Catch an unused alloc_region. */
1051 if ((first_page == 0) && (alloc_region->last_page == -1))
1052 return;
1054 next_page = first_page+1;
1056 ret = thread_mutex_lock(&free_pages_lock);
1057 gc_assert(ret == 0);
1058 if (alloc_region->free_pointer != alloc_region->start_addr) {
1059 /* some bytes were allocated in the region */
1060 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1062 gc_assert(alloc_region->start_addr ==
1063 (page_address(first_page)
1064 + page_table[first_page].bytes_used));
1066 /* All the pages used need to be updated */
1068 /* Update the first page. */
1070 /* If the page was free then set up the gen, and
1071 * scan_start_offset. */
1072 if (page_table[first_page].bytes_used == 0)
1073 gc_assert(page_starts_contiguous_block_p(first_page));
1074 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1076 gc_assert(page_table[first_page].allocated & page_type_flag);
1077 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1078 gc_assert(page_table[first_page].large_object == 0);
1080 byte_cnt = 0;
1082 /* Calculate the number of bytes used in this page. This is not
1083 * always the number of new bytes, unless it was free. */
1084 more = 0;
1085 if ((bytes_used = void_diff(alloc_region->free_pointer,
1086 page_address(first_page)))
1087 >GENCGC_CARD_BYTES) {
1088 bytes_used = GENCGC_CARD_BYTES;
1089 more = 1;
1091 page_table[first_page].bytes_used = bytes_used;
1092 byte_cnt += bytes_used;
1095 /* All the rest of the pages should be free. We need to set
1096 * their scan_start_offset pointer to the start of the
1097 * region, and set the bytes_used. */
1098 while (more) {
1099 page_table[next_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1100 gc_assert(page_table[next_page].allocated & page_type_flag);
1101 gc_assert(page_table[next_page].bytes_used == 0);
1102 gc_assert(page_table[next_page].gen == gc_alloc_generation);
1103 gc_assert(page_table[next_page].large_object == 0);
1105 gc_assert(page_table[next_page].scan_start_offset ==
1106 void_diff(page_address(next_page),
1107 alloc_region->start_addr));
1109 /* Calculate the number of bytes used in this page. */
1110 more = 0;
1111 if ((bytes_used = void_diff(alloc_region->free_pointer,
1112 page_address(next_page)))>GENCGC_CARD_BYTES) {
1113 bytes_used = GENCGC_CARD_BYTES;
1114 more = 1;
1116 page_table[next_page].bytes_used = bytes_used;
1117 byte_cnt += bytes_used;
1119 next_page++;
1122 region_size = void_diff(alloc_region->free_pointer,
1123 alloc_region->start_addr);
1124 bytes_allocated += region_size;
1125 generations[gc_alloc_generation].bytes_allocated += region_size;
1127 gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
1129 /* Set the generations alloc restart page to the last page of
1130 * the region. */
1131 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0, next_page-1);
1133 /* Add the region to the new_areas if requested. */
1134 if (BOXED_PAGE_FLAG & page_type_flag)
1135 add_new_area(first_page,orig_first_page_bytes_used, region_size);
1138 FSHOW((stderr,
1139 "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1140 region_size,
1141 gc_alloc_generation));
1143 } else {
1144 /* There are no bytes allocated. Unallocate the first_page if
1145 * there are 0 bytes_used. */
1146 page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1147 if (page_table[first_page].bytes_used == 0)
1148 page_table[first_page].allocated = FREE_PAGE_FLAG;
1151 /* Unallocate any unused pages. */
1152 while (next_page <= alloc_region->last_page) {
1153 gc_assert(page_table[next_page].bytes_used == 0);
1154 page_table[next_page].allocated = FREE_PAGE_FLAG;
1155 next_page++;
1157 ret = thread_mutex_unlock(&free_pages_lock);
1158 gc_assert(ret == 0);
1160 /* alloc_region is per-thread, we're ok to do this unlocked */
1161 gc_set_region_empty(alloc_region);
1164 /* Allocate a possibly large object. */
1165 void *
1166 gc_alloc_large(sword_t nbytes, int page_type_flag, struct alloc_region *alloc_region)
1168 boolean more;
1169 page_index_t first_page, next_page, last_page;
1170 page_bytes_t orig_first_page_bytes_used;
1171 os_vm_size_t byte_cnt;
1172 os_vm_size_t bytes_used;
1173 int ret;
1175 ret = thread_mutex_lock(&free_pages_lock);
1176 gc_assert(ret == 0);
1178 first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1);
1179 if (first_page <= alloc_region->last_page) {
1180 first_page = alloc_region->last_page+1;
1183 last_page=gc_find_freeish_pages(&first_page,nbytes, page_type_flag);
1185 gc_assert(first_page > alloc_region->last_page);
1187 set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1, last_page);
1189 /* Set up the pages. */
1190 orig_first_page_bytes_used = page_table[first_page].bytes_used;
1192 /* If the first page was free then set up the gen, and
1193 * scan_start_offset. */
1194 if (page_table[first_page].bytes_used == 0) {
1195 page_table[first_page].allocated = page_type_flag;
1196 page_table[first_page].gen = gc_alloc_generation;
1197 page_table[first_page].scan_start_offset = 0;
1198 page_table[first_page].large_object = 1;
1201 gc_assert(page_table[first_page].allocated == page_type_flag);
1202 gc_assert(page_table[first_page].gen == gc_alloc_generation);
1203 gc_assert(page_table[first_page].large_object == 1);
1205 byte_cnt = 0;
1207 /* Calc. the number of bytes used in this page. This is not
1208 * always the number of new bytes, unless it was free. */
1209 more = 0;
1210 if ((bytes_used = nbytes+orig_first_page_bytes_used) > GENCGC_CARD_BYTES) {
1211 bytes_used = GENCGC_CARD_BYTES;
1212 more = 1;
1214 page_table[first_page].bytes_used = bytes_used;
1215 byte_cnt += bytes_used;
1217 next_page = first_page+1;
1219 /* All the rest of the pages should be free. We need to set their
1220 * scan_start_offset pointer to the start of the region, and set
1221 * the bytes_used. */
1222 while (more) {
1223 gc_assert(page_free_p(next_page));
1224 gc_assert(page_table[next_page].bytes_used == 0);
1225 page_table[next_page].allocated = page_type_flag;
1226 page_table[next_page].gen = gc_alloc_generation;
1227 page_table[next_page].large_object = 1;
1229 page_table[next_page].scan_start_offset =
1230 npage_bytes(next_page-first_page) - orig_first_page_bytes_used;
1232 /* Calculate the number of bytes used in this page. */
1233 more = 0;
1234 bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt;
1235 if (bytes_used > GENCGC_CARD_BYTES) {
1236 bytes_used = GENCGC_CARD_BYTES;
1237 more = 1;
1239 page_table[next_page].bytes_used = bytes_used;
1240 page_table[next_page].write_protected=0;
1241 page_table[next_page].dont_move=0;
1242 byte_cnt += bytes_used;
1243 next_page++;
1246 gc_assert((byte_cnt-orig_first_page_bytes_used) == (size_t)nbytes);
1248 bytes_allocated += nbytes;
1249 generations[gc_alloc_generation].bytes_allocated += nbytes;
1251 /* Add the region to the new_areas if requested. */
1252 if (BOXED_PAGE_FLAG & page_type_flag)
1253 add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1255 /* Bump up last_free_page */
1256 if (last_page+1 > last_free_page) {
1257 last_free_page = last_page+1;
1258 set_alloc_pointer((lispobj)(page_address(last_free_page)));
1260 ret = thread_mutex_unlock(&free_pages_lock);
1261 gc_assert(ret == 0);
1263 #ifdef READ_PROTECT_FREE_PAGES
1264 os_protect(page_address(first_page),
1265 npage_bytes(1+last_page-first_page),
1266 OS_VM_PROT_ALL);
1267 #endif
1269 zero_dirty_pages(first_page, last_page);
1271 return page_address(first_page);
1274 static page_index_t gencgc_alloc_start_page = -1;
1276 void
1277 gc_heap_exhausted_error_or_lose (sword_t available, sword_t requested)
1279 struct thread *thread = arch_os_get_current_thread();
1280 /* Write basic information before doing anything else: if we don't
1281 * call to lisp this is a must, and even if we do there is always
1282 * the danger that we bounce back here before the error has been
1283 * handled, or indeed even printed.
1285 report_heap_exhaustion(available, requested, thread);
1286 if (gc_active_p || (available == 0)) {
1287 /* If we are in GC, or totally out of memory there is no way
1288 * to sanely transfer control to the lisp-side of things.
1290 lose("Heap exhausted, game over.");
1292 else {
1293 /* FIXME: assert free_pages_lock held */
1294 (void)thread_mutex_unlock(&free_pages_lock);
1295 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
1296 gc_assert(get_pseudo_atomic_atomic(thread));
1297 clear_pseudo_atomic_atomic(thread);
1298 if (get_pseudo_atomic_interrupted(thread))
1299 do_pending_interrupt();
1300 #endif
1301 /* Another issue is that signalling HEAP-EXHAUSTED error leads
1302 * to running user code at arbitrary places, even in a
1303 * WITHOUT-INTERRUPTS which may lead to a deadlock without
1304 * running out of the heap. So at this point all bets are
1305 * off. */
1306 if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
1307 corruption_warning_and_maybe_lose
1308 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1309 /* available and requested should be double word aligned, thus
1310 they can passed as fixnums and shifted later. */
1311 funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR), available, requested);
1312 lose("HEAP-EXHAUSTED-ERROR fell through");
1316 page_index_t
1317 gc_find_freeish_pages(page_index_t *restart_page_ptr, sword_t bytes,
1318 int page_type_flag)
1320 page_index_t most_bytes_found_from = 0, most_bytes_found_to = 0;
1321 page_index_t first_page, last_page, restart_page = *restart_page_ptr;
1322 os_vm_size_t nbytes = bytes;
1323 os_vm_size_t nbytes_goal = nbytes;
1324 os_vm_size_t bytes_found = 0;
1325 os_vm_size_t most_bytes_found = 0;
1326 boolean small_object = nbytes < GENCGC_CARD_BYTES;
1327 /* FIXME: assert(free_pages_lock is held); */
1329 if (nbytes_goal < gencgc_alloc_granularity)
1330 nbytes_goal = gencgc_alloc_granularity;
1332 /* Toggled by gc_and_save for heap compaction, normally -1. */
1333 if (gencgc_alloc_start_page != -1) {
1334 restart_page = gencgc_alloc_start_page;
1337 /* FIXME: This is on bytes instead of nbytes pending cleanup of
1338 * long from the interface. */
1339 gc_assert(bytes>=0);
1340 /* Search for a page with at least nbytes of space. We prefer
1341 * not to split small objects on multiple pages, to reduce the
1342 * number of contiguous allocation regions spaning multiple
1343 * pages: this helps avoid excessive conservativism.
1345 * For other objects, we guarantee that they start on their own
1346 * page boundary.
1348 first_page = restart_page;
1349 while (first_page < page_table_pages) {
1350 bytes_found = 0;
1351 if (page_free_p(first_page)) {
1352 gc_assert(0 == page_table[first_page].bytes_used);
1353 bytes_found = GENCGC_CARD_BYTES;
1354 } else if (small_object &&
1355 (page_table[first_page].allocated == page_type_flag) &&
1356 (page_table[first_page].large_object == 0) &&
1357 (page_table[first_page].gen == gc_alloc_generation) &&
1358 (page_table[first_page].write_protected == 0) &&
1359 (page_table[first_page].dont_move == 0)) {
1360 bytes_found = GENCGC_CARD_BYTES - page_table[first_page].bytes_used;
1361 if (bytes_found < nbytes) {
1362 if (bytes_found > most_bytes_found)
1363 most_bytes_found = bytes_found;
1364 first_page++;
1365 continue;
1367 } else {
1368 first_page++;
1369 continue;
1372 gc_assert(page_table[first_page].write_protected == 0);
1373 for (last_page = first_page+1;
1374 ((last_page < page_table_pages) &&
1375 page_free_p(last_page) &&
1376 (bytes_found < nbytes_goal));
1377 last_page++) {
1378 bytes_found += GENCGC_CARD_BYTES;
1379 gc_assert(0 == page_table[last_page].bytes_used);
1380 gc_assert(0 == page_table[last_page].write_protected);
1383 if (bytes_found > most_bytes_found) {
1384 most_bytes_found = bytes_found;
1385 most_bytes_found_from = first_page;
1386 most_bytes_found_to = last_page;
1388 if (bytes_found >= nbytes_goal)
1389 break;
1391 first_page = last_page;
1394 bytes_found = most_bytes_found;
1395 restart_page = first_page + 1;
1397 /* Check for a failure */
1398 if (bytes_found < nbytes) {
1399 gc_assert(restart_page >= page_table_pages);
1400 gc_heap_exhausted_error_or_lose(most_bytes_found, nbytes);
1403 gc_assert(most_bytes_found_to);
1404 *restart_page_ptr = most_bytes_found_from;
1405 return most_bytes_found_to-1;
1408 /* Allocate bytes. All the rest of the special-purpose allocation
1409 * functions will eventually call this */
1411 void *
1412 gc_alloc_with_region(sword_t nbytes,int page_type_flag, struct alloc_region *my_region,
1413 int quick_p)
1415 void *new_free_pointer;
1417 if (nbytes>=LARGE_OBJECT_SIZE)
1418 return gc_alloc_large(nbytes, page_type_flag, my_region);
1420 /* Check whether there is room in the current alloc region. */
1421 new_free_pointer = my_region->free_pointer + nbytes;
1423 /* fprintf(stderr, "alloc %d bytes from %p to %p\n", nbytes,
1424 my_region->free_pointer, new_free_pointer); */
1426 if (new_free_pointer <= my_region->end_addr) {
1427 /* If so then allocate from the current alloc region. */
1428 void *new_obj = my_region->free_pointer;
1429 my_region->free_pointer = new_free_pointer;
1431 /* Unless a `quick' alloc was requested, check whether the
1432 alloc region is almost empty. */
1433 if (!quick_p &&
1434 void_diff(my_region->end_addr,my_region->free_pointer) <= 32) {
1435 /* If so, finished with the current region. */
1436 gc_alloc_update_page_tables(page_type_flag, my_region);
1437 /* Set up a new region. */
1438 gc_alloc_new_region(32 /*bytes*/, page_type_flag, my_region);
1441 return((void *)new_obj);
1444 /* Else not enough free space in the current region: retry with a
1445 * new region. */
1447 gc_alloc_update_page_tables(page_type_flag, my_region);
1448 gc_alloc_new_region(nbytes, page_type_flag, my_region);
1449 return gc_alloc_with_region(nbytes, page_type_flag, my_region,0);
1452 /* Copy a large object. If the object is in a large object region then
1453 * it is simply promoted, else it is copied. If it's large enough then
1454 * it's copied to a large object region.
1456 * Bignums and vectors may have shrunk. If the object is not copied
1457 * the space needs to be reclaimed, and the page_tables corrected. */
1458 static lispobj
1459 general_copy_large_object(lispobj object, word_t nwords, boolean boxedp)
1461 int tag;
1462 lispobj *new;
1463 page_index_t first_page;
1465 gc_assert(is_lisp_pointer(object));
1466 gc_assert(from_space_p(object));
1467 gc_assert((nwords & 0x01) == 0);
1469 if ((nwords > 1024*1024) && gencgc_verbose) {
1470 FSHOW((stderr, "/general_copy_large_object: %d bytes\n",
1471 nwords*N_WORD_BYTES));
1474 /* Check whether it's a large object. */
1475 first_page = find_page_index((void *)object);
1476 gc_assert(first_page >= 0);
1478 if (page_table[first_page].large_object) {
1479 /* Promote the object. Note: Unboxed objects may have been
1480 * allocated to a BOXED region so it may be necessary to
1481 * change the region to UNBOXED. */
1482 os_vm_size_t remaining_bytes;
1483 os_vm_size_t bytes_freed;
1484 page_index_t next_page;
1485 page_bytes_t old_bytes_used;
1487 /* FIXME: This comment is somewhat stale.
1489 * Note: Any page write-protection must be removed, else a
1490 * later scavenge_newspace may incorrectly not scavenge these
1491 * pages. This would not be necessary if they are added to the
1492 * new areas, but let's do it for them all (they'll probably
1493 * be written anyway?). */
1495 gc_assert(page_starts_contiguous_block_p(first_page));
1496 next_page = first_page;
1497 remaining_bytes = nwords*N_WORD_BYTES;
1499 while (remaining_bytes > GENCGC_CARD_BYTES) {
1500 gc_assert(page_table[next_page].gen == from_space);
1501 gc_assert(page_table[next_page].large_object);
1502 gc_assert(page_table[next_page].scan_start_offset ==
1503 npage_bytes(next_page-first_page));
1504 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
1505 /* Should have been unprotected by unprotect_oldspace()
1506 * for boxed objects, and after promotion unboxed ones
1507 * should not be on protected pages at all. */
1508 gc_assert(!page_table[next_page].write_protected);
1510 if (boxedp)
1511 gc_assert(page_boxed_p(next_page));
1512 else {
1513 gc_assert(page_allocated_no_region_p(next_page));
1514 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1516 page_table[next_page].gen = new_space;
1518 remaining_bytes -= GENCGC_CARD_BYTES;
1519 next_page++;
1522 /* Now only one page remains, but the object may have shrunk so
1523 * there may be more unused pages which will be freed. */
1525 /* Object may have shrunk but shouldn't have grown - check. */
1526 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1528 page_table[next_page].gen = new_space;
1530 if (boxedp)
1531 gc_assert(page_boxed_p(next_page));
1532 else
1533 page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1535 /* Adjust the bytes_used. */
1536 old_bytes_used = page_table[next_page].bytes_used;
1537 page_table[next_page].bytes_used = remaining_bytes;
1539 bytes_freed = old_bytes_used - remaining_bytes;
1541 /* Free any remaining pages; needs care. */
1542 next_page++;
1543 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
1544 (page_table[next_page].gen == from_space) &&
1545 /* FIXME: It is not obvious to me why this is necessary
1546 * as a loop condition: it seems to me that the
1547 * scan_start_offset test should be sufficient, but
1548 * experimentally that is not the case. --NS
1549 * 2011-11-28 */
1550 (boxedp ?
1551 page_boxed_p(next_page) :
1552 page_allocated_no_region_p(next_page)) &&
1553 page_table[next_page].large_object &&
1554 (page_table[next_page].scan_start_offset ==
1555 npage_bytes(next_page - first_page))) {
1556 /* Checks out OK, free the page. Don't need to both zeroing
1557 * pages as this should have been done before shrinking the
1558 * object. These pages shouldn't be write-protected, even if
1559 * boxed they should be zero filled. */
1560 gc_assert(page_table[next_page].write_protected == 0);
1562 old_bytes_used = page_table[next_page].bytes_used;
1563 page_table[next_page].allocated = FREE_PAGE_FLAG;
1564 page_table[next_page].bytes_used = 0;
1565 bytes_freed += old_bytes_used;
1566 next_page++;
1569 if ((bytes_freed > 0) && gencgc_verbose) {
1570 FSHOW((stderr,
1571 "/general_copy_large_object bytes_freed=%"OS_VM_SIZE_FMT"\n",
1572 bytes_freed));
1575 generations[from_space].bytes_allocated -= nwords*N_WORD_BYTES
1576 + bytes_freed;
1577 generations[new_space].bytes_allocated += nwords*N_WORD_BYTES;
1578 bytes_allocated -= bytes_freed;
1580 /* Add the region to the new_areas if requested. */
1581 if (boxedp)
1582 add_new_area(first_page,0,nwords*N_WORD_BYTES);
1584 return(object);
1586 } else {
1587 /* Get tag of object. */
1588 tag = lowtag_of(object);
1590 /* Allocate space. */
1591 new = gc_general_alloc(nwords*N_WORD_BYTES,
1592 (boxedp ? BOXED_PAGE_FLAG : UNBOXED_PAGE_FLAG),
1593 ALLOC_QUICK);
1595 /* Copy the object. */
1596 memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1598 /* Return Lisp pointer of new object. */
1599 return ((lispobj) new) | tag;
1603 lispobj
1604 copy_large_object(lispobj object, sword_t nwords)
1606 return general_copy_large_object(object, nwords, 1);
1609 lispobj
1610 copy_large_unboxed_object(lispobj object, sword_t nwords)
1612 return general_copy_large_object(object, nwords, 0);
1615 /* to copy unboxed objects */
1616 lispobj
1617 copy_unboxed_object(lispobj object, sword_t nwords)
1619 return gc_general_copy_object(object, nwords, UNBOXED_PAGE_FLAG);
1624 * code and code-related objects
1627 static lispobj trans_fun_header(lispobj object);
1628 static lispobj trans_boxed(lispobj object);
1631 /* Scan a x86 compiled code object, looking for possible fixups that
1632 * have been missed after a move.
1634 * Two types of fixups are needed:
1635 * 1. Absolute fixups to within the code object.
1636 * 2. Relative fixups to outside the code object.
1638 * Currently only absolute fixups to the constant vector, or to the
1639 * code area are checked. */
1640 #ifdef LISP_FEATURE_X86
1641 void
1642 sniff_code_object(struct code *code, os_vm_size_t displacement)
1644 sword_t nheader_words, ncode_words, nwords;
1645 os_vm_address_t constants_start_addr = NULL, constants_end_addr, p;
1646 os_vm_address_t code_start_addr, code_end_addr;
1647 os_vm_address_t code_addr = (os_vm_address_t)code;
1648 int fixup_found = 0;
1650 if (!check_code_fixups)
1651 return;
1653 FSHOW((stderr, "/sniffing code: %p, %lu\n", code, displacement));
1655 ncode_words = code_instruction_words(code->code_size);
1656 nheader_words = code_header_words(*(lispobj *)code);
1657 nwords = ncode_words + nheader_words;
1659 constants_start_addr = code_addr + 5*N_WORD_BYTES;
1660 constants_end_addr = code_addr + nheader_words*N_WORD_BYTES;
1661 code_start_addr = code_addr + nheader_words*N_WORD_BYTES;
1662 code_end_addr = code_addr + nwords*N_WORD_BYTES;
1664 /* Work through the unboxed code. */
1665 for (p = code_start_addr; p < code_end_addr; p++) {
1666 void *data = *(void **)p;
1667 unsigned d1 = *((unsigned char *)p - 1);
1668 unsigned d2 = *((unsigned char *)p - 2);
1669 unsigned d3 = *((unsigned char *)p - 3);
1670 unsigned d4 = *((unsigned char *)p - 4);
1671 #if QSHOW
1672 unsigned d5 = *((unsigned char *)p - 5);
1673 unsigned d6 = *((unsigned char *)p - 6);
1674 #endif
1676 /* Check for code references. */
1677 /* Check for a 32 bit word that looks like an absolute
1678 reference to within the code adea of the code object. */
1679 if ((data >= (void*)(code_start_addr-displacement))
1680 && (data < (void*)(code_end_addr-displacement))) {
1681 /* function header */
1682 if ((d4 == 0x5e)
1683 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) ==
1684 (unsigned)code)) {
1685 /* Skip the function header */
1686 p += 6*4 - 4 - 1;
1687 continue;
1689 /* the case of PUSH imm32 */
1690 if (d1 == 0x68) {
1691 fixup_found = 1;
1692 FSHOW((stderr,
1693 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1694 p, d6, d5, d4, d3, d2, d1, data));
1695 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1697 /* the case of MOV [reg-8],imm32 */
1698 if ((d3 == 0xc7)
1699 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1700 || d2==0x45 || d2==0x46 || d2==0x47)
1701 && (d1 == 0xf8)) {
1702 fixup_found = 1;
1703 FSHOW((stderr,
1704 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1705 p, d6, d5, d4, d3, d2, d1, data));
1706 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1708 /* the case of LEA reg,[disp32] */
1709 if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1710 fixup_found = 1;
1711 FSHOW((stderr,
1712 "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1713 p, d6, d5, d4, d3, d2, d1, data));
1714 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1718 /* Check for constant references. */
1719 /* Check for a 32 bit word that looks like an absolute
1720 reference to within the constant vector. Constant references
1721 will be aligned. */
1722 if ((data >= (void*)(constants_start_addr-displacement))
1723 && (data < (void*)(constants_end_addr-displacement))
1724 && (((unsigned)data & 0x3) == 0)) {
1725 /* Mov eax,m32 */
1726 if (d1 == 0xa1) {
1727 fixup_found = 1;
1728 FSHOW((stderr,
1729 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1730 p, d6, d5, d4, d3, d2, d1, data));
1731 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1734 /* the case of MOV m32,EAX */
1735 if (d1 == 0xa3) {
1736 fixup_found = 1;
1737 FSHOW((stderr,
1738 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1739 p, d6, d5, d4, d3, d2, d1, data));
1740 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1743 /* the case of CMP m32,imm32 */
1744 if ((d1 == 0x3d) && (d2 == 0x81)) {
1745 fixup_found = 1;
1746 FSHOW((stderr,
1747 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1748 p, d6, d5, d4, d3, d2, d1, data));
1749 /* XX Check this */
1750 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1753 /* Check for a mod=00, r/m=101 byte. */
1754 if ((d1 & 0xc7) == 5) {
1755 /* Cmp m32,reg */
1756 if (d2 == 0x39) {
1757 fixup_found = 1;
1758 FSHOW((stderr,
1759 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1760 p, d6, d5, d4, d3, d2, d1, data));
1761 FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1763 /* the case of CMP reg32,m32 */
1764 if (d2 == 0x3b) {
1765 fixup_found = 1;
1766 FSHOW((stderr,
1767 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1768 p, d6, d5, d4, d3, d2, d1, data));
1769 FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1771 /* the case of MOV m32,reg32 */
1772 if (d2 == 0x89) {
1773 fixup_found = 1;
1774 FSHOW((stderr,
1775 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1776 p, d6, d5, d4, d3, d2, d1, data));
1777 FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1779 /* the case of MOV reg32,m32 */
1780 if (d2 == 0x8b) {
1781 fixup_found = 1;
1782 FSHOW((stderr,
1783 "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1784 p, d6, d5, d4, d3, d2, d1, data));
1785 FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1787 /* the case of LEA reg32,m32 */
1788 if (d2 == 0x8d) {
1789 fixup_found = 1;
1790 FSHOW((stderr,
1791 "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1792 p, d6, d5, d4, d3, d2, d1, data));
1793 FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1799 /* If anything was found, print some information on the code
1800 * object. */
1801 if (fixup_found) {
1802 FSHOW((stderr,
1803 "/compiled code object at %x: header words = %d, code words = %d\n",
1804 code, nheader_words, ncode_words));
1805 FSHOW((stderr,
1806 "/const start = %x, end = %x\n",
1807 constants_start_addr, constants_end_addr));
1808 FSHOW((stderr,
1809 "/code start = %x, end = %x\n",
1810 code_start_addr, code_end_addr));
1813 #endif
1815 #ifdef LISP_FEATURE_X86
1816 void
1817 gencgc_apply_code_fixups(struct code *old_code, struct code *new_code)
1819 sword_t nheader_words, ncode_words, nwords;
1820 os_vm_address_t constants_start_addr, constants_end_addr;
1821 os_vm_address_t code_start_addr, code_end_addr;
1822 os_vm_address_t code_addr = (os_vm_address_t)new_code;
1823 os_vm_address_t old_addr = (os_vm_address_t)old_code;
1824 os_vm_size_t displacement = code_addr - old_addr;
1825 lispobj fixups = NIL;
1826 struct vector *fixups_vector;
1828 ncode_words = code_instruction_words(new_code->code_size);
1829 nheader_words = code_header_words(*(lispobj *)new_code);
1830 nwords = ncode_words + nheader_words;
1831 /* FSHOW((stderr,
1832 "/compiled code object at %x: header words = %d, code words = %d\n",
1833 new_code, nheader_words, ncode_words)); */
1834 constants_start_addr = code_addr + 5*N_WORD_BYTES;
1835 constants_end_addr = code_addr + nheader_words*N_WORD_BYTES;
1836 code_start_addr = code_addr + nheader_words*N_WORD_BYTES;
1837 code_end_addr = code_addr + nwords*N_WORD_BYTES;
1839 FSHOW((stderr,
1840 "/const start = %x, end = %x\n",
1841 constants_start_addr,constants_end_addr));
1842 FSHOW((stderr,
1843 "/code start = %x; end = %x\n",
1844 code_start_addr,code_end_addr));
1847 /* The first constant should be a pointer to the fixups for this
1848 code objects. Check. */
1849 fixups = new_code->constants[0];
1851 /* It will be 0 or the unbound-marker if there are no fixups (as
1852 * will be the case if the code object has been purified, for
1853 * example) and will be an other pointer if it is valid. */
1854 if ((fixups == 0) || (fixups == UNBOUND_MARKER_WIDETAG) ||
1855 !is_lisp_pointer(fixups)) {
1856 /* Check for possible errors. */
1857 if (check_code_fixups)
1858 sniff_code_object(new_code, displacement);
1860 return;
1863 fixups_vector = (struct vector *)native_pointer(fixups);
1865 /* Could be pointing to a forwarding pointer. */
1866 /* FIXME is this always in from_space? if so, could replace this code with
1867 * forwarding_pointer_p/forwarding_pointer_value */
1868 if (is_lisp_pointer(fixups) &&
1869 (find_page_index((void*)fixups_vector) != -1) &&
1870 (fixups_vector->header == 0x01)) {
1871 /* If so, then follow it. */
1872 /*SHOW("following pointer to a forwarding pointer");*/
1873 fixups_vector =
1874 (struct vector *)native_pointer((lispobj)fixups_vector->length);
1877 /*SHOW("got fixups");*/
1879 if (widetag_of(fixups_vector->header) == SIMPLE_ARRAY_WORD_WIDETAG) {
1880 /* Got the fixups for the code block. Now work through the vector,
1881 and apply a fixup at each address. */
1882 sword_t length = fixnum_value(fixups_vector->length);
1883 sword_t i;
1884 for (i = 0; i < length; i++) {
1885 long offset = fixups_vector->data[i];
1886 /* Now check the current value of offset. */
1887 os_vm_address_t old_value = *(os_vm_address_t *)(code_start_addr + offset);
1889 /* If it's within the old_code object then it must be an
1890 * absolute fixup (relative ones are not saved) */
1891 if ((old_value >= old_addr)
1892 && (old_value < (old_addr + nwords*N_WORD_BYTES)))
1893 /* So add the dispacement. */
1894 *(os_vm_address_t *)(code_start_addr + offset) =
1895 old_value + displacement;
1896 else
1897 /* It is outside the old code object so it must be a
1898 * relative fixup (absolute fixups are not saved). So
1899 * subtract the displacement. */
1900 *(os_vm_address_t *)(code_start_addr + offset) =
1901 old_value - displacement;
1903 } else {
1904 /* This used to just print a note to stderr, but a bogus fixup seems to
1905 * indicate real heap corruption, so a hard hailure is in order. */
1906 lose("fixup vector %p has a bad widetag: %d\n",
1907 fixups_vector, widetag_of(fixups_vector->header));
1910 /* Check for possible errors. */
1911 if (check_code_fixups) {
1912 sniff_code_object(new_code,displacement);
1915 #endif
1917 static lispobj
1918 trans_boxed_large(lispobj object)
1920 lispobj header;
1921 uword_t length;
1923 gc_assert(is_lisp_pointer(object));
1925 header = *((lispobj *) native_pointer(object));
1926 length = HeaderValue(header) + 1;
1927 length = CEILING(length, 2);
1929 return copy_large_object(object, length);
1933 * weak pointers
1936 /* XX This is a hack adapted from cgc.c. These don't work too
1937 * efficiently with the gencgc as a list of the weak pointers is
1938 * maintained within the objects which causes writes to the pages. A
1939 * limited attempt is made to avoid unnecessary writes, but this needs
1940 * a re-think. */
1941 #define WEAK_POINTER_NWORDS \
1942 CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
1944 static sword_t
1945 scav_weak_pointer(lispobj *where, lispobj object)
1947 /* Since we overwrite the 'next' field, we have to make
1948 * sure not to do so for pointers already in the list.
1949 * Instead of searching the list of weak_pointers each
1950 * time, we ensure that next is always NULL when the weak
1951 * pointer isn't in the list, and not NULL otherwise.
1952 * Since we can't use NULL to denote end of list, we
1953 * use a pointer back to the same weak_pointer.
1955 struct weak_pointer * wp = (struct weak_pointer*)where;
1957 if (NULL == wp->next) {
1958 wp->next = weak_pointers;
1959 weak_pointers = wp;
1960 if (NULL == wp->next)
1961 wp->next = wp;
1964 /* Do not let GC scavenge the value slot of the weak pointer.
1965 * (That is why it is a weak pointer.) */
1967 return WEAK_POINTER_NWORDS;
1971 lispobj *
1972 search_read_only_space(void *pointer)
1974 lispobj *start = (lispobj *) READ_ONLY_SPACE_START;
1975 lispobj *end = (lispobj *) SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
1976 if ((pointer < (void *)start) || (pointer >= (void *)end))
1977 return NULL;
1978 return (gc_search_space(start,
1979 (((lispobj *)pointer)+2)-start,
1980 (lispobj *) pointer));
1983 lispobj *
1984 search_static_space(void *pointer)
1986 lispobj *start = (lispobj *)STATIC_SPACE_START;
1987 lispobj *end = (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
1988 if ((pointer < (void *)start) || (pointer >= (void *)end))
1989 return NULL;
1990 return (gc_search_space(start,
1991 (((lispobj *)pointer)+2)-start,
1992 (lispobj *) pointer));
1995 /* a faster version for searching the dynamic space. This will work even
1996 * if the object is in a current allocation region. */
1997 lispobj *
1998 search_dynamic_space(void *pointer)
2000 page_index_t page_index = find_page_index(pointer);
2001 lispobj *start;
2003 /* The address may be invalid, so do some checks. */
2004 if ((page_index == -1) || page_free_p(page_index))
2005 return NULL;
2006 start = (lispobj *)page_scan_start(page_index);
2007 return (gc_search_space(start,
2008 (((lispobj *)pointer)+2)-start,
2009 (lispobj *)pointer));
2012 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2014 /* Is there any possibility that pointer is a valid Lisp object
2015 * reference, and/or something else (e.g. subroutine call return
2016 * address) which should prevent us from moving the referred-to thing?
2017 * This is called from preserve_pointers() */
2018 static int
2019 possibly_valid_dynamic_space_pointer_s(lispobj *pointer,
2020 page_index_t addr_page_index,
2021 lispobj **store_here)
2023 lispobj *start_addr;
2025 /* Find the object start address. */
2026 start_addr = search_dynamic_space(pointer);
2028 if (start_addr == NULL) {
2029 return 0;
2031 if (store_here) {
2032 *store_here = start_addr;
2035 /* If the containing object is a code object, presume that the
2036 * pointer is valid, simply because it could be an unboxed return
2037 * address. */
2038 if (widetag_of(*start_addr) == CODE_HEADER_WIDETAG)
2039 return 1;
2041 /* Large object pages only contain ONE object, and it will never
2042 * be a CONS. However, arrays and bignums can be allocated larger
2043 * than necessary and then shrunk to fit, leaving what look like
2044 * (0 . 0) CONSes at the end. These appear valid to
2045 * looks_like_valid_lisp_pointer_p(), so pick them off here. */
2046 if (page_table[addr_page_index].large_object &&
2047 (lowtag_of((lispobj)pointer) == LIST_POINTER_LOWTAG))
2048 return 0;
2050 return looks_like_valid_lisp_pointer_p((lispobj)pointer, start_addr);
2053 #endif // defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2055 static int
2056 valid_conservative_root_p(void *addr, page_index_t addr_page_index,
2057 lispobj **begin_ptr)
2059 #ifdef GENCGC_IS_PRECISE
2060 /* If we're in precise gencgc (non-x86oid as of this writing) then
2061 * we are only called on valid object pointers in the first place,
2062 * so we just have to do a bounds-check against the heap, a
2063 * generation check, and the already-pinned check. */
2064 if ((addr_page_index == -1)
2065 || (page_table[addr_page_index].gen != from_space)
2066 || (page_table[addr_page_index].dont_move != 0))
2067 return 0;
2068 #else
2069 /* quick check 1: Address is quite likely to have been invalid. */
2070 if ((addr_page_index == -1)
2071 || page_free_p(addr_page_index)
2072 || (page_table[addr_page_index].bytes_used == 0)
2073 || (page_table[addr_page_index].gen != from_space))
2074 return 0;
2075 gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2077 /* quick check 2: Check the offset within the page.
2080 if (((uword_t)addr & (GENCGC_CARD_BYTES - 1)) >
2081 page_table[addr_page_index].bytes_used)
2082 return 0;
2084 /* Filter out anything which can't be a pointer to a Lisp object
2085 * (or, as a special case which also requires dont_move, a return
2086 * address referring to something in a CodeObject). This is
2087 * expensive but important, since it vastly reduces the
2088 * probability that random garbage will be bogusly interpreted as
2089 * a pointer which prevents a page from moving. */
2090 if (!possibly_valid_dynamic_space_pointer_s(addr, addr_page_index,
2091 begin_ptr))
2092 return 0;
2093 #endif
2095 return 1;
2098 boolean
2099 in_dontmove_nativeptr_p(page_index_t page_index, lispobj *native_ptr)
2101 in_use_marker_t *markers = pinned_dwords(page_index);
2102 if (markers) {
2103 lispobj *begin = page_address(page_index);
2104 int dword_in_page = (native_ptr - begin) / 2;
2105 return (markers[dword_in_page / N_WORD_BITS] >> (dword_in_page % N_WORD_BITS)) & 1;
2106 } else {
2107 return 0;
2111 /* Adjust large bignum and vector objects. This will adjust the
2112 * allocated region if the size has shrunk, and move unboxed objects
2113 * into unboxed pages. The pages are not promoted here, and the
2114 * promoted region is not added to the new_regions; this is really
2115 * only designed to be called from preserve_pointer(). Shouldn't fail
2116 * if this is missed, just may delay the moving of objects to unboxed
2117 * pages, and the freeing of pages. */
2118 static void
2119 maybe_adjust_large_object(lispobj *where)
2121 page_index_t first_page;
2122 page_index_t next_page;
2123 sword_t nwords;
2125 uword_t remaining_bytes;
2126 uword_t bytes_freed;
2127 uword_t old_bytes_used;
2129 int boxed;
2131 /* Check whether it's a vector or bignum object. */
2132 switch (widetag_of(where[0])) {
2133 case SIMPLE_VECTOR_WIDETAG:
2134 boxed = BOXED_PAGE_FLAG;
2135 break;
2136 case BIGNUM_WIDETAG:
2137 case SIMPLE_BASE_STRING_WIDETAG:
2138 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2139 case SIMPLE_CHARACTER_STRING_WIDETAG:
2140 #endif
2141 case SIMPLE_BIT_VECTOR_WIDETAG:
2142 case SIMPLE_ARRAY_NIL_WIDETAG:
2143 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2144 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2145 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2146 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2147 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2148 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2150 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
2152 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2153 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2154 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2155 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2156 #endif
2157 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2158 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2159 #endif
2160 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2161 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2162 #endif
2163 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2164 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2165 #endif
2167 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
2169 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2170 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2171 #endif
2172 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2173 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2174 #endif
2175 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2176 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2177 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2178 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2179 #endif
2180 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2181 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2182 #endif
2183 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2184 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2185 #endif
2186 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2187 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2188 #endif
2189 boxed = UNBOXED_PAGE_FLAG;
2190 break;
2191 default:
2192 return;
2195 /* Find its current size. */
2196 nwords = (sizetab[widetag_of(where[0])])(where);
2198 first_page = find_page_index((void *)where);
2199 gc_assert(first_page >= 0);
2201 /* Note: Any page write-protection must be removed, else a later
2202 * scavenge_newspace may incorrectly not scavenge these pages.
2203 * This would not be necessary if they are added to the new areas,
2204 * but lets do it for them all (they'll probably be written
2205 * anyway?). */
2207 gc_assert(page_starts_contiguous_block_p(first_page));
2209 next_page = first_page;
2210 remaining_bytes = nwords*N_WORD_BYTES;
2211 while (remaining_bytes > GENCGC_CARD_BYTES) {
2212 gc_assert(page_table[next_page].gen == from_space);
2213 gc_assert(page_allocated_no_region_p(next_page));
2214 gc_assert(page_table[next_page].large_object);
2215 gc_assert(page_table[next_page].scan_start_offset ==
2216 npage_bytes(next_page-first_page));
2217 gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
2219 page_table[next_page].allocated = boxed;
2221 /* Shouldn't be write-protected at this stage. Essential that the
2222 * pages aren't. */
2223 gc_assert(!page_table[next_page].write_protected);
2224 remaining_bytes -= GENCGC_CARD_BYTES;
2225 next_page++;
2228 /* Now only one page remains, but the object may have shrunk so
2229 * there may be more unused pages which will be freed. */
2231 /* Object may have shrunk but shouldn't have grown - check. */
2232 gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2234 page_table[next_page].allocated = boxed;
2235 gc_assert(page_table[next_page].allocated ==
2236 page_table[first_page].allocated);
2238 /* Adjust the bytes_used. */
2239 old_bytes_used = page_table[next_page].bytes_used;
2240 page_table[next_page].bytes_used = remaining_bytes;
2242 bytes_freed = old_bytes_used - remaining_bytes;
2244 /* Free any remaining pages; needs care. */
2245 next_page++;
2246 while ((old_bytes_used == GENCGC_CARD_BYTES) &&
2247 (page_table[next_page].gen == from_space) &&
2248 page_allocated_no_region_p(next_page) &&
2249 page_table[next_page].large_object &&
2250 (page_table[next_page].scan_start_offset ==
2251 npage_bytes(next_page - first_page))) {
2252 /* It checks out OK, free the page. We don't need to both zeroing
2253 * pages as this should have been done before shrinking the
2254 * object. These pages shouldn't be write protected as they
2255 * should be zero filled. */
2256 gc_assert(page_table[next_page].write_protected == 0);
2258 old_bytes_used = page_table[next_page].bytes_used;
2259 page_table[next_page].allocated = FREE_PAGE_FLAG;
2260 page_table[next_page].bytes_used = 0;
2261 bytes_freed += old_bytes_used;
2262 next_page++;
2265 if ((bytes_freed > 0) && gencgc_verbose) {
2266 FSHOW((stderr,
2267 "/maybe_adjust_large_object() freed %d\n",
2268 bytes_freed));
2271 generations[from_space].bytes_allocated -= bytes_freed;
2272 bytes_allocated -= bytes_freed;
2274 return;
2278 * Why is this restricted to protected objects only?
2279 * Because the rest of the page has been scavenged already,
2280 * and since that leaves forwarding pointers in the unprotected
2281 * areas you cannot scavenge it again until those are gone.
2283 static void
2284 scavenge_pinned_range(void* page_base, int start, int count)
2286 // 'start' and 'count' are expressed in units of dwords
2287 scavenge((lispobj*)page_base + 2*start, 2*count);
2290 static void
2291 scavenge_pinned_ranges()
2293 page_index_t page;
2294 for (page = 0; page < last_free_page; page++) {
2295 in_use_marker_t* bitmap = pinned_dwords(page);
2296 if (bitmap)
2297 bitmap_scan(bitmap,
2298 GENCGC_CARD_BYTES / (2*N_WORD_BYTES) / N_WORD_BITS,
2299 0, scavenge_pinned_range, page_address(page));
2303 static void wipe_range(void* page_base, int start, int count)
2305 bzero((lispobj*)page_base + 2*start, count*2*N_WORD_BYTES);
2308 static void
2309 wipe_nonpinned_words()
2311 page_index_t i;
2312 in_use_marker_t* bitmap;
2314 for (i = 0; i < last_free_page; i++) {
2315 if (page_table[i].dont_move && (bitmap = pinned_dwords(i)) != 0) {
2316 bitmap_scan(bitmap,
2317 GENCGC_CARD_BYTES / (2*N_WORD_BYTES) / N_WORD_BITS,
2318 BIT_SCAN_INVERT | BIT_SCAN_CLEAR,
2319 wipe_range, page_address(i));
2320 page_table[i].has_pin_map = 0;
2321 // move the page to newspace
2322 generations[new_space].bytes_allocated += page_table[i].bytes_used;
2323 generations[page_table[i].gen].bytes_allocated -= page_table[i].bytes_used;
2324 page_table[i].gen = new_space;
2327 #ifndef LISP_FEATURE_WIN32
2328 madvise(page_table_pinned_dwords, pins_map_size_in_bytes, MADV_DONTNEED);
2329 #endif
2332 static void
2333 pin_words(page_index_t pageindex, lispobj *mark_which_pointer)
2335 struct page *page = &page_table[pageindex];
2337 if (!do_wipe_p)
2338 return;
2340 gc_assert(mark_which_pointer);
2341 if (!page->has_pin_map) {
2342 page->has_pin_map = 1;
2343 #ifdef DEBUG
2345 int i;
2346 in_use_marker_t* map = pinned_dwords(pageindex);
2347 for (i=0; i<n_dwords_in_card/N_WORD_BITS; ++i)
2348 gc_assert(map[i] == 0);
2350 #endif
2352 lispobj header = *mark_which_pointer;
2353 int size = 2;
2354 // Don't bother calling a sizing function for fixnums or pointers.
2355 // The object pointed to must be a cons.
2356 if (!fixnump(header) && !is_lisp_pointer(header)) {
2357 size = (sizetab[widetag_of(header)])(mark_which_pointer);
2358 if (size == 1 && (lowtag_of(header) == 9 || lowtag_of(header) == 2))
2359 size = 2;
2361 gc_assert(size % 2 == 0);
2362 lispobj *page_base = page_address(pageindex);
2363 unsigned int begin_dword_index = (mark_which_pointer - page_base) / 2;
2364 unsigned int end_dword_index = begin_dword_index + size / 2;
2365 unsigned int index;
2366 in_use_marker_t *bitmap = pinned_dwords(pageindex);
2367 for (index = begin_dword_index; index < end_dword_index; index++)
2368 bitmap[index/N_WORD_BITS] |= (uword_t)1 << (index % N_WORD_BITS);
2371 /* Take a possible pointer to a Lisp object and mark its page in the
2372 * page_table so that it will not be relocated during a GC.
2374 * This involves locating the page it points to, then backing up to
2375 * the start of its region, then marking all pages dont_move from there
2376 * up to the first page that's not full or has a different generation
2378 * It is assumed that all the page static flags have been cleared at
2379 * the start of a GC.
2381 * It is also assumed that the current gc_alloc() region has been
2382 * flushed and the tables updated. */
2384 // TODO: there's probably a way to be a little more efficient here.
2385 // As things are, we start by finding the object that encloses 'addr',
2386 // then we see if 'addr' was a "valid" Lisp pointer to that object
2387 // - meaning we expect the correct lowtag on the pointer - except
2388 // that for code objects we don't require a correct lowtag
2389 // and we allow a pointer to anywhere in the object.
2391 // It should be possible to avoid calling search_dynamic_space
2392 // more of the time. First, check if the page pointed to might hold code.
2393 // If it does, then we continue regardless of the pointer's lowtag
2394 // (because of the special allowance). If the page definitely does *not*
2395 // hold code, then we require up front that the lowtake make sense,
2396 // by doing the same checks that are in looks_like_valid_lisp_pointer_p.
2398 // Problem: when code is allocated from a per-thread region,
2399 // does it ensure that the occupied pages are flagged as having code?
2401 static void
2402 preserve_pointer(void *addr)
2404 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2405 /* Immobile space MUST be lower than dynamic space,
2406 or else this test needs to be revised */
2407 if (addr < (void*)IMMOBILE_SPACE_END) {
2408 extern void immobile_space_preserve_pointer(void*);
2409 immobile_space_preserve_pointer(addr);
2410 return;
2412 #endif
2413 page_index_t addr_page_index = find_page_index(addr);
2414 page_index_t first_page;
2415 page_index_t i;
2416 unsigned int region_allocation;
2417 lispobj *begin_ptr = NULL;
2419 if (!valid_conservative_root_p(addr, addr_page_index, &begin_ptr))
2420 return;
2422 /* (Now that we know that addr_page_index is in range, it's
2423 * safe to index into page_table[] with it.) */
2424 region_allocation = page_table[addr_page_index].allocated;
2426 /* Find the beginning of the region. Note that there may be
2427 * objects in the region preceding the one that we were passed a
2428 * pointer to: if this is the case, we will write-protect all the
2429 * previous objects' pages too. */
2431 #if 0
2432 /* I think this'd work just as well, but without the assertions.
2433 * -dan 2004.01.01 */
2434 first_page = find_page_index(page_scan_start(addr_page_index))
2435 #else
2436 first_page = addr_page_index;
2437 while (!page_starts_contiguous_block_p(first_page)) {
2438 --first_page;
2439 /* Do some checks. */
2440 gc_assert(page_table[first_page].bytes_used == GENCGC_CARD_BYTES);
2441 gc_assert(page_table[first_page].gen == from_space);
2442 gc_assert(page_table[first_page].allocated == region_allocation);
2444 #endif
2446 /* Adjust any large objects before promotion as they won't be
2447 * copied after promotion. */
2448 if (page_table[first_page].large_object) {
2449 maybe_adjust_large_object(page_address(first_page));
2450 /* It may have moved to unboxed pages. */
2451 region_allocation = page_table[first_page].allocated;
2454 /* Now work forward until the end of this contiguous area is found,
2455 * marking all pages as dont_move. */
2456 for (i = first_page; ;i++) {
2457 gc_assert(page_table[i].allocated == region_allocation);
2459 /* Mark the page static. */
2460 page_table[i].dont_move = 1;
2462 /* It is essential that the pages are not write protected as
2463 * they may have pointers into the old-space which need
2464 * scavenging. They shouldn't be write protected at this
2465 * stage. */
2466 gc_assert(!page_table[i].write_protected);
2468 /* Check whether this is the last page in this contiguous block.. */
2469 if (page_ends_contiguous_block_p(i, from_space))
2470 break;
2473 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2474 /* Do not do this for multi-page objects. Those pages do not need
2475 * object wipeout anyway.
2477 if (i == first_page) {
2478 /* We need the pointer to the beginning of the object
2479 * We might have gotten it above but maybe not, so make sure
2481 if (begin_ptr == NULL) {
2482 possibly_valid_dynamic_space_pointer_s(addr, first_page,
2483 &begin_ptr);
2485 pin_words(first_page, begin_ptr);
2487 #endif
2489 /* Check that the page is now static. */
2490 gc_assert(page_table[addr_page_index].dont_move != 0);
2493 /* If the given page is not write-protected, then scan it for pointers
2494 * to younger generations or the top temp. generation, if no
2495 * suspicious pointers are found then the page is write-protected.
2497 * Care is taken to check for pointers to the current gc_alloc()
2498 * region if it is a younger generation or the temp. generation. This
2499 * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2500 * the gc_alloc_generation does not need to be checked as this is only
2501 * called from scavenge_generation() when the gc_alloc generation is
2502 * younger, so it just checks if there is a pointer to the current
2503 * region.
2505 * We return 1 if the page was write-protected, else 0. */
2506 static int
2507 update_page_write_prot(page_index_t page)
2509 generation_index_t gen = page_table[page].gen;
2510 sword_t j;
2511 int wp_it = 1;
2512 void **page_addr = (void **)page_address(page);
2513 sword_t num_words = page_table[page].bytes_used / N_WORD_BYTES;
2515 /* Shouldn't be a free page. */
2516 gc_assert(page_allocated_p(page));
2517 gc_assert(page_table[page].bytes_used != 0);
2519 /* Skip if it's already write-protected, pinned, or unboxed */
2520 if (page_table[page].write_protected
2521 /* FIXME: What's the reason for not write-protecting pinned pages? */
2522 || page_table[page].dont_move
2523 || page_unboxed_p(page))
2524 return (0);
2526 /* Scan the page for pointers to younger generations or the
2527 * top temp. generation. */
2529 /* This is conservative: any word satisfying is_lisp_pointer() is
2530 * assumed to be a pointer. To do otherwise would require a family
2531 * of scavenge-like functions. */
2532 for (j = 0; j < num_words; j++) {
2533 void *ptr = *(page_addr+j);
2534 page_index_t index;
2535 lispobj __attribute__((unused)) header;
2537 if (!is_lisp_pointer((lispobj)ptr))
2538 continue;
2539 /* Check that it's in the dynamic space */
2540 if ((index = find_page_index(ptr)) != -1) {
2541 if (/* Does it point to a younger or the temp. generation? */
2542 (page_allocated_p(index)
2543 && (page_table[index].bytes_used != 0)
2544 && ((page_table[index].gen < gen)
2545 || (page_table[index].gen == SCRATCH_GENERATION)))
2547 /* Or does it point within a current gc_alloc() region? */
2548 || ((boxed_region.start_addr <= ptr)
2549 && (ptr <= boxed_region.free_pointer))
2550 || ((unboxed_region.start_addr <= ptr)
2551 && (ptr <= unboxed_region.free_pointer))) {
2552 wp_it = 0;
2553 break;
2556 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2557 else if ((index = find_immobile_page_index(ptr)) >= 0 &&
2558 other_immediate_lowtag_p(header = *native_pointer((lispobj)ptr))) {
2559 // This is *possibly* a pointer to an object in immobile space,
2560 // given that above two conditions were satisfied.
2561 // But unlike in the dynamic space case, we need to read a byte
2562 // from the object to determine its generation, which requires care.
2563 // Consider an unboxed word that looks like a pointer to a word that
2564 // looks like fun-header-widetag. We can't naively back up to the
2565 // underlying code object since the alleged header might not be one.
2566 int obj_gen = gen; // Make comparison fail if we fall through
2567 if (lowtag_of((lispobj)ptr) != FUN_POINTER_LOWTAG) {
2568 obj_gen = __immobile_obj_generation(native_pointer((lispobj)ptr));
2569 } else if (widetag_of(header) == SIMPLE_FUN_HEADER_WIDETAG) {
2570 struct code* code =
2571 code_obj_from_simple_fun((struct simple_fun *)
2572 ((lispobj)ptr - FUN_POINTER_LOWTAG));
2573 // This is a heuristic, since we're not actually looking for
2574 // an object boundary. Precise scanning of 'page' would obviate
2575 // the guard conditions here.
2576 if ((lispobj)code >= IMMOBILE_VARYOBJ_SUBSPACE_START
2577 && widetag_of(code->header) == CODE_HEADER_WIDETAG)
2578 obj_gen = __immobile_obj_generation((lispobj*)code);
2580 // A bogus generation number implies a not-really-pointer,
2581 // but it won't cause misbehavior.
2582 if (obj_gen < gen || obj_gen == SCRATCH_GENERATION) {
2583 wp_it = 0;
2584 break;
2587 #endif
2590 if (wp_it == 1) {
2591 /* Write-protect the page. */
2592 /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2594 os_protect((void *)page_addr,
2595 GENCGC_CARD_BYTES,
2596 OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2598 /* Note the page as protected in the page tables. */
2599 page_table[page].write_protected = 1;
2602 return (wp_it);
2605 /* Scavenge all generations from FROM to TO, inclusive, except for
2606 * new_space which needs special handling, as new objects may be
2607 * added which are not checked here - use scavenge_newspace generation.
2609 * Write-protected pages should not have any pointers to the
2610 * from_space so do need scavenging; thus write-protected pages are
2611 * not always scavenged. There is some code to check that these pages
2612 * are not written; but to check fully the write-protected pages need
2613 * to be scavenged by disabling the code to skip them.
2615 * Under the current scheme when a generation is GCed the younger
2616 * generations will be empty. So, when a generation is being GCed it
2617 * is only necessary to scavenge the older generations for pointers
2618 * not the younger. So a page that does not have pointers to younger
2619 * generations does not need to be scavenged.
2621 * The write-protection can be used to note pages that don't have
2622 * pointers to younger pages. But pages can be written without having
2623 * pointers to younger generations. After the pages are scavenged here
2624 * they can be scanned for pointers to younger generations and if
2625 * there are none the page can be write-protected.
2627 * One complication is when the newspace is the top temp. generation.
2629 * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2630 * that none were written, which they shouldn't be as they should have
2631 * no pointers to younger generations. This breaks down for weak
2632 * pointers as the objects contain a link to the next and are written
2633 * if a weak pointer is scavenged. Still it's a useful check. */
2634 static void
2635 scavenge_generations(generation_index_t from, generation_index_t to)
2637 page_index_t i;
2638 page_index_t num_wp = 0;
2640 #define SC_GEN_CK 0
2641 #if SC_GEN_CK
2642 /* Clear the write_protected_cleared flags on all pages. */
2643 for (i = 0; i < page_table_pages; i++)
2644 page_table[i].write_protected_cleared = 0;
2645 #endif
2647 for (i = 0; i < last_free_page; i++) {
2648 generation_index_t generation = page_table[i].gen;
2649 if (page_boxed_p(i)
2650 && (page_table[i].bytes_used != 0)
2651 && (generation != new_space)
2652 && (generation >= from)
2653 && (generation <= to)) {
2654 page_index_t last_page,j;
2655 int write_protected=1;
2657 /* This should be the start of a region */
2658 gc_assert(page_starts_contiguous_block_p(i));
2660 /* Now work forward until the end of the region */
2661 for (last_page = i; ; last_page++) {
2662 write_protected =
2663 write_protected && page_table[last_page].write_protected;
2664 if (page_ends_contiguous_block_p(last_page, generation))
2665 break;
2667 if (!write_protected) {
2668 scavenge(page_address(i),
2669 ((uword_t)(page_table[last_page].bytes_used
2670 + npage_bytes(last_page-i)))
2671 /N_WORD_BYTES);
2673 /* Now scan the pages and write protect those that
2674 * don't have pointers to younger generations. */
2675 if (enable_page_protection) {
2676 for (j = i; j <= last_page; j++) {
2677 num_wp += update_page_write_prot(j);
2680 if ((gencgc_verbose > 1) && (num_wp != 0)) {
2681 FSHOW((stderr,
2682 "/write protected %d pages within generation %d\n",
2683 num_wp, generation));
2686 i = last_page;
2690 #if SC_GEN_CK
2691 /* Check that none of the write_protected pages in this generation
2692 * have been written to. */
2693 for (i = 0; i < page_table_pages; i++) {
2694 if (page_allocated_p(i)
2695 && (page_table[i].bytes_used != 0)
2696 && (page_table[i].gen == generation)
2697 && (page_table[i].write_protected_cleared != 0)) {
2698 FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2699 FSHOW((stderr,
2700 "/page bytes_used=%d scan_start_offset=%lu dont_move=%d\n",
2701 page_table[i].bytes_used,
2702 page_table[i].scan_start_offset,
2703 page_table[i].dont_move));
2704 lose("write to protected page %d in scavenge_generation()\n", i);
2707 #endif
2711 /* Scavenge a newspace generation. As it is scavenged new objects may
2712 * be allocated to it; these will also need to be scavenged. This
2713 * repeats until there are no more objects unscavenged in the
2714 * newspace generation.
2716 * To help improve the efficiency, areas written are recorded by
2717 * gc_alloc() and only these scavenged. Sometimes a little more will be
2718 * scavenged, but this causes no harm. An easy check is done that the
2719 * scavenged bytes equals the number allocated in the previous
2720 * scavenge.
2722 * Write-protected pages are not scanned except if they are marked
2723 * dont_move in which case they may have been promoted and still have
2724 * pointers to the from space.
2726 * Write-protected pages could potentially be written by alloc however
2727 * to avoid having to handle re-scavenging of write-protected pages
2728 * gc_alloc() does not write to write-protected pages.
2730 * New areas of objects allocated are recorded alternatively in the two
2731 * new_areas arrays below. */
2732 static struct new_area new_areas_1[NUM_NEW_AREAS];
2733 static struct new_area new_areas_2[NUM_NEW_AREAS];
2735 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2736 extern unsigned int immobile_scav_queue_count;
2737 extern void
2738 gc_init_immobile(),
2739 update_immobile_nursery_bits(),
2740 scavenge_immobile_roots(generation_index_t,generation_index_t),
2741 scavenge_immobile_newspace(),
2742 sweep_immobile_space(int raise),
2743 write_protect_immobile_space();
2744 #else
2745 #define immobile_scav_queue_count 0
2746 #endif
2748 /* Do one full scan of the new space generation. This is not enough to
2749 * complete the job as new objects may be added to the generation in
2750 * the process which are not scavenged. */
2751 static void
2752 scavenge_newspace_generation_one_scan(generation_index_t generation)
2754 page_index_t i;
2756 FSHOW((stderr,
2757 "/starting one full scan of newspace generation %d\n",
2758 generation));
2759 for (i = 0; i < last_free_page; i++) {
2760 /* Note that this skips over open regions when it encounters them. */
2761 if (page_boxed_p(i)
2762 && (page_table[i].bytes_used != 0)
2763 && (page_table[i].gen == generation)
2764 && ((page_table[i].write_protected == 0)
2765 /* (This may be redundant as write_protected is now
2766 * cleared before promotion.) */
2767 || (page_table[i].dont_move == 1))) {
2768 page_index_t last_page;
2769 int all_wp=1;
2771 /* The scavenge will start at the scan_start_offset of
2772 * page i.
2774 * We need to find the full extent of this contiguous
2775 * block in case objects span pages.
2777 * Now work forward until the end of this contiguous area
2778 * is found. A small area is preferred as there is a
2779 * better chance of its pages being write-protected. */
2780 for (last_page = i; ;last_page++) {
2781 /* If all pages are write-protected and movable,
2782 * then no need to scavenge */
2783 all_wp=all_wp && page_table[last_page].write_protected &&
2784 !page_table[last_page].dont_move;
2786 /* Check whether this is the last page in this
2787 * contiguous block */
2788 if (page_ends_contiguous_block_p(last_page, generation))
2789 break;
2792 /* Do a limited check for write-protected pages. */
2793 if (!all_wp) {
2794 sword_t nwords = (((uword_t)
2795 (page_table[last_page].bytes_used
2796 + npage_bytes(last_page-i)
2797 + page_table[i].scan_start_offset))
2798 / N_WORD_BYTES);
2799 new_areas_ignore_page = last_page;
2801 scavenge(page_scan_start(i), nwords);
2804 i = last_page;
2807 FSHOW((stderr,
2808 "/done with one full scan of newspace generation %d\n",
2809 generation));
2812 /* Do a complete scavenge of the newspace generation. */
2813 static void
2814 scavenge_newspace_generation(generation_index_t generation)
2816 size_t i;
2818 /* the new_areas array currently being written to by gc_alloc() */
2819 struct new_area (*current_new_areas)[] = &new_areas_1;
2820 size_t current_new_areas_index;
2822 /* the new_areas created by the previous scavenge cycle */
2823 struct new_area (*previous_new_areas)[] = NULL;
2824 size_t previous_new_areas_index;
2826 /* Flush the current regions updating the tables. */
2827 gc_alloc_update_all_page_tables(0);
2829 /* Turn on the recording of new areas by gc_alloc(). */
2830 new_areas = current_new_areas;
2831 new_areas_index = 0;
2833 /* Don't need to record new areas that get scavenged anyway during
2834 * scavenge_newspace_generation_one_scan. */
2835 record_new_objects = 1;
2837 /* Start with a full scavenge. */
2838 scavenge_newspace_generation_one_scan(generation);
2840 /* Record all new areas now. */
2841 record_new_objects = 2;
2843 /* Give a chance to weak hash tables to make other objects live.
2844 * FIXME: The algorithm implemented here for weak hash table gcing
2845 * is O(W^2+N) as Bruno Haible warns in
2846 * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
2847 * see "Implementation 2". */
2848 scav_weak_hash_tables();
2850 /* Flush the current regions updating the tables. */
2851 gc_alloc_update_all_page_tables(0);
2853 /* Grab new_areas_index. */
2854 current_new_areas_index = new_areas_index;
2856 /*FSHOW((stderr,
2857 "The first scan is finished; current_new_areas_index=%d.\n",
2858 current_new_areas_index));*/
2860 while (current_new_areas_index > 0 || immobile_scav_queue_count) {
2861 /* Move the current to the previous new areas */
2862 previous_new_areas = current_new_areas;
2863 previous_new_areas_index = current_new_areas_index;
2865 /* Scavenge all the areas in previous new areas. Any new areas
2866 * allocated are saved in current_new_areas. */
2868 /* Allocate an array for current_new_areas; alternating between
2869 * new_areas_1 and 2 */
2870 if (previous_new_areas == &new_areas_1)
2871 current_new_areas = &new_areas_2;
2872 else
2873 current_new_areas = &new_areas_1;
2875 /* Set up for gc_alloc(). */
2876 new_areas = current_new_areas;
2877 new_areas_index = 0;
2879 #ifdef LISP_FEATURE_IMMOBILE_SPACE
2880 scavenge_immobile_newspace();
2881 #endif
2882 /* Check whether previous_new_areas had overflowed. */
2883 if (previous_new_areas_index >= NUM_NEW_AREAS) {
2885 /* New areas of objects allocated have been lost so need to do a
2886 * full scan to be sure! If this becomes a problem try
2887 * increasing NUM_NEW_AREAS. */
2888 if (gencgc_verbose) {
2889 SHOW("new_areas overflow, doing full scavenge");
2892 /* Don't need to record new areas that get scavenged
2893 * anyway during scavenge_newspace_generation_one_scan. */
2894 record_new_objects = 1;
2896 scavenge_newspace_generation_one_scan(generation);
2898 /* Record all new areas now. */
2899 record_new_objects = 2;
2901 scav_weak_hash_tables();
2903 /* Flush the current regions updating the tables. */
2904 gc_alloc_update_all_page_tables(0);
2906 } else {
2908 /* Work through previous_new_areas. */
2909 for (i = 0; i < previous_new_areas_index; i++) {
2910 page_index_t page = (*previous_new_areas)[i].page;
2911 size_t offset = (*previous_new_areas)[i].offset;
2912 size_t size = (*previous_new_areas)[i].size / N_WORD_BYTES;
2913 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
2914 scavenge(page_address(page)+offset, size);
2917 scav_weak_hash_tables();
2919 /* Flush the current regions updating the tables. */
2920 gc_alloc_update_all_page_tables(0);
2923 current_new_areas_index = new_areas_index;
2925 /*FSHOW((stderr,
2926 "The re-scan has finished; current_new_areas_index=%d.\n",
2927 current_new_areas_index));*/
2930 /* Turn off recording of areas allocated by gc_alloc(). */
2931 record_new_objects = 0;
2933 #if SC_NS_GEN_CK
2935 page_index_t i;
2936 /* Check that none of the write_protected pages in this generation
2937 * have been written to. */
2938 for (i = 0; i < page_table_pages; i++) {
2939 if (page_allocated_p(i)
2940 && (page_table[i].bytes_used != 0)
2941 && (page_table[i].gen == generation)
2942 && (page_table[i].write_protected_cleared != 0)
2943 && (page_table[i].dont_move == 0)) {
2944 lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
2945 i, generation, page_table[i].dont_move);
2949 #endif
2952 /* Un-write-protect all the pages in from_space. This is done at the
2953 * start of a GC else there may be many page faults while scavenging
2954 * the newspace (I've seen drive the system time to 99%). These pages
2955 * would need to be unprotected anyway before unmapping in
2956 * free_oldspace; not sure what effect this has on paging.. */
2957 static void
2958 unprotect_oldspace(void)
2960 page_index_t i;
2961 void *region_addr = 0;
2962 void *page_addr = 0;
2963 uword_t region_bytes = 0;
2965 for (i = 0; i < last_free_page; i++) {
2966 if (page_allocated_p(i)
2967 && (page_table[i].bytes_used != 0)
2968 && (page_table[i].gen == from_space)) {
2970 /* Remove any write-protection. We should be able to rely
2971 * on the write-protect flag to avoid redundant calls. */
2972 if (page_table[i].write_protected) {
2973 page_table[i].write_protected = 0;
2974 page_addr = page_address(i);
2975 if (!region_addr) {
2976 /* First region. */
2977 region_addr = page_addr;
2978 region_bytes = GENCGC_CARD_BYTES;
2979 } else if (region_addr + region_bytes == page_addr) {
2980 /* Region continue. */
2981 region_bytes += GENCGC_CARD_BYTES;
2982 } else {
2983 /* Unprotect previous region. */
2984 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2985 /* First page in new region. */
2986 region_addr = page_addr;
2987 region_bytes = GENCGC_CARD_BYTES;
2992 if (region_addr) {
2993 /* Unprotect last region. */
2994 os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2998 /* Work through all the pages and free any in from_space. This
2999 * assumes that all objects have been copied or promoted to an older
3000 * generation. Bytes_allocated and the generation bytes_allocated
3001 * counter are updated. The number of bytes freed is returned. */
3002 static uword_t
3003 free_oldspace(void)
3005 uword_t bytes_freed = 0;
3006 page_index_t first_page, last_page;
3008 first_page = 0;
3010 do {
3011 /* Find a first page for the next region of pages. */
3012 while ((first_page < last_free_page)
3013 && (page_free_p(first_page)
3014 || (page_table[first_page].bytes_used == 0)
3015 || (page_table[first_page].gen != from_space)))
3016 first_page++;
3018 if (first_page >= last_free_page)
3019 break;
3021 /* Find the last page of this region. */
3022 last_page = first_page;
3024 do {
3025 /* Free the page. */
3026 bytes_freed += page_table[last_page].bytes_used;
3027 generations[page_table[last_page].gen].bytes_allocated -=
3028 page_table[last_page].bytes_used;
3029 page_table[last_page].allocated = FREE_PAGE_FLAG;
3030 page_table[last_page].bytes_used = 0;
3031 /* Should already be unprotected by unprotect_oldspace(). */
3032 gc_assert(!page_table[last_page].write_protected);
3033 last_page++;
3035 while ((last_page < last_free_page)
3036 && page_allocated_p(last_page)
3037 && (page_table[last_page].bytes_used != 0)
3038 && (page_table[last_page].gen == from_space));
3040 #ifdef READ_PROTECT_FREE_PAGES
3041 os_protect(page_address(first_page),
3042 npage_bytes(last_page-first_page),
3043 OS_VM_PROT_NONE);
3044 #endif
3045 first_page = last_page;
3046 } while (first_page < last_free_page);
3048 bytes_allocated -= bytes_freed;
3049 return bytes_freed;
3052 #if 0
3053 /* Print some information about a pointer at the given address. */
3054 static void
3055 print_ptr(lispobj *addr)
3057 /* If addr is in the dynamic space then out the page information. */
3058 page_index_t pi1 = find_page_index((void*)addr);
3060 if (pi1 != -1)
3061 fprintf(stderr," %p: page %d alloc %d gen %d bytes_used %d offset %lu dont_move %d\n",
3062 addr,
3063 pi1,
3064 page_table[pi1].allocated,
3065 page_table[pi1].gen,
3066 page_table[pi1].bytes_used,
3067 page_table[pi1].scan_start_offset,
3068 page_table[pi1].dont_move);
3069 fprintf(stderr," %x %x %x %x (%x) %x %x %x %x\n",
3070 *(addr-4),
3071 *(addr-3),
3072 *(addr-2),
3073 *(addr-1),
3074 *(addr-0),
3075 *(addr+1),
3076 *(addr+2),
3077 *(addr+3),
3078 *(addr+4));
3080 #endif
3082 static int
3083 is_in_stack_space(lispobj ptr)
3085 /* For space verification: Pointers can be valid if they point
3086 * to a thread stack space. This would be faster if the thread
3087 * structures had page-table entries as if they were part of
3088 * the heap space. */
3089 struct thread *th;
3090 for_each_thread(th) {
3091 if ((th->control_stack_start <= (lispobj *)ptr) &&
3092 (th->control_stack_end >= (lispobj *)ptr)) {
3093 return 1;
3096 return 0;
3099 // NOTE: This function can produces false failure indications,
3100 // usually related to dynamic space pointing to the stack of a
3101 // dead thread, but there may be other reasons as well.
3102 static void
3103 verify_space(lispobj *start, size_t words)
3105 extern int valid_lisp_pointer_p(lispobj);
3106 int is_in_dynamic_space = (find_page_index((void*)start) != -1);
3107 int is_in_readonly_space =
3108 (READ_ONLY_SPACE_START <= (uword_t)start &&
3109 (uword_t)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3110 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3111 int is_in_immobile_space =
3112 (IMMOBILE_SPACE_START <= (uword_t)start &&
3113 (uword_t)start < SymbolValue(IMMOBILE_SPACE_FREE_POINTER,0));
3114 #endif
3116 while (words > 0) {
3117 size_t count = 1;
3118 lispobj thing = *start;
3120 if (is_lisp_pointer(thing)) {
3121 page_index_t page_index = find_page_index((void*)thing);
3122 sword_t to_readonly_space =
3123 (READ_ONLY_SPACE_START <= thing &&
3124 thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3125 sword_t to_static_space =
3126 (STATIC_SPACE_START <= thing &&
3127 thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3128 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3129 sword_t to_immobile_space =
3130 (IMMOBILE_SPACE_START <= thing &&
3131 thing < SymbolValue(IMMOBILE_FIXEDOBJ_FREE_POINTER,0)) ||
3132 (IMMOBILE_VARYOBJ_SUBSPACE_START <= thing &&
3133 thing < SymbolValue(IMMOBILE_SPACE_FREE_POINTER,0));
3134 #endif
3136 /* Does it point to the dynamic space? */
3137 if (page_index != -1) {
3138 /* If it's within the dynamic space it should point to a used page. */
3139 if (!page_allocated_p(page_index))
3140 lose ("Ptr %p @ %p sees free page.\n", thing, start);
3141 if ((char*)thing - (char*)page_address(page_index)
3142 >= page_table[page_index].bytes_used)
3143 lose ("Ptr %p @ %p sees unallocated space.\n", thing, start);
3144 /* Check that it doesn't point to a forwarding pointer! */
3145 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3146 lose("Ptr %p @ %p sees forwarding ptr.\n", thing, start);
3148 /* Check that its not in the RO space as it would then be a
3149 * pointer from the RO to the dynamic space. */
3150 if (is_in_readonly_space) {
3151 lose("ptr to dynamic space %p from RO space %x\n",
3152 thing, start);
3154 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3155 // verify all immobile space -> dynamic space pointers
3156 if (is_in_immobile_space && !valid_lisp_pointer_p(thing)) {
3157 lose("Ptr %p @ %p sees junk.\n", thing, start);
3159 #endif
3160 /* Does it point to a plausible object? This check slows
3161 * it down a lot (so it's commented out).
3163 * "a lot" is serious: it ate 50 minutes cpu time on
3164 * my duron 950 before I came back from lunch and
3165 * killed it.
3167 * FIXME: Add a variable to enable this
3168 * dynamically. */
3170 if (!possibly_valid_dynamic_space_pointer_s((lispobj *)thing, page_index, NULL)) {
3171 lose("ptr %p to invalid object %p\n", thing, start);
3174 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3175 } else if (to_immobile_space) {
3176 // the object pointed to must not have been discarded as garbage
3177 if (!other_immediate_lowtag_p(*native_pointer(thing))
3178 || immobile_filler_p(native_pointer(thing)))
3179 lose("Ptr %p @ %p sees trashed object.\n", (void*)thing, start);
3180 // verify all pointers to immobile space
3181 if (!valid_lisp_pointer_p(thing))
3182 lose("Ptr %p @ %p sees junk.\n", thing, start);
3183 #endif
3184 } else {
3185 extern char __attribute__((unused)) funcallable_instance_tramp;
3186 /* Verify that it points to another valid space. */
3187 if (!to_readonly_space && !to_static_space
3188 && !is_in_stack_space(thing)) {
3189 lose("Ptr %p @ %p sees junk.\n", thing, start);
3192 } else {
3193 if (!(fixnump(thing))) {
3194 /* skip fixnums */
3195 switch(widetag_of(*start)) {
3197 /* boxed objects */
3198 case SIMPLE_VECTOR_WIDETAG:
3199 case RATIO_WIDETAG:
3200 case COMPLEX_WIDETAG:
3201 case SIMPLE_ARRAY_WIDETAG:
3202 case COMPLEX_BASE_STRING_WIDETAG:
3203 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
3204 case COMPLEX_CHARACTER_STRING_WIDETAG:
3205 #endif
3206 case COMPLEX_VECTOR_NIL_WIDETAG:
3207 case COMPLEX_BIT_VECTOR_WIDETAG:
3208 case COMPLEX_VECTOR_WIDETAG:
3209 case COMPLEX_ARRAY_WIDETAG:
3210 case CLOSURE_HEADER_WIDETAG:
3211 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3212 case VALUE_CELL_HEADER_WIDETAG:
3213 case SYMBOL_HEADER_WIDETAG:
3214 case CHARACTER_WIDETAG:
3215 #if N_WORD_BITS == 64
3216 case SINGLE_FLOAT_WIDETAG:
3217 #endif
3218 case UNBOUND_MARKER_WIDETAG:
3219 case FDEFN_WIDETAG:
3220 count = 1;
3221 break;
3223 case INSTANCE_HEADER_WIDETAG:
3225 sword_t ntotal = instance_length(thing);
3226 lispobj layout = instance_layout(start);
3227 if (!layout) {
3228 count = 1;
3229 break;
3231 instance_scan_interleaved(verify_space,
3232 start, ntotal,
3233 native_pointer(layout));
3234 count = ntotal + 1;
3235 break;
3237 case CODE_HEADER_WIDETAG:
3239 lispobj header = *start;
3240 struct code *code = (struct code *) start;
3241 sword_t nheader_words, ncode_words, nwords;
3242 lispobj fheaderl;
3243 struct simple_fun *fheaderp;
3245 /* Check that it's not in the dynamic space.
3246 * FIXME: Isn't is supposed to be OK for code
3247 * objects to be in the dynamic space these days? */
3248 /* It is for byte compiled code, but there's
3249 * no byte compilation in SBCL anymore. */
3250 if (is_in_dynamic_space
3251 /* Only when enabled */
3252 && verify_dynamic_code_check) {
3253 FSHOW((stderr,
3254 "/code object at %p in the dynamic space\n",
3255 start));
3258 ncode_words = code_instruction_words(code->code_size);
3259 nheader_words = code_header_words(header);
3260 nwords = ncode_words + nheader_words;
3261 nwords = CEILING(nwords, 2);
3262 /* Scavenge the boxed section of the code data block */
3263 verify_space(start + 1, nheader_words - 1);
3265 /* Scavenge the boxed section of each function
3266 * object in the code data block. */
3267 fheaderl = code->entry_points;
3268 while (fheaderl != NIL) {
3269 fheaderp =
3270 (struct simple_fun *) native_pointer(fheaderl);
3271 gc_assert(widetag_of(fheaderp->header) ==
3272 SIMPLE_FUN_HEADER_WIDETAG);
3273 verify_space(SIMPLE_FUN_SCAV_START(fheaderp),
3274 SIMPLE_FUN_SCAV_NWORDS(fheaderp));
3275 fheaderl = fheaderp->next;
3277 count = nwords;
3278 break;
3281 /* unboxed objects */
3282 case BIGNUM_WIDETAG:
3283 #if N_WORD_BITS != 64
3284 case SINGLE_FLOAT_WIDETAG:
3285 #endif
3286 case DOUBLE_FLOAT_WIDETAG:
3287 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3288 case LONG_FLOAT_WIDETAG:
3289 #endif
3290 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3291 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3292 #endif
3293 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3294 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3295 #endif
3296 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3297 case COMPLEX_LONG_FLOAT_WIDETAG:
3298 #endif
3299 #ifdef SIMD_PACK_WIDETAG
3300 case SIMD_PACK_WIDETAG:
3301 #endif
3302 case SIMPLE_BASE_STRING_WIDETAG:
3303 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3304 case SIMPLE_CHARACTER_STRING_WIDETAG:
3305 #endif
3306 case SIMPLE_BIT_VECTOR_WIDETAG:
3307 case SIMPLE_ARRAY_NIL_WIDETAG:
3308 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3309 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3310 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3311 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3312 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3313 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3315 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
3317 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3318 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3319 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3320 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3321 #endif
3322 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3323 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3324 #endif
3325 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3326 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3327 #endif
3328 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3329 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3330 #endif
3332 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
3334 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3335 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3336 #endif
3337 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3338 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3339 #endif
3340 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3341 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3342 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3343 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3344 #endif
3345 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3346 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3347 #endif
3348 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3349 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3350 #endif
3351 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3352 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3353 #endif
3354 case SAP_WIDETAG:
3355 case WEAK_POINTER_WIDETAG:
3356 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3357 case NO_TLS_VALUE_MARKER_WIDETAG:
3358 #endif
3359 count = (sizetab[widetag_of(*start)])(start);
3360 break;
3362 default:
3363 lose("Unhandled widetag %p at %p\n",
3364 widetag_of(*start), start);
3368 start += count;
3369 words -= count;
3373 static void verify_dynamic_space();
3375 static void
3376 verify_gc(void)
3378 /* FIXME: It would be nice to make names consistent so that
3379 * foo_size meant size *in* *bytes* instead of size in some
3380 * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3381 * Some counts of lispobjs are called foo_count; it might be good
3382 * to grep for all foo_size and rename the appropriate ones to
3383 * foo_count. */
3384 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3385 # ifdef __linux__
3386 // Try this verification if marknsweep was compiled with extra debugging.
3387 // But weak symbols don't work on macOS.
3388 extern void __attribute__((weak)) check_varyobj_pages();
3389 if (&check_varyobj_pages) check_varyobj_pages();
3390 # endif
3391 verify_space((lispobj*)IMMOBILE_SPACE_START,
3392 (lispobj*)SymbolValue(IMMOBILE_FIXEDOBJ_FREE_POINTER,0)
3393 - (lispobj*)IMMOBILE_SPACE_START);
3394 verify_space((lispobj*)IMMOBILE_VARYOBJ_SUBSPACE_START,
3395 (lispobj*)SymbolValue(IMMOBILE_SPACE_FREE_POINTER,0)
3396 - (lispobj*)IMMOBILE_VARYOBJ_SUBSPACE_START);
3397 #endif
3398 sword_t read_only_space_size =
3399 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3400 - (lispobj*)READ_ONLY_SPACE_START;
3401 sword_t static_space_size =
3402 (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3403 - (lispobj*)STATIC_SPACE_START;
3404 struct thread *th;
3405 for_each_thread(th) {
3406 sword_t binding_stack_size =
3407 (lispobj*)get_binding_stack_pointer(th)
3408 - (lispobj*)th->binding_stack_start;
3409 verify_space(th->binding_stack_start, binding_stack_size);
3411 verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3412 verify_space((lispobj*)STATIC_SPACE_START , static_space_size);
3413 verify_dynamic_space();
3416 static void
3417 verify_generation(generation_index_t generation)
3419 page_index_t i;
3420 int genmask = generation >= 0 ? 1 << generation : ~0;
3422 for (i = 0; i < last_free_page; i++) {
3423 if (page_allocated_p(i)
3424 && (page_table[i].bytes_used != 0)
3425 && ((1 << page_table[i].gen) & genmask)) {
3426 page_index_t last_page;
3428 /* This should be the start of a contiguous block */
3429 gc_assert(page_starts_contiguous_block_p(i));
3431 /* Need to find the full extent of this contiguous block in case
3432 objects span pages. */
3434 /* Now work forward until the end of this contiguous area is
3435 found. */
3436 for (last_page = i; ;last_page++)
3437 /* Check whether this is the last page in this contiguous
3438 * block. */
3439 if (page_ends_contiguous_block_p(last_page, page_table[i].gen))
3440 break;
3442 verify_space(page_address(i),
3443 ((uword_t)
3444 (page_table[last_page].bytes_used
3445 + npage_bytes(last_page-i)))
3446 / N_WORD_BYTES);
3447 i = last_page;
3452 /* Check that all the free space is zero filled. */
3453 static void
3454 verify_zero_fill(void)
3456 page_index_t page;
3458 for (page = 0; page < last_free_page; page++) {
3459 if (page_free_p(page)) {
3460 /* The whole page should be zero filled. */
3461 sword_t *start_addr = (sword_t *)page_address(page);
3462 sword_t size = 1024;
3463 sword_t i;
3464 for (i = 0; i < size; i++) {
3465 if (start_addr[i] != 0) {
3466 lose("free page not zero at %x\n", start_addr + i);
3469 } else {
3470 sword_t free_bytes = GENCGC_CARD_BYTES - page_table[page].bytes_used;
3471 if (free_bytes > 0) {
3472 sword_t *start_addr = (sword_t *)((uword_t)page_address(page)
3473 + page_table[page].bytes_used);
3474 sword_t size = free_bytes / N_WORD_BYTES;
3475 sword_t i;
3476 for (i = 0; i < size; i++) {
3477 if (start_addr[i] != 0) {
3478 lose("free region not zero at %x\n", start_addr + i);
3486 /* External entry point for verify_zero_fill */
3487 void
3488 gencgc_verify_zero_fill(void)
3490 /* Flush the alloc regions updating the tables. */
3491 gc_alloc_update_all_page_tables(1);
3492 SHOW("verifying zero fill");
3493 verify_zero_fill();
3496 static void
3497 verify_dynamic_space(void)
3499 verify_generation(-1);
3500 if (gencgc_enable_verify_zero_fill)
3501 verify_zero_fill();
3504 /* Write-protect all the dynamic boxed pages in the given generation. */
3505 static void
3506 write_protect_generation_pages(generation_index_t generation)
3508 page_index_t start;
3510 gc_assert(generation < SCRATCH_GENERATION);
3512 for (start = 0; start < last_free_page; start++) {
3513 if (protect_page_p(start, generation)) {
3514 void *page_start;
3515 page_index_t last;
3517 /* Note the page as protected in the page tables. */
3518 page_table[start].write_protected = 1;
3520 for (last = start + 1; last < last_free_page; last++) {
3521 if (!protect_page_p(last, generation))
3522 break;
3523 page_table[last].write_protected = 1;
3526 page_start = (void *)page_address(start);
3528 os_protect(page_start,
3529 npage_bytes(last - start),
3530 OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3532 start = last;
3536 if (gencgc_verbose > 1) {
3537 FSHOW((stderr,
3538 "/write protected %d of %d pages in generation %d\n",
3539 count_write_protect_generation_pages(generation),
3540 count_generation_pages(generation),
3541 generation));
3545 #if defined(LISP_FEATURE_SB_THREAD) && (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
3546 static void
3547 preserve_context_registers (os_context_t *c)
3549 void **ptr;
3550 /* On Darwin the signal context isn't a contiguous block of memory,
3551 * so just preserve_pointering its contents won't be sufficient.
3553 #if defined(LISP_FEATURE_DARWIN)||defined(LISP_FEATURE_WIN32)
3554 #if defined LISP_FEATURE_X86
3555 preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3556 preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3557 preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3558 preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3559 preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3560 preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3561 preserve_pointer((void*)*os_context_pc_addr(c));
3562 #elif defined LISP_FEATURE_X86_64
3563 preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3564 preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3565 preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3566 preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3567 preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3568 preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3569 preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3570 preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3571 preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3572 preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3573 preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3574 preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3575 preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3576 preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3577 preserve_pointer((void*)*os_context_pc_addr(c));
3578 #else
3579 #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3580 #endif
3581 #endif
3582 #if !defined(LISP_FEATURE_WIN32)
3583 for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3584 preserve_pointer(*ptr);
3586 #endif
3588 #endif
3590 static void
3591 move_pinned_pages_to_newspace()
3593 page_index_t i;
3595 /* scavenge() will evacuate all oldspace pages, but no newspace
3596 * pages. Pinned pages are precisely those pages which must not
3597 * be evacuated, so move them to newspace directly. */
3599 for (i = 0; i < last_free_page; i++) {
3600 if (page_table[i].dont_move &&
3601 /* dont_move is cleared lazily, so validate the space as well. */
3602 page_table[i].gen == from_space) {
3603 if (pinned_dwords(i) && do_wipe_p) {
3604 // do not move to newspace after all, this will be word-wiped
3605 continue;
3607 page_table[i].gen = new_space;
3608 /* And since we're moving the pages wholesale, also adjust
3609 * the generation allocation counters. */
3610 generations[new_space].bytes_allocated += page_table[i].bytes_used;
3611 generations[from_space].bytes_allocated -= page_table[i].bytes_used;
3616 /* Garbage collect a generation. If raise is 0 then the remains of the
3617 * generation are not raised to the next generation. */
3618 static void
3619 garbage_collect_generation(generation_index_t generation, int raise)
3621 page_index_t i;
3622 uword_t static_space_size;
3623 struct thread *th;
3625 gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3627 /* The oldest generation can't be raised. */
3628 gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
3630 /* Check if weak hash tables were processed in the previous GC. */
3631 gc_assert(weak_hash_tables == NULL);
3633 /* Initialize the weak pointer list. */
3634 weak_pointers = NULL;
3636 /* When a generation is not being raised it is transported to a
3637 * temporary generation (NUM_GENERATIONS), and lowered when
3638 * done. Set up this new generation. There should be no pages
3639 * allocated to it yet. */
3640 if (!raise) {
3641 gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
3644 /* Set the global src and dest. generations */
3645 from_space = generation;
3646 if (raise)
3647 new_space = generation+1;
3648 else
3649 new_space = SCRATCH_GENERATION;
3651 /* Change to a new space for allocation, resetting the alloc_start_page */
3652 gc_alloc_generation = new_space;
3653 generations[new_space].alloc_start_page = 0;
3654 generations[new_space].alloc_unboxed_start_page = 0;
3655 generations[new_space].alloc_large_start_page = 0;
3656 generations[new_space].alloc_large_unboxed_start_page = 0;
3658 /* Before any pointers are preserved, the dont_move flags on the
3659 * pages need to be cleared. */
3660 for (i = 0; i < last_free_page; i++)
3661 if(page_table[i].gen==from_space) {
3662 page_table[i].dont_move = 0;
3663 gc_assert(pinned_dwords(i) == NULL);
3666 /* Un-write-protect the old-space pages. This is essential for the
3667 * promoted pages as they may contain pointers into the old-space
3668 * which need to be scavenged. It also helps avoid unnecessary page
3669 * faults as forwarding pointers are written into them. They need to
3670 * be un-protected anyway before unmapping later. */
3671 unprotect_oldspace();
3673 /* Scavenge the stacks' conservative roots. */
3675 /* there are potentially two stacks for each thread: the main
3676 * stack, which may contain Lisp pointers, and the alternate stack.
3677 * We don't ever run Lisp code on the altstack, but it may
3678 * host a sigcontext with lisp objects in it */
3680 /* what we need to do: (1) find the stack pointer for the main
3681 * stack; scavenge it (2) find the interrupt context on the
3682 * alternate stack that might contain lisp values, and scavenge
3683 * that */
3685 /* we assume that none of the preceding applies to the thread that
3686 * initiates GC. If you ever call GC from inside an altstack
3687 * handler, you will lose. */
3689 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3690 /* And if we're saving a core, there's no point in being conservative. */
3691 if (conservative_stack) {
3692 for_each_thread(th) {
3693 void **ptr;
3694 void **esp=(void **)-1;
3695 if (th->state == STATE_DEAD)
3696 continue;
3697 # if defined(LISP_FEATURE_SB_SAFEPOINT)
3698 /* Conservative collect_garbage is always invoked with a
3699 * foreign C call or an interrupt handler on top of every
3700 * existing thread, so the stored SP in each thread
3701 * structure is valid, no matter which thread we are looking
3702 * at. For threads that were running Lisp code, the pitstop
3703 * and edge functions maintain this value within the
3704 * interrupt or exception handler. */
3705 esp = os_get_csp(th);
3706 assert_on_stack(th, esp);
3708 /* In addition to pointers on the stack, also preserve the
3709 * return PC, the only value from the context that we need
3710 * in addition to the SP. The return PC gets saved by the
3711 * foreign call wrapper, and removed from the control stack
3712 * into a register. */
3713 preserve_pointer(th->pc_around_foreign_call);
3715 /* And on platforms with interrupts: scavenge ctx registers. */
3717 /* Disabled on Windows, because it does not have an explicit
3718 * stack of `interrupt_contexts'. The reported CSP has been
3719 * chosen so that the current context on the stack is
3720 * covered by the stack scan. See also set_csp_from_context(). */
3721 # ifndef LISP_FEATURE_WIN32
3722 if (th != arch_os_get_current_thread()) {
3723 long k = fixnum_value(
3724 SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3725 while (k > 0)
3726 preserve_context_registers(th->interrupt_contexts[--k]);
3728 # endif
3729 # elif defined(LISP_FEATURE_SB_THREAD)
3730 sword_t i,free;
3731 if(th==arch_os_get_current_thread()) {
3732 /* Somebody is going to burn in hell for this, but casting
3733 * it in two steps shuts gcc up about strict aliasing. */
3734 esp = (void **)((void *)&raise);
3735 } else {
3736 void **esp1;
3737 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3738 for(i=free-1;i>=0;i--) {
3739 os_context_t *c=th->interrupt_contexts[i];
3740 esp1 = (void **) *os_context_register_addr(c,reg_SP);
3741 if (esp1>=(void **)th->control_stack_start &&
3742 esp1<(void **)th->control_stack_end) {
3743 if(esp1<esp) esp=esp1;
3744 preserve_context_registers(c);
3748 # else
3749 esp = (void **)((void *)&raise);
3750 # endif
3751 if (!esp || esp == (void*) -1)
3752 lose("garbage_collect: no SP known for thread %x (OS %x)",
3753 th, th->os_thread);
3754 for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp; ptr--) {
3755 preserve_pointer(*ptr);
3759 #else
3760 /* Non-x86oid systems don't have "conservative roots" as such, but
3761 * the same mechanism is used for objects pinned for use by alien
3762 * code. */
3763 for_each_thread(th) {
3764 lispobj pin_list = SymbolTlValue(PINNED_OBJECTS,th);
3765 while (pin_list != NIL) {
3766 struct cons *list_entry =
3767 (struct cons *)native_pointer(pin_list);
3768 preserve_pointer(list_entry->car);
3769 pin_list = list_entry->cdr;
3772 #endif
3774 #if QSHOW
3775 if (gencgc_verbose > 1) {
3776 sword_t num_dont_move_pages = count_dont_move_pages();
3777 fprintf(stderr,
3778 "/non-movable pages due to conservative pointers = %ld (%lu bytes)\n",
3779 num_dont_move_pages,
3780 npage_bytes(num_dont_move_pages));
3782 #endif
3784 /* Now that all of the pinned (dont_move) pages are known, and
3785 * before we start to scavenge (and thus relocate) objects,
3786 * relocate the pinned pages to newspace, so that the scavenger
3787 * will not attempt to relocate their contents. */
3788 move_pinned_pages_to_newspace();
3790 /* Scavenge all the rest of the roots. */
3792 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3794 * If not x86, we need to scavenge the interrupt context(s) and the
3795 * control stack.
3798 struct thread *th;
3799 for_each_thread(th) {
3800 scavenge_interrupt_contexts(th);
3801 scavenge_control_stack(th);
3804 # ifdef LISP_FEATURE_SB_SAFEPOINT
3805 /* In this case, scrub all stacks right here from the GCing thread
3806 * instead of doing what the comment below says. Suboptimal, but
3807 * easier. */
3808 for_each_thread(th)
3809 scrub_thread_control_stack(th);
3810 # else
3811 /* Scrub the unscavenged control stack space, so that we can't run
3812 * into any stale pointers in a later GC (this is done by the
3813 * stop-for-gc handler in the other threads). */
3814 scrub_control_stack();
3815 # endif
3817 #endif
3819 /* Scavenge the Lisp functions of the interrupt handlers, taking
3820 * care to avoid SIG_DFL and SIG_IGN. */
3821 for (i = 0; i < NSIG; i++) {
3822 union interrupt_handler handler = interrupt_handlers[i];
3823 if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3824 !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3825 scavenge((lispobj *)(interrupt_handlers + i), 1);
3828 /* Scavenge the binding stacks. */
3830 struct thread *th;
3831 for_each_thread(th) {
3832 sword_t len= (lispobj *)get_binding_stack_pointer(th) -
3833 th->binding_stack_start;
3834 scavenge((lispobj *) th->binding_stack_start,len);
3835 #ifdef LISP_FEATURE_SB_THREAD
3836 /* do the tls as well */
3837 len=(SymbolValue(FREE_TLS_INDEX,0) >> WORD_SHIFT) -
3838 (sizeof (struct thread))/(sizeof (lispobj));
3839 scavenge((lispobj *) (th+1),len);
3840 #endif
3844 /* The original CMU CL code had scavenge-read-only-space code
3845 * controlled by the Lisp-level variable
3846 * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3847 * wasn't documented under what circumstances it was useful or
3848 * safe to turn it on, so it's been turned off in SBCL. If you
3849 * want/need this functionality, and can test and document it,
3850 * please submit a patch. */
3851 #if 0
3852 if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3853 uword_t read_only_space_size =
3854 (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3855 (lispobj*)READ_ONLY_SPACE_START;
3856 FSHOW((stderr,
3857 "/scavenge read only space: %d bytes\n",
3858 read_only_space_size * sizeof(lispobj)));
3859 scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3861 #endif
3863 /* Scavenge static space. */
3864 static_space_size =
3865 (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3866 (lispobj *)STATIC_SPACE_START;
3867 if (gencgc_verbose > 1) {
3868 FSHOW((stderr,
3869 "/scavenge static space: %d bytes\n",
3870 static_space_size * sizeof(lispobj)));
3872 scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3874 /* All generations but the generation being GCed need to be
3875 * scavenged. The new_space generation needs special handling as
3876 * objects may be moved in - it is handled separately below. */
3877 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3878 scavenge_immobile_roots(generation+1, SCRATCH_GENERATION);
3879 #endif
3880 scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
3882 scavenge_pinned_ranges();
3884 /* Finally scavenge the new_space generation. Keep going until no
3885 * more objects are moved into the new generation */
3886 scavenge_newspace_generation(new_space);
3888 /* FIXME: I tried reenabling this check when debugging unrelated
3889 * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3890 * Since the current GC code seems to work well, I'm guessing that
3891 * this debugging code is just stale, but I haven't tried to
3892 * figure it out. It should be figured out and then either made to
3893 * work or just deleted. */
3895 #define RESCAN_CHECK 0
3896 #if RESCAN_CHECK
3897 /* As a check re-scavenge the newspace once; no new objects should
3898 * be found. */
3900 os_vm_size_t old_bytes_allocated = bytes_allocated;
3901 os_vm_size_t bytes_allocated;
3903 /* Start with a full scavenge. */
3904 scavenge_newspace_generation_one_scan(new_space);
3906 /* Flush the current regions, updating the tables. */
3907 gc_alloc_update_all_page_tables(1);
3909 bytes_allocated = bytes_allocated - old_bytes_allocated;
3911 if (bytes_allocated != 0) {
3912 lose("Rescan of new_space allocated %d more bytes.\n",
3913 bytes_allocated);
3916 #endif
3918 scan_weak_hash_tables();
3919 scan_weak_pointers();
3920 wipe_nonpinned_words();
3921 #ifdef LISP_FEATURE_IMMOBILE_SPACE
3922 // Do this last, because until wipe_nonpinned_words() happens,
3923 // not all page table entries have the 'gen' value updated,
3924 // which we need to correctly find all old->young pointers.
3925 sweep_immobile_space(raise);
3926 #endif
3928 /* Flush the current regions, updating the tables. */
3929 gc_alloc_update_all_page_tables(0);
3931 /* Free the pages in oldspace, but not those marked dont_move. */
3932 free_oldspace();
3934 /* If the GC is not raising the age then lower the generation back
3935 * to its normal generation number */
3936 if (!raise) {
3937 for (i = 0; i < last_free_page; i++)
3938 if ((page_table[i].bytes_used != 0)
3939 && (page_table[i].gen == SCRATCH_GENERATION))
3940 page_table[i].gen = generation;
3941 gc_assert(generations[generation].bytes_allocated == 0);
3942 generations[generation].bytes_allocated =
3943 generations[SCRATCH_GENERATION].bytes_allocated;
3944 generations[SCRATCH_GENERATION].bytes_allocated = 0;
3947 /* Reset the alloc_start_page for generation. */
3948 generations[generation].alloc_start_page = 0;
3949 generations[generation].alloc_unboxed_start_page = 0;
3950 generations[generation].alloc_large_start_page = 0;
3951 generations[generation].alloc_large_unboxed_start_page = 0;
3953 if (generation >= verify_gens) {
3954 if (gencgc_verbose) {
3955 SHOW("verifying");
3957 verify_gc();
3960 /* Set the new gc trigger for the GCed generation. */
3961 generations[generation].gc_trigger =
3962 generations[generation].bytes_allocated
3963 + generations[generation].bytes_consed_between_gc;
3965 if (raise)
3966 generations[generation].num_gc = 0;
3967 else
3968 ++generations[generation].num_gc;
3972 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3973 sword_t
3974 update_dynamic_space_free_pointer(void)
3976 page_index_t last_page = -1, i;
3978 for (i = 0; i < last_free_page; i++)
3979 if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
3980 last_page = i;
3982 last_free_page = last_page+1;
3984 set_alloc_pointer((lispobj)(page_address(last_free_page)));
3985 return 0; /* dummy value: return something ... */
3988 static void
3989 remap_page_range (page_index_t from, page_index_t to)
3991 /* There's a mysterious Solaris/x86 problem with using mmap
3992 * tricks for memory zeroing. See sbcl-devel thread
3993 * "Re: patch: standalone executable redux".
3995 #if defined(LISP_FEATURE_SUNOS)
3996 zero_and_mark_pages(from, to);
3997 #else
3998 const page_index_t
3999 release_granularity = gencgc_release_granularity/GENCGC_CARD_BYTES,
4000 release_mask = release_granularity-1,
4001 end = to+1,
4002 aligned_from = (from+release_mask)&~release_mask,
4003 aligned_end = (end&~release_mask);
4005 if (aligned_from < aligned_end) {
4006 zero_pages_with_mmap(aligned_from, aligned_end-1);
4007 if (aligned_from != from)
4008 zero_and_mark_pages(from, aligned_from-1);
4009 if (aligned_end != end)
4010 zero_and_mark_pages(aligned_end, end-1);
4011 } else {
4012 zero_and_mark_pages(from, to);
4014 #endif
4017 static void
4018 remap_free_pages (page_index_t from, page_index_t to, int forcibly)
4020 page_index_t first_page, last_page;
4022 if (forcibly)
4023 return remap_page_range(from, to);
4025 for (first_page = from; first_page <= to; first_page++) {
4026 if (page_allocated_p(first_page) ||
4027 (page_table[first_page].need_to_zero == 0))
4028 continue;
4030 last_page = first_page + 1;
4031 while (page_free_p(last_page) &&
4032 (last_page <= to) &&
4033 (page_table[last_page].need_to_zero == 1))
4034 last_page++;
4036 remap_page_range(first_page, last_page-1);
4038 first_page = last_page;
4042 generation_index_t small_generation_limit = 1;
4044 /* GC all generations newer than last_gen, raising the objects in each
4045 * to the next older generation - we finish when all generations below
4046 * last_gen are empty. Then if last_gen is due for a GC, or if
4047 * last_gen==NUM_GENERATIONS (the scratch generation? eh?) we GC that
4048 * too. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
4050 * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
4051 * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
4052 void
4053 collect_garbage(generation_index_t last_gen)
4055 generation_index_t gen = 0, i;
4056 int raise, more = 0;
4057 int gen_to_wp;
4058 /* The largest value of last_free_page seen since the time
4059 * remap_free_pages was called. */
4060 static page_index_t high_water_mark = 0;
4062 FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
4063 log_generation_stats(gc_logfile, "=== GC Start ===");
4065 gc_active_p = 1;
4067 if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
4068 FSHOW((stderr,
4069 "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
4070 last_gen));
4071 last_gen = 0;
4074 /* Flush the alloc regions updating the tables. */
4075 gc_alloc_update_all_page_tables(1);
4077 /* Verify the new objects created by Lisp code. */
4078 if (pre_verify_gen_0) {
4079 FSHOW((stderr, "pre-checking generation 0\n"));
4080 verify_generation(0);
4083 if (gencgc_verbose > 1)
4084 print_generation_stats();
4086 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4087 /* Immobile space generation bits are lazily updated for gen0
4088 (not touched on every object allocation) so do it now */
4089 update_immobile_nursery_bits();
4090 #endif
4092 do {
4093 /* Collect the generation. */
4095 if (more || (gen >= gencgc_oldest_gen_to_gc)) {
4096 /* Never raise the oldest generation. Never raise the extra generation
4097 * collected due to more-flag. */
4098 raise = 0;
4099 more = 0;
4100 } else {
4101 raise =
4102 (gen < last_gen)
4103 || (generations[gen].num_gc >= generations[gen].number_of_gcs_before_promotion);
4104 /* If we would not normally raise this one, but we're
4105 * running low on space in comparison to the object-sizes
4106 * we've been seeing, raise it and collect the next one
4107 * too. */
4108 if (!raise && gen == last_gen) {
4109 more = (2*large_allocation) >= (dynamic_space_size - bytes_allocated);
4110 raise = more;
4114 if (gencgc_verbose > 1) {
4115 FSHOW((stderr,
4116 "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
4117 gen,
4118 raise,
4119 generations[gen].bytes_allocated,
4120 generations[gen].gc_trigger,
4121 generations[gen].num_gc));
4124 /* If an older generation is being filled, then update its
4125 * memory age. */
4126 if (raise == 1) {
4127 generations[gen+1].cum_sum_bytes_allocated +=
4128 generations[gen+1].bytes_allocated;
4131 garbage_collect_generation(gen, raise);
4133 /* Reset the memory age cum_sum. */
4134 generations[gen].cum_sum_bytes_allocated = 0;
4136 if (gencgc_verbose > 1) {
4137 FSHOW((stderr, "GC of generation %d finished:\n", gen));
4138 print_generation_stats();
4141 gen++;
4142 } while ((gen <= gencgc_oldest_gen_to_gc)
4143 && ((gen < last_gen)
4144 || more
4145 || (raise
4146 && (generations[gen].bytes_allocated
4147 > generations[gen].gc_trigger)
4148 && (generation_average_age(gen)
4149 > generations[gen].minimum_age_before_gc))));
4151 /* Now if gen-1 was raised all generations before gen are empty.
4152 * If it wasn't raised then all generations before gen-1 are empty.
4154 * Now objects within this gen's pages cannot point to younger
4155 * generations unless they are written to. This can be exploited
4156 * by write-protecting the pages of gen; then when younger
4157 * generations are GCed only the pages which have been written
4158 * need scanning. */
4159 if (raise)
4160 gen_to_wp = gen;
4161 else
4162 gen_to_wp = gen - 1;
4164 /* There's not much point in WPing pages in generation 0 as it is
4165 * never scavenged (except promoted pages). */
4166 if ((gen_to_wp > 0) && enable_page_protection) {
4167 /* Check that they are all empty. */
4168 for (i = 0; i < gen_to_wp; i++) {
4169 if (generations[i].bytes_allocated)
4170 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
4171 gen_to_wp, i);
4173 write_protect_generation_pages(gen_to_wp);
4175 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4176 write_protect_immobile_space();
4177 #endif
4179 /* Set gc_alloc() back to generation 0. The current regions should
4180 * be flushed after the above GCs. */
4181 gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
4182 gc_alloc_generation = 0;
4184 /* Save the high-water mark before updating last_free_page */
4185 if (last_free_page > high_water_mark)
4186 high_water_mark = last_free_page;
4188 update_dynamic_space_free_pointer();
4190 /* Update auto_gc_trigger. Make sure we trigger the next GC before
4191 * running out of heap! */
4192 if (bytes_consed_between_gcs <= (dynamic_space_size - bytes_allocated))
4193 auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
4194 else
4195 auto_gc_trigger = bytes_allocated + (dynamic_space_size - bytes_allocated)/2;
4197 if(gencgc_verbose)
4198 fprintf(stderr,"Next gc when %"OS_VM_SIZE_FMT" bytes have been consed\n",
4199 auto_gc_trigger);
4201 /* If we did a big GC (arbitrarily defined as gen > 1), release memory
4202 * back to the OS.
4204 if (gen > small_generation_limit) {
4205 if (last_free_page > high_water_mark)
4206 high_water_mark = last_free_page;
4207 remap_free_pages(0, high_water_mark, 0);
4208 high_water_mark = 0;
4211 gc_active_p = 0;
4212 large_allocation = 0;
4214 log_generation_stats(gc_logfile, "=== GC End ===");
4215 SHOW("returning from collect_garbage");
4218 /* This is called by Lisp PURIFY when it is finished. All live objects
4219 * will have been moved to the RO and Static heaps. The dynamic space
4220 * will need a full re-initialization. We don't bother having Lisp
4221 * PURIFY flush the current gc_alloc() region, as the page_tables are
4222 * re-initialized, and every page is zeroed to be sure. */
4223 void
4224 gc_free_heap(void) // FIXME: remove, not used
4226 page_index_t page, last_page;
4228 if (gencgc_verbose > 1) {
4229 SHOW("entering gc_free_heap");
4232 for (page = 0; page < page_table_pages; page++) {
4233 /* Skip free pages which should already be zero filled. */
4234 if (page_allocated_p(page)) {
4235 void *page_start;
4236 for (last_page = page;
4237 (last_page < page_table_pages) && page_allocated_p(last_page);
4238 last_page++) {
4239 /* Mark the page free. The other slots are assumed invalid
4240 * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
4241 * should not be write-protected -- except that the
4242 * generation is used for the current region but it sets
4243 * that up. */
4244 page_table[page].allocated = FREE_PAGE_FLAG;
4245 page_table[page].bytes_used = 0;
4246 page_table[page].write_protected = 0;
4249 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
4250 * about this change. */
4251 page_start = (void *)page_address(page);
4252 os_protect(page_start, npage_bytes(last_page-page), OS_VM_PROT_ALL);
4253 remap_free_pages(page, last_page-1, 1);
4254 page = last_page-1;
4255 #endif
4256 } else if (gencgc_zero_check_during_free_heap) {
4257 /* Double-check that the page is zero filled. */
4258 sword_t *page_start;
4259 page_index_t i;
4260 gc_assert(page_free_p(page));
4261 gc_assert(page_table[page].bytes_used == 0);
4262 page_start = (sword_t *)page_address(page);
4263 for (i=0; i<(long)(GENCGC_CARD_BYTES/sizeof(sword_t)); i++) {
4264 if (page_start[i] != 0) {
4265 lose("free region not zero at %x\n", page_start + i);
4271 bytes_allocated = 0;
4273 /* Initialize the generations. */
4274 for (page = 0; page < NUM_GENERATIONS; page++) {
4275 generations[page].alloc_start_page = 0;
4276 generations[page].alloc_unboxed_start_page = 0;
4277 generations[page].alloc_large_start_page = 0;
4278 generations[page].alloc_large_unboxed_start_page = 0;
4279 generations[page].bytes_allocated = 0;
4280 generations[page].gc_trigger = 2000000;
4281 generations[page].num_gc = 0;
4282 generations[page].cum_sum_bytes_allocated = 0;
4285 if (gencgc_verbose > 1)
4286 print_generation_stats();
4288 /* Initialize gc_alloc(). */
4289 gc_alloc_generation = 0;
4291 gc_set_region_empty(&boxed_region);
4292 gc_set_region_empty(&unboxed_region);
4294 last_free_page = 0;
4295 set_alloc_pointer((lispobj)((char *)heap_base));
4297 if (verify_after_free_heap) {
4298 /* Check whether purify has left any bad pointers. */
4299 FSHOW((stderr, "checking after free_heap\n"));
4300 verify_gc();
4304 void
4305 gc_init(void)
4307 page_index_t i;
4309 #if defined(LISP_FEATURE_SB_SAFEPOINT)
4310 alloc_gc_page();
4311 #endif
4313 /* Compute the number of pages needed for the dynamic space.
4314 * Dynamic space size should be aligned on page size. */
4315 page_table_pages = dynamic_space_size/GENCGC_CARD_BYTES;
4316 gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4318 /* Default nursery size to 5% of the total dynamic space size,
4319 * min 1Mb. */
4320 bytes_consed_between_gcs = dynamic_space_size/(os_vm_size_t)20;
4321 if (bytes_consed_between_gcs < (1024*1024))
4322 bytes_consed_between_gcs = 1024*1024;
4324 /* The page_table must be allocated using "calloc" to initialize
4325 * the page structures correctly. There used to be a separate
4326 * initialization loop (now commented out; see below) but that was
4327 * unnecessary and did hurt startup time. */
4328 page_table = calloc(page_table_pages, sizeof(struct page));
4329 gc_assert(page_table);
4330 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4331 gc_init_immobile();
4332 #endif
4334 size_t pins_map_size_in_bytes =
4335 (n_dwords_in_card / N_WORD_BITS) * sizeof (uword_t) * page_table_pages;
4336 /* We use mmap directly here so that we can use a minimum of
4337 system calls per page during GC.
4338 All we need here now is a madvise(DONTNEED) at the end of GC. */
4339 page_table_pinned_dwords
4340 = (in_use_marker_t*)os_validate(NULL, pins_map_size_in_bytes);
4341 /* We do not need to zero */
4342 gc_assert(page_table_pinned_dwords);
4344 gc_init_tables();
4345 scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4346 transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4348 heap_base = (void*)DYNAMIC_SPACE_START;
4350 /* The page structures are initialized implicitly when page_table
4351 * is allocated with "calloc" above. Formerly we had the following
4352 * explicit initialization here (comments converted to C99 style
4353 * for readability as C's block comments don't nest):
4355 * // Initialize each page structure.
4356 * for (i = 0; i < page_table_pages; i++) {
4357 * // Initialize all pages as free.
4358 * page_table[i].allocated = FREE_PAGE_FLAG;
4359 * page_table[i].bytes_used = 0;
4361 * // Pages are not write-protected at startup.
4362 * page_table[i].write_protected = 0;
4365 * Without this loop the image starts up much faster when dynamic
4366 * space is large -- which it is on 64-bit platforms already by
4367 * default -- and when "calloc" for large arrays is implemented
4368 * using copy-on-write of a page of zeroes -- which it is at least
4369 * on Linux. In this case the pages that page_table_pages is stored
4370 * in are mapped and cleared not before the corresponding part of
4371 * dynamic space is used. For example, this saves clearing 16 MB of
4372 * memory at startup if the page size is 4 KB and the size of
4373 * dynamic space is 4 GB.
4374 * FREE_PAGE_FLAG must be 0 for this to work correctly which is
4375 * asserted below: */
4377 /* Compile time assertion: If triggered, declares an array
4378 * of dimension -1 forcing a syntax error. The intent of the
4379 * assignment is to avoid an "unused variable" warning. */
4380 char assert_free_page_flag_0[(FREE_PAGE_FLAG) ? -1 : 1];
4381 assert_free_page_flag_0[0] = assert_free_page_flag_0[0];
4384 bytes_allocated = 0;
4386 /* Initialize the generations.
4388 * FIXME: very similar to code in gc_free_heap(), should be shared */
4389 for (i = 0; i < NUM_GENERATIONS; i++) {
4390 generations[i].alloc_start_page = 0;
4391 generations[i].alloc_unboxed_start_page = 0;
4392 generations[i].alloc_large_start_page = 0;
4393 generations[i].alloc_large_unboxed_start_page = 0;
4394 generations[i].bytes_allocated = 0;
4395 generations[i].gc_trigger = 2000000;
4396 generations[i].num_gc = 0;
4397 generations[i].cum_sum_bytes_allocated = 0;
4398 /* the tune-able parameters */
4399 generations[i].bytes_consed_between_gc
4400 = bytes_consed_between_gcs/(os_vm_size_t)HIGHEST_NORMAL_GENERATION;
4401 generations[i].number_of_gcs_before_promotion = 1;
4402 generations[i].minimum_age_before_gc = 0.75;
4405 /* Initialize gc_alloc. */
4406 gc_alloc_generation = 0;
4407 gc_set_region_empty(&boxed_region);
4408 gc_set_region_empty(&unboxed_region);
4410 last_free_page = 0;
4413 /* Pick up the dynamic space from after a core load.
4415 * The ALLOCATION_POINTER points to the end of the dynamic space.
4418 static void
4419 gencgc_pickup_dynamic(void)
4421 page_index_t page = 0;
4422 void *alloc_ptr = (void *)get_alloc_pointer();
4423 lispobj *prev=(lispobj *)page_address(page);
4424 generation_index_t gen = PSEUDO_STATIC_GENERATION;
4426 bytes_allocated = 0;
4428 do {
4429 lispobj *first,*ptr= (lispobj *)page_address(page);
4431 if (!gencgc_partial_pickup || page_allocated_p(page)) {
4432 /* It is possible, though rare, for the saved page table
4433 * to contain free pages below alloc_ptr. */
4434 page_table[page].gen = gen;
4435 page_table[page].bytes_used = GENCGC_CARD_BYTES;
4436 page_table[page].large_object = 0;
4437 page_table[page].write_protected = 0;
4438 page_table[page].write_protected_cleared = 0;
4439 page_table[page].dont_move = 0;
4440 page_table[page].need_to_zero = 1;
4442 bytes_allocated += GENCGC_CARD_BYTES;
4445 if (!gencgc_partial_pickup) {
4446 page_table[page].allocated = BOXED_PAGE_FLAG;
4447 first=gc_search_space(prev,(ptr+2)-prev,ptr);
4448 if(ptr == first)
4449 prev=ptr;
4450 page_table[page].scan_start_offset =
4451 page_address(page) - (void *)prev;
4453 page++;
4454 } while (page_address(page) < alloc_ptr);
4456 last_free_page = page;
4458 generations[gen].bytes_allocated = bytes_allocated;
4460 gc_alloc_update_all_page_tables(1);
4461 write_protect_generation_pages(gen);
4464 void
4465 gc_initialize_pointers(void)
4467 gencgc_pickup_dynamic();
4471 /* alloc(..) is the external interface for memory allocation. It
4472 * allocates to generation 0. It is not called from within the garbage
4473 * collector as it is only external uses that need the check for heap
4474 * size (GC trigger) and to disable the interrupts (interrupts are
4475 * always disabled during a GC).
4477 * The vops that call alloc(..) assume that the returned space is zero-filled.
4478 * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4480 * The check for a GC trigger is only performed when the current
4481 * region is full, so in most cases it's not needed. */
4483 static inline lispobj *
4484 general_alloc_internal(sword_t nbytes, int page_type_flag, struct alloc_region *region,
4485 struct thread *thread)
4487 #ifndef LISP_FEATURE_WIN32
4488 lispobj alloc_signal;
4489 #endif
4490 void *new_obj;
4491 void *new_free_pointer;
4492 os_vm_size_t trigger_bytes = 0;
4494 gc_assert(nbytes > 0);
4496 /* Check for alignment allocation problems. */
4497 gc_assert((((uword_t)region->free_pointer & LOWTAG_MASK) == 0)
4498 && ((nbytes & LOWTAG_MASK) == 0));
4500 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
4501 /* Must be inside a PA section. */
4502 gc_assert(get_pseudo_atomic_atomic(thread));
4503 #endif
4505 if ((os_vm_size_t) nbytes > large_allocation)
4506 large_allocation = nbytes;
4508 /* maybe we can do this quickly ... */
4509 new_free_pointer = region->free_pointer + nbytes;
4510 if (new_free_pointer <= region->end_addr) {
4511 new_obj = (void*)(region->free_pointer);
4512 region->free_pointer = new_free_pointer;
4513 return(new_obj); /* yup */
4516 /* We don't want to count nbytes against auto_gc_trigger unless we
4517 * have to: it speeds up the tenuring of objects and slows down
4518 * allocation. However, unless we do so when allocating _very_
4519 * large objects we are in danger of exhausting the heap without
4520 * running sufficient GCs.
4522 if ((os_vm_size_t) nbytes >= bytes_consed_between_gcs)
4523 trigger_bytes = nbytes;
4525 /* we have to go the long way around, it seems. Check whether we
4526 * should GC in the near future
4528 if (auto_gc_trigger && (bytes_allocated+trigger_bytes > auto_gc_trigger)) {
4529 /* Don't flood the system with interrupts if the need to gc is
4530 * already noted. This can happen for example when SUB-GC
4531 * allocates or after a gc triggered in a WITHOUT-GCING. */
4532 if (SymbolValue(GC_PENDING,thread) == NIL) {
4533 /* set things up so that GC happens when we finish the PA
4534 * section */
4535 SetSymbolValue(GC_PENDING,T,thread);
4536 if (SymbolValue(GC_INHIBIT,thread) == NIL) {
4537 #ifdef LISP_FEATURE_SB_SAFEPOINT
4538 thread_register_gc_trigger();
4539 #else
4540 set_pseudo_atomic_interrupted(thread);
4541 #ifdef GENCGC_IS_PRECISE
4542 /* PPC calls alloc() from a trap
4543 * look up the most context if it's from a trap. */
4545 os_context_t *context =
4546 thread->interrupt_data->allocation_trap_context;
4547 maybe_save_gc_mask_and_block_deferrables
4548 (context ? os_context_sigmask_addr(context) : NULL);
4550 #else
4551 maybe_save_gc_mask_and_block_deferrables(NULL);
4552 #endif
4553 #endif
4557 new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4559 #ifndef LISP_FEATURE_WIN32
4560 /* for sb-prof, and not supported on Windows yet */
4561 alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4562 if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4563 if ((sword_t) alloc_signal <= 0) {
4564 SetSymbolValue(ALLOC_SIGNAL, T, thread);
4565 raise(SIGPROF);
4566 } else {
4567 SetSymbolValue(ALLOC_SIGNAL,
4568 alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4569 thread);
4572 #endif
4574 return (new_obj);
4577 lispobj *
4578 general_alloc(sword_t nbytes, int page_type_flag)
4580 struct thread *thread = arch_os_get_current_thread();
4581 /* Select correct region, and call general_alloc_internal with it.
4582 * For other then boxed allocation we must lock first, since the
4583 * region is shared. */
4584 if (BOXED_PAGE_FLAG & page_type_flag) {
4585 #ifdef LISP_FEATURE_SB_THREAD
4586 struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4587 #else
4588 struct alloc_region *region = &boxed_region;
4589 #endif
4590 return general_alloc_internal(nbytes, page_type_flag, region, thread);
4591 } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4592 lispobj * obj;
4593 gc_assert(0 == thread_mutex_lock(&allocation_lock));
4594 obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4595 gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4596 return obj;
4597 } else {
4598 lose("bad page type flag: %d", page_type_flag);
4602 lispobj AMD64_SYSV_ABI *
4603 alloc(sword_t nbytes)
4605 #ifdef LISP_FEATURE_SB_SAFEPOINT_STRICTLY
4606 struct thread *self = arch_os_get_current_thread();
4607 int was_pseudo_atomic = get_pseudo_atomic_atomic(self);
4608 if (!was_pseudo_atomic)
4609 set_pseudo_atomic_atomic(self);
4610 #else
4611 gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4612 #endif
4614 lispobj *result = general_alloc(nbytes, BOXED_PAGE_FLAG);
4616 #ifdef LISP_FEATURE_SB_SAFEPOINT_STRICTLY
4617 if (!was_pseudo_atomic)
4618 clear_pseudo_atomic_atomic(self);
4619 #endif
4621 return result;
4625 * shared support for the OS-dependent signal handlers which
4626 * catch GENCGC-related write-protect violations
4628 void unhandled_sigmemoryfault(void* addr);
4630 /* Depending on which OS we're running under, different signals might
4631 * be raised for a violation of write protection in the heap. This
4632 * function factors out the common generational GC magic which needs
4633 * to invoked in this case, and should be called from whatever signal
4634 * handler is appropriate for the OS we're running under.
4636 * Return true if this signal is a normal generational GC thing that
4637 * we were able to handle, or false if it was abnormal and control
4638 * should fall through to the general SIGSEGV/SIGBUS/whatever logic.
4640 * We have two control flags for this: one causes us to ignore faults
4641 * on unprotected pages completely, and the second complains to stderr
4642 * but allows us to continue without losing.
4644 extern boolean ignore_memoryfaults_on_unprotected_pages;
4645 boolean ignore_memoryfaults_on_unprotected_pages = 0;
4647 extern boolean continue_after_memoryfault_on_unprotected_pages;
4648 boolean continue_after_memoryfault_on_unprotected_pages = 0;
4651 gencgc_handle_wp_violation(void* fault_addr)
4653 page_index_t page_index = find_page_index(fault_addr);
4655 #if QSHOW_SIGNALS
4656 FSHOW((stderr,
4657 "heap WP violation? fault_addr=%p, page_index=%"PAGE_INDEX_FMT"\n",
4658 fault_addr, page_index));
4659 #endif
4661 /* Check whether the fault is within the dynamic space. */
4662 if (page_index == (-1)) {
4663 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4664 extern int immobile_space_handle_wp_violation(void*);
4665 if (immobile_space_handle_wp_violation(fault_addr))
4666 return 1;
4667 #endif
4669 /* It can be helpful to be able to put a breakpoint on this
4670 * case to help diagnose low-level problems. */
4671 unhandled_sigmemoryfault(fault_addr);
4673 /* not within the dynamic space -- not our responsibility */
4674 return 0;
4676 } else {
4677 int ret;
4678 ret = thread_mutex_lock(&free_pages_lock);
4679 gc_assert(ret == 0);
4680 if (page_table[page_index].write_protected) {
4681 /* Unprotect the page. */
4682 os_protect(page_address(page_index), GENCGC_CARD_BYTES, OS_VM_PROT_ALL);
4683 page_table[page_index].write_protected_cleared = 1;
4684 page_table[page_index].write_protected = 0;
4685 } else if (!ignore_memoryfaults_on_unprotected_pages) {
4686 /* The only acceptable reason for this signal on a heap
4687 * access is that GENCGC write-protected the page.
4688 * However, if two CPUs hit a wp page near-simultaneously,
4689 * we had better not have the second one lose here if it
4690 * does this test after the first one has already set wp=0
4692 if(page_table[page_index].write_protected_cleared != 1) {
4693 void lisp_backtrace(int frames);
4694 lisp_backtrace(10);
4695 fprintf(stderr,
4696 "Fault @ %p, page %"PAGE_INDEX_FMT" not marked as write-protected:\n"
4697 " boxed_region.first_page: %"PAGE_INDEX_FMT","
4698 " boxed_region.last_page %"PAGE_INDEX_FMT"\n"
4699 " page.scan_start_offset: %"OS_VM_SIZE_FMT"\n"
4700 " page.bytes_used: %"PAGE_BYTES_FMT"\n"
4701 " page.allocated: %d\n"
4702 " page.write_protected: %d\n"
4703 " page.write_protected_cleared: %d\n"
4704 " page.generation: %d\n",
4705 fault_addr,
4706 page_index,
4707 boxed_region.first_page,
4708 boxed_region.last_page,
4709 page_table[page_index].scan_start_offset,
4710 page_table[page_index].bytes_used,
4711 page_table[page_index].allocated,
4712 page_table[page_index].write_protected,
4713 page_table[page_index].write_protected_cleared,
4714 page_table[page_index].gen);
4715 if (!continue_after_memoryfault_on_unprotected_pages)
4716 lose("Feh.\n");
4719 ret = thread_mutex_unlock(&free_pages_lock);
4720 gc_assert(ret == 0);
4721 /* Don't worry, we can handle it. */
4722 return 1;
4725 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4726 * it's not just a case of the program hitting the write barrier, and
4727 * are about to let Lisp deal with it. It's basically just a
4728 * convenient place to set a gdb breakpoint. */
4729 void
4730 unhandled_sigmemoryfault(void *addr)
4733 static void
4734 update_thread_page_tables(struct thread *th)
4736 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4737 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
4738 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->sprof_alloc_region);
4739 #endif
4742 /* GC is single-threaded and all memory allocations during a
4743 collection happen in the GC thread, so it is sufficient to update
4744 all the the page tables once at the beginning of a collection and
4745 update only page tables of the GC thread during the collection. */
4746 void gc_alloc_update_all_page_tables(int for_all_threads)
4748 /* Flush the alloc regions updating the tables. */
4749 struct thread *th;
4750 if (for_all_threads) {
4751 for_each_thread(th) {
4752 update_thread_page_tables(th);
4755 else {
4756 th = arch_os_get_current_thread();
4757 if (th) {
4758 update_thread_page_tables(th);
4761 gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4762 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4765 void
4766 gc_set_region_empty(struct alloc_region *region)
4768 region->first_page = 0;
4769 region->last_page = -1;
4770 region->start_addr = page_address(0);
4771 region->free_pointer = page_address(0);
4772 region->end_addr = page_address(0);
4775 static void
4776 zero_all_free_pages()
4778 page_index_t i;
4780 for (i = 0; i < last_free_page; i++) {
4781 if (page_free_p(i)) {
4782 #ifdef READ_PROTECT_FREE_PAGES
4783 os_protect(page_address(i),
4784 GENCGC_CARD_BYTES,
4785 OS_VM_PROT_ALL);
4786 #endif
4787 zero_pages(i, i);
4792 /* Things to do before doing a final GC before saving a core (without
4793 * purify).
4795 * + Pages in large_object pages aren't moved by the GC, so we need to
4796 * unset that flag from all pages.
4797 * + The pseudo-static generation isn't normally collected, but it seems
4798 * reasonable to collect it at least when saving a core. So move the
4799 * pages to a normal generation.
4801 static void
4802 prepare_for_final_gc ()
4804 page_index_t i;
4806 #ifdef LISP_FEATURE_IMMOBILE_SPACE
4807 extern void prepare_immobile_space_for_final_gc();
4808 prepare_immobile_space_for_final_gc ();
4809 #endif
4810 do_wipe_p = 0;
4811 for (i = 0; i < last_free_page; i++) {
4812 page_table[i].large_object = 0;
4813 if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4814 int used = page_table[i].bytes_used;
4815 page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4816 generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4817 generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4823 /* Do a non-conservative GC, and then save a core with the initial
4824 * function being set to the value of the static symbol
4825 * SB!VM:RESTART-LISP-FUNCTION */
4826 void
4827 gc_and_save(char *filename, boolean prepend_runtime,
4828 boolean save_runtime_options, boolean compressed,
4829 int compression_level, int application_type)
4831 FILE *file;
4832 void *runtime_bytes = NULL;
4833 size_t runtime_size;
4835 file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4836 &runtime_size);
4837 if (file == NULL)
4838 return;
4840 conservative_stack = 0;
4842 /* The filename might come from Lisp, and be moved by the now
4843 * non-conservative GC. */
4844 filename = strdup(filename);
4846 /* Collect twice: once into relatively high memory, and then back
4847 * into low memory. This compacts the retained data into the lower
4848 * pages, minimizing the size of the core file.
4850 prepare_for_final_gc();
4851 gencgc_alloc_start_page = last_free_page;
4852 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4854 prepare_for_final_gc();
4855 gencgc_alloc_start_page = -1;
4856 collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4858 if (prepend_runtime)
4859 save_runtime_to_filehandle(file, runtime_bytes, runtime_size,
4860 application_type);
4862 /* The dumper doesn't know that pages need to be zeroed before use. */
4863 zero_all_free_pages();
4864 save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4865 prepend_runtime, save_runtime_options,
4866 compressed ? compression_level : COMPRESSION_LEVEL_NONE);
4867 /* Oops. Save still managed to fail. Since we've mangled the stack
4868 * beyond hope, there's not much we can do.
4869 * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4870 * going to be rather unsatisfactory too... */
4871 lose("Attempt to save core after non-conservative GC failed.\n");