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))))))
26 #!+(or cgc gencgc) (progn
27 #!-sb-fluid (declaim (inline dynamic-usage))
28 (def-c-var-frob dynamic-usage "bytes_allocated"))
31 (defun dynamic-usage ()
32 (the (unsigned-byte 32)
33 (- (sb!sys:sap-int (sb!c::dynamic-space-free-pointer))
34 (current-dynamic-space-start))))
37 #!-sb-fluid (declaim (inline current-dynamic-space-start))
38 (def-c-var-frob current-dynamic-space-start "current_dynamic_space"))
40 (defun static-space-usage ()
41 (- (* sb!vm:*static-space-free-pointer* sb!vm:word-bytes)
42 sb!vm:static-space-start))
44 (defun read-only-space-usage ()
45 (- (* sb!vm::*read-only-space-free-pointer* sb!vm:word-bytes)
46 sb!vm:read-only-space-start))
48 (defun control-stack-usage ()
49 #!-x86 (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
50 sb!vm:control-stack-start)
51 #!+x86 (- sb!vm:control-stack-end
52 (sb!sys:sap-int (sb!c::control-stack-pointer-sap))))
54 (defun binding-stack-usage ()
55 (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
56 sb!vm:binding-stack-start))
60 (defun room-minimal-info ()
61 (format t "Dynamic space usage is: ~10:D bytes.~%" (dynamic-usage))
62 (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
63 (format t "Static space usage is: ~10:D bytes.~%" (static-space-usage))
64 (format t "Control stack usage is: ~10:D bytes.~%" (control-stack-usage))
65 (format t "Binding stack usage is: ~10:D bytes.~%" (binding-stack-usage))
66 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
69 (defun room-intermediate-info ()
71 (sb!vm:memory-usage :count-spaces '(:dynamic)
76 (defun room-maximal-info ()
78 (sb!vm:memory-usage :count-spaces '(:static :dynamic))
79 (sb!vm:instance-usage :dynamic :top-n 10)
80 (sb!vm:instance-usage :static :top-n 10))
82 (defun room (&optional (verbosity :default))
84 "Print to *STANDARD-OUTPUT* information about the state of internal
85 storage and its management. The optional argument controls the
86 verbosity of output. If it is T, ROOM prints out a maximal amount of
87 information. If it is NIL, ROOM prints out a minimal amount of
88 information. If it is :DEFAULT or it is not supplied, ROOM prints out
89 an intermediate amount of information."
97 (room-intermediate-info)))
100 ;;;; GET-BYTES-CONSED
103 (defvar *last-bytes-in-use* nil)
104 (defvar *total-bytes-consed* 0)
105 (declaim (type (or index null) *last-bytes-in-use*))
106 (declaim (type unsigned-byte *total-bytes-consed*))
108 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
109 (defun get-bytes-consed ()
111 "Return the number of bytes consed since the first time this function
112 was called. The first time it is called, it returns zero."
113 (declare (optimize (speed 3) (safety 0)))
114 (cond ((null *last-bytes-in-use*)
115 (setq *last-bytes-in-use* (dynamic-usage))
116 (setq *total-bytes-consed* 0))
118 (let ((bytes (dynamic-usage)))
119 (incf *total-bytes-consed*
120 (the index (- bytes *last-bytes-in-use*)))
121 (setq *last-bytes-in-use* bytes))))
122 ;; FIXME: We should really use something like PCOUNTER to make this
124 (aver (not (minusp *total-bytes-consed*)))
125 *total-bytes-consed*)
127 ;;;; variables and constants
129 ;;; the default value of *BYTES-CONSED-BETWEEN-GCS* and *GC-TRIGGER*
130 (defconstant default-bytes-consed-between-gcs 2000000)
132 ;;; the minimum amount of dynamic space which must be consed before a
133 ;;; GC will be triggered
135 ;;; Unlike CMU CL, we don't export this variable. (There's no need to,
136 ;;; since the BYTES-CONSED-BETWEEN-GCS function is SETFable.)
137 (defvar *bytes-consed-between-gcs* default-bytes-consed-between-gcs)
138 (declaim (type index *bytes-consed-between-gcs*))
142 ;;; These variables are a list of functions which are run before and
143 ;;; after garbage collection occurs.
144 (defvar *before-gc-hooks* nil ; actually initialized in cold init
146 "A list of functions that are called before garbage collection occurs.
147 The functions should take no arguments.")
148 (defvar *after-gc-hooks* nil ; actually initialized in cold init
150 "A list of functions that are called after garbage collection occurs.
151 The functions should take no arguments.")
153 ;;; This hook is invoked whenever SUB-GC intends to GC (unless the GC
154 ;;; was explicitly forced by calling SB!EXT:GC). If the hook function
155 ;;; returns NIL then the GC procedes; otherwise, the GC is inhibited and
156 ;;; *GC-INHIBIT* and *NEED-TO-COLLECT-GARBAGE* are left bound to T.
157 ;;; Presumably someone will call GC-ON later to collect the garbage.
158 (defvar *gc-inhibit-hook* nil
160 "This should be bound to a function or NIL. If it is a function, this
161 function should take one argument, the current amount of dynamic
162 usage. The function should return NIL if garbage collection should
163 continue and non-NIL if it should be inhibited. Use with caution.")
165 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
167 "When non-NIL, this must be a STREAM; and the functions bound to
168 *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
169 STREAM value before and after a garbage collection occurs
172 (defvar *gc-run-time* 0
174 "the total CPU time spent doing garbage collection (as reported by
175 GET-INTERNAL-RUN-TIME)")
176 (declaim (type index *gc-run-time*))
178 ;;; a limit to help catch programs which allocate too much memory,
179 ;;; since a hard heap overflow is so hard to recover from.
180 (declaim (type (or unsigned-byte null) *soft-heap-limit*))
181 (defvar *soft-heap-limit* nil)
183 ;;; Internal trigger. When the dynamic usage increases beyond this
184 ;;; amount, the system notes that a garbage collection needs to occur by
185 ;;; setting *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
186 ;;; nobody has figured out what it should be yet.
187 (defvar *gc-trigger* nil)
189 (declaim (type (or index null) *gc-trigger*))
191 ;;; On the X86, we store the GC trigger in a ``static'' symbol instead
192 ;;; of letting magic C code handle it. It gets initialized by the
195 (defvar sb!vm::*internal-gc-trigger*)
197 ;;;; The following specials are used to control when garbage collection
200 ;;; When non-NIL, inhibits garbage collection.
201 (defvar *gc-inhibit*) ; initialized in cold init
203 ;;; This flag is used to prevent recursive entry into the garbage
205 (defvar *already-maybe-gcing*) ; initialized in cold init
207 ;;; When T, indicates that the dynamic usage has exceeded the value
209 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
211 (defun default-gc-notify-before (notify-stream bytes-in-use)
212 (declare (type stream notify-stream))
213 (format notify-stream
214 "~&; GC is beginning with ~:D bytes in use.~%"
216 (finish-output notify-stream))
217 (defparameter *gc-notify-before* #'default-gc-notify-before
219 "This function bound to this variable is invoked before GC'ing (unless
220 *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
221 current amount of dynamic usage (in bytes). It should notify the
222 user that the system is going to GC.")
224 (defun default-gc-notify-after (notify-stream
228 (declare (type stream notify-stream))
229 (format notify-stream
230 "~&; GC has finished with ~:D bytes in use (~:D bytes freed).~%"
233 (format notify-stream
234 "~&; The new GC trigger is ~:D bytes.~%"
236 (finish-output notify-stream))
237 (defparameter *gc-notify-after* #'default-gc-notify-after
239 "The function bound to this variable is invoked after GC'ing with
240 the value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in
241 bytes) now free, the number of bytes freed by the GC, and the new GC
242 trigger threshold. The function should notify the user that the system
243 has finished GC'ing.")
247 (sb!alien:def-alien-routine collect-garbage sb!c-call:int
248 #!+gencgc (last-gen sb!c-call:int))
251 (sb!alien:def-alien-routine set-auto-gc-trigger sb!c-call:void
252 (dynamic-usage sb!c-call:unsigned-long))
254 (sb!alien:def-alien-routine clear-auto-gc-trigger sb!c-call:void)
256 ;;; This variable contains the function that does the real GC. This is
257 ;;; for low-level GC experimentation. Do not touch it if you do not
258 ;;; know what you are doing.
259 (defvar *internal-gc* #'collect-garbage)
263 ;;; Used to carefully invoke hooks.
264 (eval-when (:compile-toplevel :execute)
265 (sb!xc:defmacro carefully-funcall (function &rest args)
266 `(handler-case (funcall ,function ,@args)
268 (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
271 ;;; SUB-GC decides when and if to do a garbage collection.
272 ;;; The FORCE-P flags controls if a GC should occur even if
273 ;;; the dynamic usage is not greater than *GC-TRIGGER*.
275 ;;; For GENCGC all generations < GEN will be GC'ed.
276 (defun sub-gc (&key force-p (gen 0))
277 (/show0 "entering SUB-GC")
278 (unless *already-maybe-gcing*
279 (let* ((*already-maybe-gcing* t)
280 (start-time (get-internal-run-time))
281 (pre-gc-dyn-usage (dynamic-usage))
282 ;; Currently we only check *SOFT-HEAP-LIMIT* at GC time,
283 ;; not for every allocation. That makes it cheap to do,
284 ;; even if it is a little ugly.
285 (soft-heap-limit-exceeded? (and *soft-heap-limit*
288 (*soft-heap-limit* (if soft-heap-limit-exceeded?
290 *bytes-consed-between-gcs*)
292 (when soft-heap-limit-exceeded?
293 (cerror "Continue with GC."
294 "soft heap limit exceeded (temporary new limit=~D)"
296 (unless (integerp (symbol-value '*bytes-consed-between-gcs*))
297 ;; The noise w/ symbol-value above is to keep the compiler
298 ;; from optimizing the test away because of the type declaim
299 ;; for *bytes-consed-between-gcs*.
301 ;; FIXME: I'm inclined either to get rid of the DECLAIM or to
302 ;; trust it, instead of doing this weird hack. It's not
303 ;; particularly trustable, since (SETF
304 ;; *BYTES-CONSED-BETWEEN-GCS* 'SEVEN) works. But it's also not
305 ;; very nice to have the type of the variable specified in two
306 ;; places which can (and in CMU CL 2.4.8 did, INTEGER vs.
307 ;; INDEX) drift apart. So perhaps we should just add a note to
308 ;; the variable documentation for *BYTES-CONSED-BETWEEN-GCS*
309 ;; that it must be an INDEX, and remove the DECLAIM. Or we
310 ;; could make a SETFable (BYTES-CONSED-BETWEEN-GCS) function
311 ;; and enforce the typing that way. And in fact the SETFable
312 ;; function already exists, so all we need do is make the
313 ;; variable private, and then we can trust the DECLAIM.
314 (warn "The value of *BYTES-CONSED-BETWEEN-GCS*, ~S, is not an ~
315 integer. Resetting it to ~D."
316 *bytes-consed-between-gcs*
317 default-bytes-consed-between-gcs)
318 (setf *bytes-consed-between-gcs* default-bytes-consed-between-gcs))
319 (when (and *gc-trigger* (> pre-gc-dyn-usage *gc-trigger*))
320 (setf *need-to-collect-garbage* t))
322 (and *need-to-collect-garbage* (not *gc-inhibit*)))
323 (when (and (not force-p)
325 (carefully-funcall *gc-inhibit-hook* pre-gc-dyn-usage))
326 (setf *gc-inhibit* t)
327 (return-from sub-gc nil))
328 ;; KLUDGE: Wow, we really mask interrupts all the time we're
329 ;; collecting garbage? That seems like a long time.. -- WHN 19991129
331 ;; FIXME: We probably shouldn't do this evil thing to
332 ;; *STANDARD-OUTPUT* in a binding which is wrapped around
333 ;; calls to user-settable GC hook functions.
334 (let ((*standard-output* *terminal-io*))
335 (when *gc-notify-stream*
336 (if (streamp *gc-notify-stream*)
337 (carefully-funcall *gc-notify-before*
341 "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
342 (dolist (hook *before-gc-hooks*)
343 (carefully-funcall hook))
345 (clear-auto-gc-trigger))
346 #!-gencgc (funcall *internal-gc*)
347 ;; FIXME: This EQ test is pretty gross. Among its other
348 ;; nastinesses, it looks as though it could break if we
349 ;; recompile COLLECT-GARBAGE.
350 #!+gencgc (if (eq *internal-gc* #'collect-garbage)
351 (funcall *internal-gc* gen)
352 (funcall *internal-gc*))
353 (let* ((post-gc-dyn-usage (dynamic-usage))
354 (bytes-freed (- pre-gc-dyn-usage post-gc-dyn-usage)))
355 (/show0 "got (DYNAMIC-USAGE) and BYTES-FREED")
356 (when *last-bytes-in-use*
357 (/show0 "doing *LAST-BYTES-IN-USE* thing")
358 (incf *total-bytes-consed*
359 (- pre-gc-dyn-usage *last-bytes-in-use*))
360 (/show0 "setting *LAST-BYTES-IN-USE*")
361 (setq *last-bytes-in-use* post-gc-dyn-usage))
362 (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
363 (setf *need-to-collect-garbage* nil)
364 (/show0 "calculating NEW-GC-TRIGGER")
365 (let ((new-gc-trigger (+ post-gc-dyn-usage
366 *bytes-consed-between-gcs*)))
367 (/show0 "setting *GC-TRIGGER*")
368 (setf *gc-trigger* new-gc-trigger))
369 (/show0 "calling SET-AUTO-GC-TRIGGER")
370 (set-auto-gc-trigger *gc-trigger*)
371 (dolist (hook *after-gc-hooks*)
372 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
373 ;; FIXME: This hook should be called with the same
374 ;; kind of information as *GC-NOTIFY-AFTER*. In
375 ;; particular, it would be nice for the hook function
376 ;; to be able to adjust *GC-TRIGGER* intelligently to
377 ;; e.g. 108% of total memory usage.
378 (carefully-funcall hook))
379 (when *gc-notify-stream*
380 (if (streamp *gc-notify-stream*)
381 (carefully-funcall *gc-notify-after*
387 "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
388 (scrub-control-stack))) ;XXX again? we did this from C ...
389 (incf *gc-run-time* (- (get-internal-run-time)
391 ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
394 ;;; This routine is called by the allocation miscops to decide whether
395 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
396 ;;; object which must be returned to the caller.
397 (defun maybe-gc (&optional object)
401 ;;; This is the user-advertised garbage collection function.
403 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
404 #!+(and sb-doc gencgc)
405 "Initiate a garbage collection. GEN controls the number of generations
407 #!+(and sb-doc (not gencgc))
408 "Initiate a garbage collection. GEN may be provided for compatibility, but
410 (sub-gc :force-p t :gen (if full 6 gen)))
413 ;;;; auxiliary functions
415 (defun bytes-consed-between-gcs ()
417 "Return the amount of memory that will be allocated before the next garbage
418 collection is initiated. This can be set with SETF."
419 *bytes-consed-between-gcs*)
420 (defun (setf bytes-consed-between-gcs) (val)
421 ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
422 ;; be for a strictly positive number type, e.g.
423 ;; (AND (INTEGER 1) FIXNUM)?
424 (declare (type index val))
425 (let ((old *bytes-consed-between-gcs*))
426 (setf *bytes-consed-between-gcs* val)
428 (setf *gc-trigger* (+ *gc-trigger* (- val old)))
429 (cond ((<= (dynamic-usage) *gc-trigger*)
430 (clear-auto-gc-trigger)
431 (set-auto-gc-trigger *gc-trigger*))
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
453 (defun gc-cold-init-or-reinit ()
455 (if (< *gc-trigger* (dynamic-usage))
457 (set-auto-gc-trigger *gc-trigger*))))