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