Hoist tests from scan_weak_pointers() into scav_weak_pointer()
[sbcl.git] / src / code / gc.lisp
blob64639e7c654e38cde34880838282975848fafa3d
1 ;;;; garbage collection and allocation-related code
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!KERNEL")
14 ;;;; DYNAMIC-USAGE and friends
16 #!-sb-fluid
17 (declaim (inline dynamic-usage))
18 #!+gencgc
19 (defun dynamic-usage ()
20 (extern-alien "bytes_allocated" os-vm-size-t))
21 #!-gencgc
22 (defun dynamic-usage ()
23 (truly-the word
24 (- (sap-int (sb!c::dynamic-space-free-pointer))
25 (current-dynamic-space-start))))
27 (defun static-space-usage ()
28 (- (ash sb!vm:*static-space-free-pointer* sb!vm:n-fixnum-tag-bits)
29 sb!vm:static-space-start))
31 (defun read-only-space-usage ()
32 (- (ash sb!vm::*read-only-space-free-pointer* sb!vm:n-fixnum-tag-bits)
33 sb!vm:read-only-space-start))
35 (defun control-stack-usage ()
36 #!-stack-grows-downward-not-upward
37 (- (sap-int (sb!c::control-stack-pointer-sap))
38 (sap-int (sb!di::descriptor-sap sb!vm:*control-stack-start*)))
39 #!+stack-grows-downward-not-upward
40 (- (sap-int (sb!di::descriptor-sap sb!vm:*control-stack-end*))
41 (sap-int (sb!c::control-stack-pointer-sap))))
43 (defun binding-stack-usage ()
44 (- (sap-int (sb!c::binding-stack-pointer-sap))
45 (sap-int (sb!di::descriptor-sap sb!vm:*binding-stack-start*))))
47 ;;;; ROOM
49 (defun room-minimal-info ()
50 (format t "Dynamic space usage is: ~10:D bytes.~%" (dynamic-usage))
51 (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
52 (format t "Static space usage is: ~10:D bytes.~%" (static-space-usage))
53 (format t "Control stack usage is: ~10:D bytes.~%" (control-stack-usage))
54 (format t "Binding stack usage is: ~10:D bytes.~%" (binding-stack-usage))
55 #!+sb-thread
56 (format t
57 "Control and binding stack usage is for the current thread only.~%")
58 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
59 *gc-inhibit*))
61 (defun room-intermediate-info ()
62 (room-minimal-info)
63 (sb!vm:memory-usage :count-spaces '(:dynamic)
64 :print-spaces t
65 :cutoff 0.05f0
66 :print-summary nil))
68 (defun room-maximal-info ()
69 ;; FIXME: SB!VM:INSTANCE-USAGE calls suppressed until bug 344 is fixed
70 (room-intermediate-info)
71 ;; old way, could be restored when bug 344 fixed:
72 ;;x (room-minimal-info)
73 ;;x (sb!vm:memory-usage :count-spaces '(:static :dynamic))
74 ;;x (sb!vm:instance-usage :dynamic :top-n 10)
75 ;;x (sb!vm:instance-usage :static :top-n 10)
78 (defun room (&optional (verbosity :default))
79 "Print to *STANDARD-OUTPUT* information about the state of internal
80 storage and its management. The optional argument controls the
81 verbosity of output. If it is T, ROOM prints out a maximal amount of
82 information. If it is NIL, ROOM prints out a minimal amount of
83 information. If it is :DEFAULT or it is not supplied, ROOM prints out
84 an intermediate amount of information."
85 (fresh-line)
86 (ecase verbosity
87 ((t)
88 (room-maximal-info))
89 ((nil)
90 (room-minimal-info))
91 (:default
92 (room-intermediate-info)))
93 (values))
95 ;;;; GET-BYTES-CONSED
97 ;;; the total number of bytes freed so far (including any freeing
98 ;;; which goes on in PURIFY)
99 ;;;
100 ;;; (We save this so that we can calculate the total number of bytes
101 ;;; ever allocated by adding this to the number of bytes currently
102 ;;; allocated and never freed.)
103 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
104 (defvar *n-bytes-freed-or-purified* 0)
105 (defun gc-reinit ()
106 (setq *gc-inhibit* nil)
107 (gc)
108 (setf *n-bytes-freed-or-purified* 0
109 *gc-run-time* 0))
111 (declaim (ftype (sfunction () unsigned-byte) get-bytes-consed))
112 (defun get-bytes-consed ()
113 "Return the number of bytes consed since the program began. Typically
114 this result will be a consed bignum, so if you have an application (e.g.
115 profiling) which can't tolerate the overhead of consing bignums, you'll
116 probably want either to hack in at a lower level (as the code in the
117 SB-PROFILE package does), or to design a more microefficient interface
118 and submit it as a patch."
119 (+ (dynamic-usage)
120 *n-bytes-freed-or-purified*))
122 ;;;; GC hooks
124 (!defvar *after-gc-hooks* nil
125 "Called after each garbage collection, except for garbage collections
126 triggered during thread exits. In a multithreaded environment these hooks may
127 run in any thread.")
130 ;;;; internal GC
132 (define-alien-routine collect-garbage int
133 (#!+gencgc last-gen #!-gencgc ignore int))
135 #!+sb-thread
136 (progn
137 (define-alien-routine gc-stop-the-world void)
138 (define-alien-routine gc-start-the-world void))
139 #!-sb-thread
140 (progn
141 (defun gc-stop-the-world ())
142 (defun gc-start-the-world ()))
144 #!+gencgc
145 (progn
146 (define-alien-variable ("gc_logfile" %gc-logfile) (* char))
147 (defun (setf gc-logfile) (pathname)
148 (let ((new (when pathname
149 (make-alien-string
150 (native-namestring (translate-logical-pathname pathname)
151 :as-file t))))
152 (old %gc-logfile))
153 (setf %gc-logfile new)
154 (when old
155 (free-alien old))
156 pathname))
157 (defun gc-logfile ()
158 "Return the pathname used to log garbage collections. Can be SETF.
159 Default is NIL, meaning collections are not logged. If non-null, the
160 designated file is opened before and after each collection, and generation
161 statistics are appended to it."
162 (let ((val (cast %gc-logfile c-string)))
163 (when val
164 (native-pathname val)))))
166 (declaim (inline dynamic-space-size))
167 (defun dynamic-space-size ()
168 "Size of the dynamic space in bytes."
169 (extern-alien "dynamic_space_size" os-vm-size-t))
171 ;;;; SUB-GC
173 ;;; SUB-GC does a garbage collection. This is called from three places:
174 ;;; (1) The C runtime will call here when it detects that we've consed
175 ;;; enough to exceed the gc trigger threshold. This is done in
176 ;;; alloc() for gencgc or interrupt_maybe_gc() for cheneygc
177 ;;; (2) The user may request a collection using GC, below
178 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
179 ;;; *NEED-TO-COLLECT-GARBAGE* is true
181 ;;; This is different from the behaviour in 0.7 and earlier: it no
182 ;;; longer decides whether to GC based on thresholds. If you call
183 ;;; SUB-GC you will definitely get a GC either now or when the
184 ;;; WITHOUT-GCING is over
186 ;;; For GENCGC all generations < GEN will be GC'ed.
188 (defvar *already-in-gc* (sb!thread:make-mutex :name "GC lock"))
190 (defun sub-gc (&key (gen 0))
191 (cond (*gc-inhibit*
192 (setf *gc-pending* t)
193 nil)
195 (flet ((perform-gc ()
196 ;; Called from WITHOUT-GCING and WITHOUT-INTERRUPTS
197 ;; after the world has been stopped, but it's an
198 ;; awkwardly long piece of code to nest so deeply.
199 (let ((old-usage (dynamic-usage))
200 (new-usage 0)
201 (start-time (get-internal-run-time)))
202 (collect-garbage gen)
203 (setf *gc-epoch* (cons nil nil))
204 (let ((run-time (- (get-internal-run-time) start-time)))
205 ;; KLUDGE: Sometimes we see the second getrusage() call
206 ;; return a smaller value than the first, which can
207 ;; lead to *GC-RUN-TIME* to going negative, which in
208 ;; turn is a type-error.
209 (when (plusp run-time)
210 (incf *gc-run-time* run-time)))
211 #!+sb-safepoint
212 (setf *stop-for-gc-pending* nil)
213 (setf *gc-pending* nil
214 new-usage (dynamic-usage))
215 #!+sb-thread
216 (assert (not *stop-for-gc-pending*))
217 (gc-start-the-world)
218 ;; In a multithreaded environment the other threads
219 ;; will see *n-b-f-o-p* change a little late, but
220 ;; that's OK.
221 ;; N.B. the outer without-gcing prevents this
222 ;; function from being entered, so no need for
223 ;; locking.
224 (let ((freed (- old-usage new-usage)))
225 ;; GENCGC occasionally reports negative here, but
226 ;; the current belief is that it is part of the
227 ;; normal order of things and not a bug.
228 (when (plusp freed)
229 (incf *n-bytes-freed-or-purified* freed))))))
230 (declare (inline perform-gc))
231 ;; Let's make sure we're not interrupted and that none of
232 ;; the deadline or deadlock detection stuff triggers.
233 (without-interrupts
234 (sb!thread::without-thread-waiting-for
235 (:already-without-interrupts t)
236 (let ((sb!impl::*deadline* nil)
237 (sb!impl::*deadline-seconds* nil)
238 (epoch *gc-epoch*))
239 (loop
240 ;; GCing must be done without-gcing to avoid
241 ;; recursive GC... but we can't block on
242 ;; *already-in-gc* inside without-gcing: that would
243 ;; cause a deadlock.
244 (without-gcing
245 ;; Try to grab that mutex. On acquisition, stop
246 ;; the world from with the mutex held, and then
247 ;; execute the remainder of the GC: stopping the
248 ;; world with interrupts disabled is the mother of
249 ;; all critical sections.
250 (cond ((sb!thread:with-mutex (*already-in-gc* :wait-p nil)
251 (unsafe-clear-roots gen)
252 (gc-stop-the-world)
254 ;; Success! GC.
255 (perform-gc)
256 ;; Return, but leave *gc-pending* as is: we
257 ;; did allocate a tiny bit after GCing. In
258 ;; theory, this could lead to a long chain
259 ;; of tail-recursive (but not in explicit
260 ;; tail position) GCs, but that doesn't
261 ;; seem likely to happen too often... And
262 ;; the old code already suffered from this
263 ;; problem.
264 (return t))
266 ;; Some other thread is trying to GC. Clear
267 ;; *gc-pending* (we already know we want a
268 ;; GC to happen) and either let
269 ;; without-gcing figure out that the world
270 ;; is stopping, or try again.
271 (setf *gc-pending* nil))))
272 ;; we just wanted a minor GC, and a GC has
273 ;; occurred. Leave, but don't execute after-gc
274 ;; hooks.
276 ;; Return a 0 for easy ternary logic in the C
277 ;; runtime.
278 (when (and (eql gen 0)
279 (neq epoch *gc-pending*))
280 (return 0))))))))))
282 (defun post-gc ()
283 ;; Outside the mutex, interrupts may be enabled: these may cause
284 ;; another GC. FIXME: it can potentially exceed maximum interrupt
285 ;; nesting by triggering GCs.
287 ;; Can that be avoided by having the finalizers and hooks run only
288 ;; from the outermost SUB-GC? If the nested GCs happen in interrupt
289 ;; handlers that's not enough.
291 ;; KLUDGE: Don't run the hooks in GC's if:
293 ;; A) this thread is dying, so that user-code never runs with
294 ;; (thread-alive-p *current-thread*) => nil
296 ;; B) interrupts are disabled somewhere up the call chain since we
297 ;; don't want to run user code in such a case.
299 ;; The long-term solution will be to keep a separate thread for
300 ;; finalizers and after-gc hooks.
301 (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
302 (when *allow-with-interrupts*
303 (sb!thread::without-thread-waiting-for ()
304 (with-interrupts
305 (run-pending-finalizers)
306 (call-hooks "after-GC" *after-gc-hooks* :on-error :warn))))))
308 ;;; This is the user-advertised garbage collection function.
309 (defun gc (&key (full nil) (gen 0) &allow-other-keys)
310 #!+gencgc
311 "Initiate a garbage collection.
313 The default is to initiate a nursery collection, which may in turn
314 trigger a collection of one or more older generations as well. If FULL
315 is true, all generations are collected. If GEN is provided, it can be
316 used to specify the oldest generation guaranteed to be collected.
318 On CheneyGC platforms arguments FULL and GEN take no effect: a full
319 collection is always performed."
320 #!-gencgc
321 "Initiate a garbage collection.
323 The collection is always a full collection.
325 Arguments FULL and GEN can be used for compatibility with GENCGC
326 platforms: there the default is to initiate a nursery collection,
327 which may in turn trigger a collection of one or more older
328 generations as well. If FULL is true, all generations are collected.
329 If GEN is provided, it can be used to specify the oldest generation
330 guaranteed to be collected."
331 #!-gencgc (declare (ignore full))
332 (let (#!+gencgc (gen (if full sb!vm:+pseudo-static-generation+ gen)))
333 (when (eq t (sub-gc :gen gen))
334 (post-gc))))
336 (define-alien-routine scrub-control-stack void)
338 (defun unsafe-clear-roots (gen)
339 #!-gencgc (declare (ignore gen))
340 ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
341 ;; as having these cons more than we have space left leads to huge
342 ;; badness.
343 (scrub-control-stack)
344 ;; Power cache of the bignum printer: drops overly large bignums and
345 ;; removes duplicate entries.
346 (scrub-power-cache)
347 ;; Clear caches depending on the generation being collected.
348 #!+gencgc
349 (cond ((eql 0 gen)
350 ;; Drop strings because the hash is pointer-hash
351 ;; but there is no automatic cache rehashing after GC.
352 (sb!format::tokenize-control-string-cache-clear))
353 ((eql 1 gen)
354 (sb!format::tokenize-control-string-cache-clear)
355 (ctype-of-cache-clear))
357 (drop-all-hash-caches)))
358 #!-gencgc
359 (drop-all-hash-caches))
361 ;;;; auxiliary functions
363 (defun bytes-consed-between-gcs ()
364 "The amount of memory that will be allocated before the next garbage
365 collection is initiated. This can be set with SETF.
367 On GENCGC platforms this is the nursery size, and defaults to 5% of dynamic
368 space size.
370 Note: currently changes to this value are lost when saving core."
371 (extern-alien "bytes_consed_between_gcs" os-vm-size-t))
373 (defun (setf bytes-consed-between-gcs) (val)
374 (declare (type index val))
375 (setf (extern-alien "bytes_consed_between_gcs" os-vm-size-t)
376 val))
378 (declaim (inline maybe-handle-pending-gc))
379 (defun maybe-handle-pending-gc ()
380 (when (and (not *gc-inhibit*)
381 (or #!+sb-thread *stop-for-gc-pending*
382 *gc-pending*))
383 (sb!unix::receive-pending-interrupt)))
385 ;;;; GENCGC specifics
386 ;;;;
387 ;;;; For documentation convenience, these have stubs on non-GENCGC platforms
388 ;;;; as well.
389 #!+gencgc
390 (deftype generation-index ()
391 '(integer 0 #.sb!vm:+pseudo-static-generation+))
393 ;;; FIXME: GENERATION (and PAGE, as seen in room.lisp) should probably be
394 ;;; defined in Lisp, and written to header files by genesis, instead of this
395 ;;; OAOOMiness -- this duplicates the struct definition in gencgc.c.
396 #!+gencgc
397 (define-alien-type generation
398 (struct generation
399 (alloc-start-page page-index-t)
400 (alloc-unboxed-start-page page-index-t)
401 (alloc-large-start-page page-index-t)
402 (alloc-large-unboxed-start-page page-index-t)
403 (bytes-allocated os-vm-size-t)
404 (gc-trigger os-vm-size-t)
405 (bytes-consed-between-gcs os-vm-size-t)
406 (number-of-gcs int)
407 (number-of-gcs-before-promotion int)
408 (cum-sum-bytes-allocated os-vm-size-t)
409 (minimum-age-before-gc double)))
411 #!+gencgc
412 (define-alien-variable generations
413 (array generation #.(1+ sb!vm:+pseudo-static-generation+)))
415 (macrolet ((def (slot doc &optional setfp)
416 `(progn
417 (defun ,(symbolicate "GENERATION-" slot) (generation)
418 ,doc
419 #!+gencgc
420 (declare (generation-index generation))
421 #!-gencgc
422 (declare (ignore generation))
423 #!-gencgc
424 (error "~S is a GENCGC only function and unavailable in this build"
425 ',slot)
426 #!+gencgc
427 (slot (deref generations generation) ',slot))
428 ,@(when setfp
429 `((defun (setf ,(symbolicate "GENERATION-" slot)) (value generation)
430 #!+gencgc
431 (declare (generation-index generation))
432 #!-gencgc
433 (declare (ignore value generation))
434 #!-gencgc
435 (error "(SETF ~S) is a GENCGC only function and unavailable in this build"
436 ',slot)
437 #!+gencgc
438 (setf (slot (deref generations generation) ',slot) value)))))))
439 (def bytes-consed-between-gcs
440 "Number of bytes that can be allocated to GENERATION before that
441 generation is considered for garbage collection. This value is meaningless for
442 generation 0 (the nursery): see BYTES-CONSED-BETWEEN-GCS instead. Default is
443 5% of the dynamic space size divided by the number of non-nursery generations.
444 Can be assigned to using SETF. Available on GENCGC platforms only.
446 Experimental: interface subject to change."
448 (def minimum-age-before-gc
449 "Minimum average age of objects allocated to GENERATION before that
450 generation is may be garbage collected. Default is 0.75. See also
451 GENERATION-AVERAGE-AGE. Can be assigned to using SETF. Available on GENCGC
452 platforms only.
454 Experimental: interface subject to change."
456 (def number-of-gcs-before-promotion
457 "Number of times garbage collection is done on GENERATION before
458 automatic promotion to the next generation is triggered. Default is 1. Can be
459 assigned to using SETF. Available on GENCGC platforms only.
461 Experimental: interface subject to change."
463 (def bytes-allocated
464 "Number of bytes allocated to GENERATION currently. Available on GENCGC
465 platforms only.
467 Experimental: interface subject to change.")
468 (def number-of-gcs
469 "Number of times garbage collection has been done on GENERATION without
470 promotion. Available on GENCGC platforms only.
472 Experimental: interface subject to change."))
473 (defun generation-average-age (generation)
474 "Average age of memory allocated to GENERATION: average number of times
475 objects allocated to the generation have seen younger objects promoted to it.
476 Available on GENCGC platforms only.
478 Experimental: interface subject to change."
479 #!+gencgc
480 (declare (generation-index generation))
481 #!-gencgc (declare (ignore generation))
482 #!-gencgc
483 (error "~S is a GENCGC only function and unavailable in this build."
484 'generation-average-age)
485 #!+gencgc
486 (alien-funcall (extern-alien "generation_average_age"
487 (function double generation-index-t))
488 generation))