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