More robust undefined restarts.
[sbcl.git] / src / code / gc.lisp
blobbe81e61d512c0c3c25f76f6c2d3767ee985f8f8d
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
110 ;; See comment in interr.lisp
111 *heap-exhausted-error-condition* (make-condition 'heap-exhausted-error)))
113 (declaim (ftype (sfunction () unsigned-byte) get-bytes-consed))
114 (defun get-bytes-consed ()
115 "Return the number of bytes consed since the program began. Typically
116 this result will be a consed bignum, so if you have an application (e.g.
117 profiling) which can't tolerate the overhead of consing bignums, you'll
118 probably want either to hack in at a lower level (as the code in the
119 SB-PROFILE package does), or to design a more microefficient interface
120 and submit it as a patch."
121 (+ (dynamic-usage)
122 *n-bytes-freed-or-purified*))
124 ;;;; GC hooks
126 (!defvar *after-gc-hooks* nil
127 "Called after each garbage collection, except for garbage collections
128 triggered during thread exits. In a multithreaded environment these hooks may
129 run in any thread.")
132 ;;;; internal GC
134 (define-alien-routine collect-garbage int
135 (#!+gencgc last-gen #!-gencgc ignore int))
137 #!+sb-thread
138 (progn
139 (define-alien-routine gc-stop-the-world void)
140 (define-alien-routine gc-start-the-world void))
141 #!-sb-thread
142 (progn
143 (defun gc-stop-the-world ())
144 (defun gc-start-the-world ()))
146 #!+gencgc
147 (progn
148 (define-alien-variable ("gc_logfile" %gc-logfile) (* char))
149 (defun (setf gc-logfile) (pathname)
150 (let ((new (when pathname
151 (make-alien-string
152 (native-namestring (translate-logical-pathname pathname)
153 :as-file t))))
154 (old %gc-logfile))
155 (setf %gc-logfile new)
156 (when old
157 (free-alien old))
158 pathname))
159 (defun gc-logfile ()
160 "Return the pathname used to log garbage collections. Can be SETF.
161 Default is NIL, meaning collections are not logged. If non-null, the
162 designated file is opened before and after each collection, and generation
163 statistics are appended to it."
164 (let ((val (cast %gc-logfile c-string)))
165 (when val
166 (native-pathname val)))))
168 (declaim (inline dynamic-space-size))
169 (defun dynamic-space-size ()
170 "Size of the dynamic space in bytes."
171 (extern-alien "dynamic_space_size" os-vm-size-t))
173 ;;;; SUB-GC
175 ;;; SUB-GC does a garbage collection. This is called from three places:
176 ;;; (1) The C runtime will call here when it detects that we've consed
177 ;;; enough to exceed the gc trigger threshold. This is done in
178 ;;; alloc() for gencgc or interrupt_maybe_gc() for cheneygc
179 ;;; (2) The user may request a collection using GC, below
180 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
181 ;;; *NEED-TO-COLLECT-GARBAGE* is true
183 ;;; This is different from the behaviour in 0.7 and earlier: it no
184 ;;; longer decides whether to GC based on thresholds. If you call
185 ;;; SUB-GC you will definitely get a GC either now or when the
186 ;;; WITHOUT-GCING is over
188 ;;; For GENCGC all generations < GEN will be GC'ed.
190 (defvar *already-in-gc* (sb!thread:make-mutex :name "GC lock"))
192 (defun sub-gc (&key (gen 0))
193 (cond (*gc-inhibit*
194 (setf *gc-pending* t)
195 nil)
197 (flet ((perform-gc ()
198 ;; Called from WITHOUT-GCING and WITHOUT-INTERRUPTS
199 ;; after the world has been stopped, but it's an
200 ;; awkwardly long piece of code to nest so deeply.
201 (let ((old-usage (dynamic-usage))
202 (new-usage 0)
203 (start-time (get-internal-run-time)))
204 (collect-garbage gen)
205 (setf *gc-epoch* (cons nil nil))
206 (let ((run-time (- (get-internal-run-time) start-time)))
207 ;; KLUDGE: Sometimes we see the second getrusage() call
208 ;; return a smaller value than the first, which can
209 ;; lead to *GC-RUN-TIME* to going negative, which in
210 ;; turn is a type-error.
211 (when (plusp run-time)
212 (incf *gc-run-time* run-time)))
213 #!+sb-safepoint
214 (setf *stop-for-gc-pending* nil)
215 (setf *gc-pending* nil
216 new-usage (dynamic-usage))
217 #!+sb-thread
218 (assert (not *stop-for-gc-pending*))
219 (gc-start-the-world)
220 ;; In a multithreaded environment the other threads
221 ;; will see *n-b-f-o-p* change a little late, but
222 ;; that's OK.
223 ;; N.B. the outer without-gcing prevents this
224 ;; function from being entered, so no need for
225 ;; locking.
226 (let ((freed (- old-usage new-usage)))
227 ;; GENCGC occasionally reports negative here, but
228 ;; the current belief is that it is part of the
229 ;; normal order of things and not a bug.
230 (when (plusp freed)
231 (incf *n-bytes-freed-or-purified* freed))))))
232 (declare (inline perform-gc))
233 ;; Let's make sure we're not interrupted and that none of
234 ;; the deadline or deadlock detection stuff triggers.
235 (without-interrupts
236 (sb!thread::without-thread-waiting-for
237 (:already-without-interrupts t)
238 (let ((sb!impl::*deadline* nil)
239 (sb!impl::*deadline-seconds* nil)
240 (epoch *gc-epoch*))
241 (loop
242 ;; GCing must be done without-gcing to avoid
243 ;; recursive GC... but we can't block on
244 ;; *already-in-gc* inside without-gcing: that would
245 ;; cause a deadlock.
246 (without-gcing
247 ;; Try to grab that mutex. On acquisition, stop
248 ;; the world from with the mutex held, and then
249 ;; execute the remainder of the GC: stopping the
250 ;; world with interrupts disabled is the mother of
251 ;; all critical sections.
252 (cond ((sb!thread:with-mutex (*already-in-gc* :wait-p nil)
253 (unsafe-clear-roots gen)
254 (gc-stop-the-world)
256 ;; Success! GC.
257 (perform-gc)
258 ;; Return, but leave *gc-pending* as is: we
259 ;; did allocate a tiny bit after GCing. In
260 ;; theory, this could lead to a long chain
261 ;; of tail-recursive (but not in explicit
262 ;; tail position) GCs, but that doesn't
263 ;; seem likely to happen too often... And
264 ;; the old code already suffered from this
265 ;; problem.
266 (return t))
268 ;; Some other thread is trying to GC. Clear
269 ;; *gc-pending* (we already know we want a
270 ;; GC to happen) and either let
271 ;; without-gcing figure out that the world
272 ;; is stopping, or try again.
273 (setf *gc-pending* nil))))
274 ;; we just wanted a minor GC, and a GC has
275 ;; occurred. Leave, but don't execute after-gc
276 ;; hooks.
278 ;; Return a 0 for easy ternary logic in the C
279 ;; runtime.
280 (when (and (eql gen 0)
281 (neq epoch *gc-pending*))
282 (return 0))))))))))
284 (defun post-gc ()
285 ;; Outside the mutex, interrupts may be enabled: these may cause
286 ;; another GC. FIXME: it can potentially exceed maximum interrupt
287 ;; nesting by triggering GCs.
289 ;; Can that be avoided by having the finalizers and hooks run only
290 ;; from the outermost SUB-GC? If the nested GCs happen in interrupt
291 ;; handlers that's not enough.
293 ;; KLUDGE: Don't run the hooks in GC's if:
295 ;; A) this thread is dying, so that user-code never runs with
296 ;; (thread-alive-p *current-thread*) => nil
298 ;; B) interrupts are disabled somewhere up the call chain since we
299 ;; don't want to run user code in such a case.
301 ;; The long-term solution will be to keep a separate thread for
302 ;; finalizers and after-gc hooks.
303 (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
304 (when *allow-with-interrupts*
305 (sb!thread::without-thread-waiting-for ()
306 (with-interrupts
307 (run-pending-finalizers)
308 (call-hooks "after-GC" *after-gc-hooks* :on-error :warn))))))
310 ;;; This is the user-advertised garbage collection function.
311 (defun gc (&key (full nil) (gen 0) &allow-other-keys)
312 #!+gencgc
313 "Initiate a garbage collection.
315 The default is to initiate a nursery collection, which may in turn
316 trigger a collection of one or more older generations as well. If FULL
317 is true, all generations are collected. If GEN is provided, it can be
318 used to specify the oldest generation guaranteed to be collected.
320 On CheneyGC platforms arguments FULL and GEN take no effect: a full
321 collection is always performed."
322 #!-gencgc
323 "Initiate a garbage collection.
325 The collection is always a full collection.
327 Arguments FULL and GEN can be used for compatibility with GENCGC
328 platforms: there the default is to initiate a nursery collection,
329 which may in turn trigger a collection of one or more older
330 generations as well. If FULL is true, all generations are collected.
331 If GEN is provided, it can be used to specify the oldest generation
332 guaranteed to be collected."
333 #!-gencgc (declare (ignore full))
334 (let (#!+gencgc (gen (if full sb!vm:+pseudo-static-generation+ gen)))
335 (when (eq t (sub-gc :gen gen))
336 (post-gc))))
338 (define-alien-routine scrub-control-stack void)
340 (defun unsafe-clear-roots (gen)
341 #!-gencgc (declare (ignore gen))
342 ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
343 ;; as having these cons more than we have space left leads to huge
344 ;; badness.
345 (scrub-control-stack)
346 ;; Power cache of the bignum printer: drops overly large bignums and
347 ;; removes duplicate entries.
348 (scrub-power-cache)
349 ;; Clear caches depending on the generation being collected.
350 #!+gencgc
351 (cond ((eql 0 gen)
352 ;; Drop strings because the hash is pointer-hash
353 ;; but there is no automatic cache rehashing after GC.
354 (sb!format::tokenize-control-string-cache-clear))
355 ((eql 1 gen)
356 (sb!format::tokenize-control-string-cache-clear)
357 (ctype-of-cache-clear))
359 (drop-all-hash-caches)))
360 #!-gencgc
361 (drop-all-hash-caches))
363 ;;;; auxiliary functions
365 (defun bytes-consed-between-gcs ()
366 "The amount of memory that will be allocated before the next garbage
367 collection is initiated. This can be set with SETF.
369 On GENCGC platforms this is the nursery size, and defaults to 5% of dynamic
370 space size.
372 Note: currently changes to this value are lost when saving core."
373 (extern-alien "bytes_consed_between_gcs" os-vm-size-t))
375 (defun (setf bytes-consed-between-gcs) (val)
376 (declare (type index val))
377 (setf (extern-alien "bytes_consed_between_gcs" os-vm-size-t)
378 val))
380 (declaim (inline maybe-handle-pending-gc))
381 (defun maybe-handle-pending-gc ()
382 (when (and (not *gc-inhibit*)
383 (or #!+sb-thread *stop-for-gc-pending*
384 *gc-pending*))
385 (sb!unix::receive-pending-interrupt)))
387 ;;;; GENCGC specifics
388 ;;;;
389 ;;;; For documentation convenience, these have stubs on non-GENCGC platforms
390 ;;;; as well.
391 #!+gencgc
392 (deftype generation-index ()
393 '(integer 0 #.sb!vm:+pseudo-static-generation+))
395 ;;; FIXME: GENERATION (and PAGE, as seen in room.lisp) should probably be
396 ;;; defined in Lisp, and written to header files by genesis, instead of this
397 ;;; OAOOMiness -- this duplicates the struct definition in gencgc.c.
398 #!+gencgc
399 (define-alien-type generation
400 (struct generation
401 (alloc-start-page page-index-t)
402 (alloc-unboxed-start-page page-index-t)
403 (alloc-large-start-page page-index-t)
404 (alloc-large-unboxed-start-page page-index-t)
405 (bytes-allocated os-vm-size-t)
406 (gc-trigger os-vm-size-t)
407 (bytes-consed-between-gcs os-vm-size-t)
408 (number-of-gcs int)
409 (number-of-gcs-before-promotion int)
410 (cum-sum-bytes-allocated os-vm-size-t)
411 (minimum-age-before-gc double)))
413 #!+gencgc
414 (define-alien-variable generations
415 (array generation #.(1+ sb!vm:+pseudo-static-generation+)))
417 (macrolet ((def (slot doc &optional setfp)
418 `(progn
419 (defun ,(symbolicate "GENERATION-" slot) (generation)
420 ,doc
421 #!+gencgc
422 (declare (generation-index generation))
423 #!-gencgc
424 (declare (ignore generation))
425 #!-gencgc
426 (error "~S is a GENCGC only function and unavailable in this build"
427 ',slot)
428 #!+gencgc
429 (slot (deref generations generation) ',slot))
430 ,@(when setfp
431 `((defun (setf ,(symbolicate "GENERATION-" slot)) (value generation)
432 #!+gencgc
433 (declare (generation-index generation))
434 #!-gencgc
435 (declare (ignore value generation))
436 #!-gencgc
437 (error "(SETF ~S) is a GENCGC only function and unavailable in this build"
438 ',slot)
439 #!+gencgc
440 (setf (slot (deref generations generation) ',slot) value)))))))
441 (def bytes-consed-between-gcs
442 "Number of bytes that can be allocated to GENERATION before that
443 generation is considered for garbage collection. This value is meaningless for
444 generation 0 (the nursery): see BYTES-CONSED-BETWEEN-GCS instead. Default is
445 5% of the dynamic space size divided by the number of non-nursery generations.
446 Can be assigned to using SETF. Available on GENCGC platforms only.
448 Experimental: interface subject to change."
450 (def minimum-age-before-gc
451 "Minimum average age of objects allocated to GENERATION before that
452 generation is may be garbage collected. Default is 0.75. See also
453 GENERATION-AVERAGE-AGE. Can be assigned to using SETF. Available on GENCGC
454 platforms only.
456 Experimental: interface subject to change."
458 (def number-of-gcs-before-promotion
459 "Number of times garbage collection is done on GENERATION before
460 automatic promotion to the next generation is triggered. Default is 1. Can be
461 assigned to using SETF. Available on GENCGC platforms only.
463 Experimental: interface subject to change."
465 (def bytes-allocated
466 "Number of bytes allocated to GENERATION currently. Available on GENCGC
467 platforms only.
469 Experimental: interface subject to change.")
470 (def number-of-gcs
471 "Number of times garbage collection has been done on GENERATION without
472 promotion. Available on GENCGC platforms only.
474 Experimental: interface subject to change."))
475 (defun generation-average-age (generation)
476 "Average age of memory allocated to GENERATION: average number of times
477 objects allocated to the generation have seen younger objects promoted to it.
478 Available on GENCGC platforms only.
480 Experimental: interface subject to change."
481 #!+gencgc
482 (declare (generation-index generation))
483 #!-gencgc (declare (ignore generation))
484 #!-gencgc
485 (error "~S is a GENCGC only function and unavailable in this build."
486 'generation-average-age)
487 #!+gencgc
488 (alien-funcall (extern-alien "generation_average_age"
489 (function double generation-index-t))
490 generation))