1 ;;;; garbage collection and allocation-related code
3 ;;;; This software is part of the SBCL system. See the README file for
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 (declaim (special sb!vm:*read-only-space-free-pointer*
17 sb!vm:*static-space-free-pointer*))
19 (eval-when (:compile-toplevel :execute)
20 (sb!xc:defmacro def-c-var-frob (lisp-fun c-var-name)
22 #!-sb-fluid (declaim (inline ,lisp-fun))
24 (sb!alien:extern-alien ,c-var-name (sb!alien:unsigned 32))))))
28 ;; This is called once per PROFILEd function call, so it's worth a
29 ;; little possible space cost to reduce its time cost.
31 (declaim (inline current-dynamic-space-start))
32 (def-c-var-frob current-dynamic-space-start "current_dynamic_space"))
35 (declaim (inline dynamic-usage)) ; to reduce PROFILEd call overhead
37 (def-c-var-frob dynamic-usage "bytes_allocated")
39 (defun dynamic-usage ()
40 (the (unsigned-byte 32)
41 (- (sb!sys:sap-int (sb!c::dynamic-space-free-pointer))
42 (current-dynamic-space-start))))
44 (defun static-space-usage ()
45 (- (* sb!vm:*static-space-free-pointer* sb!vm:n-word-bytes)
46 sb!vm:static-space-start))
48 (defun read-only-space-usage ()
49 (- (* sb!vm::*read-only-space-free-pointer* sb!vm:n-word-bytes)
50 sb!vm:read-only-space-start))
52 (defun control-stack-usage ()
53 #!+stack-grows-upward (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
54 sb!vm:control-stack-start)
55 #!+stack-grows-downward (- sb!vm:control-stack-end
57 (sb!c::control-stack-pointer-sap))))
59 (defun binding-stack-usage ()
60 (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
61 sb!vm:binding-stack-start))
65 (defun room-minimal-info ()
66 (format t "Dynamic space usage is: ~10:D bytes.~%" (dynamic-usage))
67 (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
68 (format t "Static space usage is: ~10:D bytes.~%" (static-space-usage))
69 (format t "Control stack usage is: ~10:D bytes.~%" (control-stack-usage))
70 (format t "Binding stack usage is: ~10:D bytes.~%" (binding-stack-usage))
71 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
74 (defun room-intermediate-info ()
76 (sb!vm:memory-usage :count-spaces '(:dynamic)
81 (defun room-maximal-info ()
83 (sb!vm:memory-usage :count-spaces '(:static :dynamic))
84 (sb!vm:instance-usage :dynamic :top-n 10)
85 (sb!vm:instance-usage :static :top-n 10))
87 (defun room (&optional (verbosity :default))
89 "Print to *STANDARD-OUTPUT* information about the state of internal
90 storage and its management. The optional argument controls the
91 verbosity of output. If it is T, ROOM prints out a maximal amount of
92 information. If it is NIL, ROOM prints out a minimal amount of
93 information. If it is :DEFAULT or it is not supplied, ROOM prints out
94 an intermediate amount of information."
102 (room-intermediate-info)))
105 ;;;; GET-BYTES-CONSED
107 ;;; the total number of bytes freed so far (including any freeing
108 ;;; which goes on in PURIFY)
110 ;;; (We save this so that we can calculate the total number of bytes
111 ;;; ever allocated by adding this to the number of bytes currently
112 ;;; allocated and never freed.)
113 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
114 (defvar *n-bytes-freed-or-purified* 0)
116 (setf *n-bytes-freed-or-purified* 0))
117 ;; KLUDGE: It's probably not quite safely right either to do
118 ;; this in *BEFORE-SAVE-INITIALIZATIONS* (since consing, or even
119 ;; worse, something which depended on (GET-BYTES-CONSED), might
120 ;; happen after that) or in *AFTER-SAVE-INITIALIZATIONS*. But
121 ;; it's probably not a big problem, and there seems to be no
122 ;; other obvious time to do it. -- WHN 2001-07-30
123 *after-save-initializations*)
125 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
126 (defun get-bytes-consed ()
128 "Return the number of bytes consed since the program began. Typically
129 this result will be a consed bignum, so if you have an application (e.g.
130 profiling) which can't tolerate the overhead of consing bignums, you'll
131 probably want either to hack in at a lower level (as the code in the
132 SB-PROFILE package does), or to design a more microefficient interface
133 and submit it as a patch."
135 *n-bytes-freed-or-purified*))
137 ;;;; variables and constants
139 ;;; the minimum amount of dynamic space which must be consed before a
140 ;;; GC will be triggered
142 ;;; Unlike CMU CL, we don't export this variable. (There's no need to,
143 ;;; since our BYTES-CONSED-BETWEEN-GCS function is SETFable.)
144 (defvar *bytes-consed-between-gcs*
145 #+gencgc (* 4 (expt 10 6))
146 ;; Stop-and-copy GC is really really slow when used too often. CSR
147 ;; reported that even on his old 64 Mb SPARC, 20 Mb is much faster
148 ;; than 4 Mb when rebuilding SBCL ca. 0.7.1. For modern machines
149 ;; with >> 128 Mb memory, the optimum could be significantly more
150 ;; than this, but at least 20 Mb should be better than 4 Mb.
151 #-gencgc (* 20 (expt 10 6)))
152 (declaim (type index *bytes-consed-between-gcs*))
156 (defvar *before-gc-hooks* nil ; actually initialized in cold init
158 "A list of functions that are called before garbage collection occurs.
159 The functions should take no arguments.")
161 (defvar *after-gc-hooks* nil ; actually initialized in cold init
163 "A list of functions that are called after garbage collection occurs.
164 The functions should take no arguments.")
166 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
168 "When non-NIL, this must be a STREAM; and the functions bound to
169 *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
170 STREAM value before and after a garbage collection occurs
173 (defvar *gc-run-time* 0
175 "the total CPU time spent doing garbage collection (as reported by
176 GET-INTERNAL-RUN-TIME)")
177 (declaim (type index *gc-run-time*))
179 ;;; a limit to help catch programs which allocate too much memory,
180 ;;; since a hard heap overflow is so hard to recover from
181 (declaim (type (or unsigned-byte null) *soft-heap-limit*))
182 (defvar *soft-heap-limit* nil)
184 ;;; When the dynamic usage increases beyond this amount, the system
185 ;;; notes that a garbage collection needs to occur by setting
186 ;;; *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
187 ;;; nobody has figured out what it should be yet.
188 (defvar *gc-trigger* nil)
190 (declaim (type (or index null) *gc-trigger*))
192 ;;; On the X86, we store the GC trigger in a ``static'' symbol instead
193 ;;; of letting magic C code handle it. It gets initialized by the
196 (defvar sb!vm::*internal-gc-trigger*)
198 ;;;; The following specials are used to control when garbage collection
201 ;;; When non-NIL, inhibits garbage collection.
202 (defvar *gc-inhibit*) ; initialized in cold init
204 ;;; This flag is used to prevent recursive entry into the garbage
206 (defvar *already-maybe-gcing*) ; initialized in cold init
208 ;;; When T, indicates that the dynamic usage has exceeded the value
210 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
212 (defun default-gc-notify-before (notify-stream bytes-in-use)
213 (declare (type stream notify-stream))
216 "~&; GC is beginning with ~:D bytes in use at internal runtime ~:D.~%"
218 (get-internal-run-time))
219 (finish-output notify-stream))
220 (defparameter *gc-notify-before* #'default-gc-notify-before
222 "This function bound to this variable is invoked before GC'ing (unless
223 *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
224 current amount of dynamic usage (in bytes). It should notify the
225 user that the system is going to GC.")
227 (defun default-gc-notify-after (notify-stream
231 (declare (type stream notify-stream))
232 (format notify-stream
233 "~&; GC has finished with ~:D bytes in use (~:D bytes freed)~@
234 ; at internal runtime ~:D. The new GC trigger is ~:D bytes.~%"
237 (get-internal-run-time)
239 (finish-output notify-stream))
240 (defparameter *gc-notify-after* #'default-gc-notify-after
242 "The function bound to this variable is invoked after GC'ing with the
243 value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in bytes) now
244 free, the number of bytes freed by the GC, and the new GC trigger
245 threshold; or if *GC-NOTIFY-STREAM* is NIL, it's not invoked. The
246 function should notify the user that the system has finished GC'ing.")
250 (sb!alien:define-alien-routine collect-garbage sb!alien:int
251 #!+gencgc (last-gen sb!alien:int))
253 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
254 (dynamic-usage sb!alien:unsigned-long))
256 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien:void)
258 ;;; This variable contains the function that does the real GC. This is
259 ;;; for low-level GC experimentation. Do not touch it if you do not
260 ;;; know what you are doing.
261 (defvar *internal-gc* #'collect-garbage)
265 ;;; This is used to carefully invoke hooks.
266 (eval-when (:compile-toplevel :execute)
267 (sb!xc:defmacro carefully-funcall (function &rest args)
268 `(handler-case (funcall ,function ,@args)
270 (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
273 ;;; SUB-GC decides when and if to do a garbage collection. The FORCE-P
274 ;;; flags controls whether a GC should occur even if the dynamic usage
275 ;;; is not greater than *GC-TRIGGER*.
277 ;;; For GENCGC all generations < GEN will be GC'ed.
278 (defun sub-gc (&key force-p (gen 0))
279 (/show0 "entering SUB-GC")
280 (unless *already-maybe-gcing*
281 (let* ((*already-maybe-gcing* t)
282 (start-time (get-internal-run-time))
283 (pre-gc-dynamic-usage (dynamic-usage))
284 ;; Currently we only check *SOFT-HEAP-LIMIT* at GC time,
285 ;; not for every allocation. That makes it cheap to do,
286 ;; even if it is a little ugly.
287 (soft-heap-limit-exceeded? (and *soft-heap-limit*
288 (> pre-gc-dynamic-usage
290 (*soft-heap-limit* (if soft-heap-limit-exceeded?
291 (+ pre-gc-dynamic-usage
292 *bytes-consed-between-gcs*)
294 (when soft-heap-limit-exceeded?
295 (cerror "Continue with GC."
296 "soft heap limit exceeded (temporary new limit=~W)"
298 (when (and *gc-trigger* (> pre-gc-dynamic-usage *gc-trigger*))
299 (setf *need-to-collect-garbage* t))
301 (and *need-to-collect-garbage* (not *gc-inhibit*)))
302 ;; KLUDGE: Wow, we really mask interrupts all the time we're
303 ;; collecting garbage? That seems like a long time.. -- WHN 19991129
305 ;; FIXME: We probably shouldn't do this evil thing to
306 ;; *STANDARD-OUTPUT* in a binding which is wrapped around
307 ;; calls to user-settable GC hook functions.
308 (let ((*standard-output* *terminal-io*))
309 (when *gc-notify-stream*
310 (if (streamp *gc-notify-stream*)
311 (carefully-funcall *gc-notify-before*
313 pre-gc-dynamic-usage)
315 "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
316 (dolist (hook *before-gc-hooks*)
317 (carefully-funcall hook))
319 (clear-auto-gc-trigger))
320 (let* (;; We do DYNAMIC-USAGE once more here in order to
321 ;; get a more accurate measurement of the space
322 ;; actually freed, since the messing around, e.g.
323 ;; GC-notify stuff, since the DYNAMIC-USAGE which
324 ;; triggered GC could've done a fair amount of
326 (pre-internal-gc-dynamic-usage (dynamic-usage))
328 #!-gencgc (funcall *internal-gc*)
329 ;; FIXME: This EQ test is pretty gross. Among its other
330 ;; nastinesses, it looks as though it could break if we
331 ;; recompile COLLECT-GARBAGE. We should probably just
332 ;; straighten out the interface so that all *INTERNAL-GC*
333 ;; functions accept a GEN argument (and then the
334 ;; non-generational ones just ignore it).
335 #!+gencgc (if (eq *internal-gc* #'collect-garbage)
336 (funcall *internal-gc* gen)
337 (funcall *internal-gc*)))
338 (post-gc-dynamic-usage (dynamic-usage))
339 (n-bytes-freed (- pre-internal-gc-dynamic-usage
340 post-gc-dynamic-usage))
341 ;; In sbcl-0.6.12.39, the raw N-BYTES-FREED from
342 ;; GENCGC could sometimes be substantially negative
343 ;; (e.g. -5872). I haven't looked into what causes
344 ;; that, but I suspect it has to do with
345 ;; fluctuating inefficiency in the way that the
346 ;; GENCGC packs things into page boundaries.
347 ;; Bumping the raw result up to 0 is a little ugly,
348 ;; but shouldn't be a problem, and it's even
349 ;; possible to sort of justify it: the packing
350 ;; inefficiency which has caused (DYNAMIC-USAGE) to
351 ;; grow is effectively consing, or at least
352 ;; overhead of consing, so it's sort of correct to
353 ;; add it to the running total of consing. ("Man
354 ;; isn't a rational animal, he's a rationalizing
355 ;; animal.":-) -- WHN 2001-06-23
356 (eff-n-bytes-freed (max 0 n-bytes-freed)))
357 (declare (ignore ignore-me))
358 (/show0 "got (DYNAMIC-USAGE) and EFF-N-BYTES-FREED")
359 (incf *n-bytes-freed-or-purified*
361 (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
362 (setf *need-to-collect-garbage* nil)
363 (/show0 "calculating NEW-GC-TRIGGER")
364 (let ((new-gc-trigger (+ post-gc-dynamic-usage
365 *bytes-consed-between-gcs*)))
366 (/show0 "setting *GC-TRIGGER*")
367 (setf *gc-trigger* new-gc-trigger))
368 (/show0 "calling SET-AUTO-GC-TRIGGER")
369 (set-auto-gc-trigger *gc-trigger*)
370 (dolist (hook *after-gc-hooks*)
371 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
372 ;; FIXME: This hook should be called with the same
373 ;; kind of information as *GC-NOTIFY-AFTER*. In
374 ;; particular, it would be nice for the hook function
375 ;; to be able to adjust *GC-TRIGGER* intelligently to
376 ;; e.g. 108% of total memory usage.
377 (carefully-funcall hook))
378 (when *gc-notify-stream*
379 (if (streamp *gc-notify-stream*)
380 (carefully-funcall *gc-notify-after*
382 post-gc-dynamic-usage
386 "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
387 (scrub-control-stack))) ;XXX again? we did this from C ...
388 (incf *gc-run-time* (- (get-internal-run-time)
390 ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
393 ;;; This routine is called by the allocation miscops to decide whether
394 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
395 ;;; object which must be returned to the caller.
396 (defun maybe-gc (&optional object)
400 ;;; This is the user-advertised garbage collection function.
401 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
402 #!+(and sb-doc gencgc)
403 "Initiate a garbage collection. GEN controls the number of generations
405 #!+(and sb-doc (not gencgc))
406 "Initiate a garbage collection. GEN may be provided for compatibility with
407 generational garbage collectors, but is ignored in this implementation."
408 (sub-gc :force-p t :gen (if full 6 gen)))
411 ;;;; auxiliary functions
413 (defun bytes-consed-between-gcs ()
415 "Return the amount of memory that will be allocated before the next garbage
416 collection is initiated. This can be set with SETF."
417 *bytes-consed-between-gcs*)
418 (defun (setf bytes-consed-between-gcs) (val)
419 ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
420 ;; be for a strictly positive number type, e.g.
421 ;; (AND (INTEGER 1) FIXNUM)?
422 (declare (type index val))
423 (let ((old *bytes-consed-between-gcs*))
424 (setf *bytes-consed-between-gcs* val)
426 (setf *gc-trigger* (+ *gc-trigger* (- val old)))
427 (cond ((<= (dynamic-usage) *gc-trigger*)
428 (clear-auto-gc-trigger)
429 (set-auto-gc-trigger *gc-trigger*))
431 ;; FIXME: If SCRUB-CONTROL-STACK is required here, why
432 ;; isn't it built into SUB-GC? And *is* it required here?
433 (sb!sys:scrub-control-stack)
439 "Enable the garbage collector."
440 (setq *gc-inhibit* nil)
441 (when *need-to-collect-garbage*
447 "Disable the garbage collector."
448 (setq *gc-inhibit* t)
451 ;;;; initialization stuff
455 (if (< *gc-trigger* (dynamic-usage))
457 (set-auto-gc-trigger *gc-trigger*))))