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-downward-not-upward
54 (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
55 (sb!vm:fixnumize sb!vm::*control-stack-start*))
56 #!+stack-grows-downward-not-upward
57 (- (sb!vm:fixnumize sb!vm::*control-stack-end*)
58 (sb!sys:sap-int (sb!c::control-stack-pointer-sap))))
60 (defun binding-stack-usage ()
61 (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
62 (sb!vm:fixnumize sb!vm::*binding-stack-start*)))
66 (defun room-minimal-info ()
67 (format t "Dynamic space usage is: ~10:D bytes.~%" (dynamic-usage))
68 (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
69 (format t "Static space usage is: ~10:D bytes.~%" (static-space-usage))
70 (format t "Control stack usage is: ~10:D bytes.~%" (control-stack-usage))
71 (format t "Binding stack usage is: ~10:D bytes.~%" (binding-stack-usage))
74 "Control and binding stack usage is for the current thread only.~%")
75 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
78 (defun room-intermediate-info ()
80 (sb!vm:memory-usage :count-spaces '(:dynamic)
85 (defun room-maximal-info ()
87 (sb!vm:memory-usage :count-spaces '(:static :dynamic))
88 (sb!vm:instance-usage :dynamic :top-n 10)
89 (sb!vm:instance-usage :static :top-n 10))
91 (defun room (&optional (verbosity :default))
93 "Print to *STANDARD-OUTPUT* information about the state of internal
94 storage and its management. The optional argument controls the
95 verbosity of output. If it is T, ROOM prints out a maximal amount of
96 information. If it is NIL, ROOM prints out a minimal amount of
97 information. If it is :DEFAULT or it is not supplied, ROOM prints out
98 an intermediate amount of information."
106 (room-intermediate-info)))
109 ;;;; GET-BYTES-CONSED
111 ;;; the total number of bytes freed so far (including any freeing
112 ;;; which goes on in PURIFY)
114 ;;; (We save this so that we can calculate the total number of bytes
115 ;;; ever allocated by adding this to the number of bytes currently
116 ;;; allocated and never freed.)
117 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
118 (defvar *n-bytes-freed-or-purified* 0)
120 (setf *n-bytes-freed-or-purified* 0))
121 ;; KLUDGE: It's probably not quite safely right either to do
122 ;; this in *BEFORE-SAVE-INITIALIZATIONS* (since consing, or even
123 ;; worse, something which depended on (GET-BYTES-CONSED), might
124 ;; happen after that) or in *AFTER-SAVE-INITIALIZATIONS*. But
125 ;; it's probably not a big problem, and there seems to be no
126 ;; other obvious time to do it. -- WHN 2001-07-30
127 *after-save-initializations*)
129 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
130 (defun get-bytes-consed ()
132 "Return the number of bytes consed since the program began. Typically
133 this result will be a consed bignum, so if you have an application (e.g.
134 profiling) which can't tolerate the overhead of consing bignums, you'll
135 probably want either to hack in at a lower level (as the code in the
136 SB-PROFILE package does), or to design a more microefficient interface
137 and submit it as a patch."
139 *n-bytes-freed-or-purified*))
141 ;;;; variables and constants
143 ;;; the minimum amount of dynamic space which must be consed before a
144 ;;; GC will be triggered
146 ;;; Unlike CMU CL, we don't export this variable. (There's no need to,
147 ;;; since our BYTES-CONSED-BETWEEN-GCS function is SETFable.)
148 (defvar *bytes-consed-between-gcs*
149 #!+gencgc (* 4 (expt 10 6))
150 ;; Stop-and-copy GC is really really slow when used too often. CSR
151 ;; reported that even on his old 64 Mb SPARC, 20 Mb is much faster
152 ;; than 4 Mb when rebuilding SBCL ca. 0.7.1. For modern machines
153 ;; with >> 128 Mb memory, the optimum could be significantly more
154 ;; than this, but at least 20 Mb should be better than 4 Mb.
155 #!-gencgc (* 20 (expt 10 6)))
156 (declaim (type index *bytes-consed-between-gcs*))
160 (defvar *before-gc-hooks* nil ; actually initialized in cold init
162 "A list of functions that are called before garbage collection occurs.
163 The functions should take no arguments.")
165 (defvar *after-gc-hooks* nil ; actually initialized in cold init
167 "A list of functions that are called after garbage collection occurs.
168 The functions should take no arguments.")
170 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
172 "When non-NIL, this must be a STREAM; and the functions bound to
173 *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
174 STREAM value before and after a garbage collection occurs
177 (defvar *gc-run-time* 0
179 "the total CPU time spent doing garbage collection (as reported by
180 GET-INTERNAL-RUN-TIME)")
181 (declaim (type index *gc-run-time*))
183 ;;;; The following specials are used to control when garbage
184 ;;;; collection occurs.
186 ;;; When the dynamic usage increases beyond this amount, the system
187 ;;; notes that a garbage collection needs to occur by setting
188 ;;; *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
189 ;;; nobody has figured out what it should be yet.
191 ;;; FIXME: *GC-TRIGGER* seems to be denominated in bytes, not words.
192 ;;; And limiting it to INDEX is fairly reasonable in order to avoid
193 ;;; bignum arithmetic on every allocation, and to minimize the need
194 ;;; for thought about weird gotchas of the GC-control mechanism itself
195 ;;; consing as it operates. But as of sbcl-0.7.5, 512Mbytes of memory
196 ;;; costs $54.95 at Fry's in Dallas but cheap consumer 64-bit machines
197 ;;; are still over the horizon, so gratuitously limiting our heap size
198 ;;; to FIXNUM bytes seems fairly stupid. It'd be reasonable to
199 ;;; (1) allow arbitrary UNSIGNED-BYTE values of *GC-TRIGGER*, or
200 ;;; (2) redenominate this variable in words instead of bytes, postponing
201 ;;; the problem to heaps which exceed 50% of the machine's address
203 ;;; (3) redemoninate this variable in CONS-sized two-word units,
204 ;;; allowing it to cover the entire memory space at the price of
205 ;;; possible loss of clarity.
206 ;;; (And whatever is done, it'd also be good to rename the variable so
207 ;;; that it's clear what unit it's denominated in.)
208 (declaim (type (or index null) *gc-trigger*))
209 (defvar *gc-trigger* nil)
211 ;;; When >0, inhibits garbage collection.
212 (defvar *gc-inhibit*) ; initialized in cold init
214 ;;; When T, indicates that a GC should have happened but did not due to
216 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
220 (sb!alien:define-alien-routine collect-garbage sb!alien:int
221 (#!+gencgc last-gen #!-gencgc ignore sb!alien:int))
223 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
224 (dynamic-usage sb!alien:unsigned-long))
226 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien:void)
229 (def-c-var-frob gc-thread-pid "gc_thread_pid")
231 (defun other-thread-collect-garbage (gen)
232 (setf (sb!alien:extern-alien "maybe_gc_pending" (sb!alien:unsigned 32))
234 (sb!unix:unix-kill (gc-thread-pid) :SIGALRM))
236 ;;; This variable contains the function that does the real GC. This is
237 ;;; for low-level GC experimentation. Do not touch it if you do not
238 ;;; know what you are doing.
239 (defvar *internal-gc*
240 #!+sb-thread #'other-thread-collect-garbage
241 #!-sb-thread #'collect-garbage)
246 ;;; This is used to carefully invoke hooks.
247 (eval-when (:compile-toplevel :execute)
248 (sb!xc:defmacro carefully-funcall (function &rest args)
249 `(handler-case (funcall ,function ,@args)
251 (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
254 ;;; SUB-GC does a garbage collection. This is called from three places:
255 ;;; (1) The C runtime will call here when it detects that we've consed
256 ;;; enough to exceed the gc trigger threshold
257 ;;; (2) The user may request a collection using GC, below
258 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
259 ;;; *NEED-TO-COLLECT-GARBAGE* is true
261 ;;; This is different from the behaviour in 0.7 and earlier: it no
262 ;;; longer decides whether to GC based on thresholds. If you call
263 ;;; SUB-GC you will definitely get a GC either now or when the
264 ;;; WITHOUT-GCING is over
266 ;;; For GENCGC all generations < GEN will be GC'ed.
268 (defvar *gc-mutex* (sb!thread:make-mutex :name "GC Mutex"))
270 (defun sub-gc (&key (gen 0))
271 (when (sb!thread::mutex-value *gc-mutex*) (return-from sub-gc nil))
272 (sb!thread:with-mutex (*gc-mutex* :wait-p nil)
273 (let* ((start-time (get-internal-run-time)))
274 (setf *need-to-collect-garbage* t)
275 (when (zerop *gc-inhibit*)
277 (dolist (hook *before-gc-hooks*) (carefully-funcall hook))
279 (clear-auto-gc-trigger))
280 (let* ((pre-internal-gc-dynamic-usage (dynamic-usage))
281 (ignore-me (funcall *internal-gc* gen))
282 (post-gc-dynamic-usage (dynamic-usage))
283 (n-bytes-freed (- pre-internal-gc-dynamic-usage
284 post-gc-dynamic-usage))
285 ;; the raw N-BYTES-FREED from GENCGC can sometimes be
286 ;; substantially negative (e.g. -5872). This is
287 ;; probably due to fluctuating inefficiency in the way
288 ;; that the GENCGC packs things into page boundaries.
289 ;; We bump the raw result up to 0: the space is
290 ;; allocated even if unusable, so should be counted
291 ;; for deciding when we've allocated enough to GC
292 ;; next. ("Man isn't a rational animal, he's a
293 ;; rationalizing animal.":-) -- WHN 2001-06-23)
294 (eff-n-bytes-freed (max 0 n-bytes-freed)))
295 (declare (ignore ignore-me))
296 (incf *n-bytes-freed-or-purified* eff-n-bytes-freed)
297 (setf *need-to-collect-garbage* nil)
298 (setf *gc-trigger* (+ post-gc-dynamic-usage
299 *bytes-consed-between-gcs*))
300 (set-auto-gc-trigger *gc-trigger*)
301 (dolist (hook *after-gc-hooks*)
302 (carefully-funcall hook))))
303 (scrub-control-stack)) ;XXX again? we did this from C ...
304 (incf *gc-run-time* (- (get-internal-run-time) start-time))))
310 ;;; This is the user-advertised garbage collection function.
311 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
312 #!+(and sb-doc gencgc)
313 "Initiate a garbage collection. GEN controls the number of generations
315 #!+(and sb-doc (not gencgc))
316 "Initiate a garbage collection. GEN may be provided for compatibility with
317 generational garbage collectors, but is ignored in this implementation."
318 (sub-gc :gen (if full 6 gen)))
321 ;;;; auxiliary functions
323 (defun bytes-consed-between-gcs ()
325 "Return the amount of memory that will be allocated before the next garbage
326 collection is initiated. This can be set with SETF."
327 *bytes-consed-between-gcs*)
328 (defun (setf bytes-consed-between-gcs) (val)
329 ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
330 ;; be for a strictly positive number type, e.g.
331 ;; (AND (INTEGER 1) FIXNUM)?
332 (declare (type index val))
333 (let ((old *bytes-consed-between-gcs*))
334 (setf *bytes-consed-between-gcs* val)
336 (setf *gc-trigger* (+ *gc-trigger* (- val old)))
337 (cond ((<= (dynamic-usage) *gc-trigger*)
338 (clear-auto-gc-trigger)
339 (set-auto-gc-trigger *gc-trigger*))
341 ;; FIXME: If SCRUB-CONTROL-STACK is required here, why
342 ;; isn't it built into SUB-GC? And *is* it required here?
343 (sb!sys:scrub-control-stack)
349 "Enable the garbage collector."
350 (setq *gc-inhibit* 0)
351 (when *need-to-collect-garbage*
357 "Disable the garbage collector."
358 (setq *gc-inhibit* 1)
361 ;;;; initialization stuff
365 (if (< *gc-trigger* (dynamic-usage))
367 (set-auto-gc-trigger *gc-trigger*))))