0.pre8.4
[sbcl/lichteblau.git] / src / code / gc.lisp
blob2389750c02cc62a31c51ef7fac13e766308eb954
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 (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)
21 `(progn
22 #!-sb-fluid (declaim (inline ,lisp-fun))
23 (defun ,lisp-fun ()
24 (sb!alien:extern-alien ,c-var-name (sb!alien:unsigned 32))))))
26 #!-gencgc
27 (progn
28 ;; This is called once per PROFILEd function call, so it's worth a
29 ;; little possible space cost to reduce its time cost.
30 #!-sb-fluid
31 (declaim (inline current-dynamic-space-start))
32 (def-c-var-frob current-dynamic-space-start "current_dynamic_space"))
34 #!-sb-fluid
35 (declaim (inline dynamic-usage)) ; to reduce PROFILEd call overhead
36 #!+gencgc
37 (def-c-var-frob dynamic-usage "bytes_allocated")
38 #!-gencgc
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:control-stack-start)
56 #!+stack-grows-downward-not-upward
57 (- 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:binding-stack-start))
64 ;;;; ROOM
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))
72 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
73 (> *gc-inhibit* 0)))
75 (defun room-intermediate-info ()
76 (room-minimal-info)
77 (sb!vm:memory-usage :count-spaces '(:dynamic)
78 :print-spaces t
79 :cutoff 0.05f0
80 :print-summary nil))
82 (defun room-maximal-info ()
83 (room-minimal-info)
84 (sb!vm:memory-usage :count-spaces '(:static :dynamic))
85 (sb!vm:instance-usage :dynamic :top-n 10)
86 (sb!vm:instance-usage :static :top-n 10))
88 (defun room (&optional (verbosity :default))
89 #!+sb-doc
90 "Print to *STANDARD-OUTPUT* information about the state of internal
91 storage and its management. The optional argument controls the
92 verbosity of output. If it is T, ROOM prints out a maximal amount of
93 information. If it is NIL, ROOM prints out a minimal amount of
94 information. If it is :DEFAULT or it is not supplied, ROOM prints out
95 an intermediate amount of information."
96 (fresh-line)
97 (ecase verbosity
98 ((t)
99 (room-maximal-info))
100 ((nil)
101 (room-minimal-info))
102 (:default
103 (room-intermediate-info)))
104 (values))
106 ;;;; GET-BYTES-CONSED
108 ;;; the total number of bytes freed so far (including any freeing
109 ;;; which goes on in PURIFY)
111 ;;; (We save this so that we can calculate the total number of bytes
112 ;;; ever allocated by adding this to the number of bytes currently
113 ;;; allocated and never freed.)
114 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
115 (defvar *n-bytes-freed-or-purified* 0)
116 (push (lambda ()
117 (setf *n-bytes-freed-or-purified* 0))
118 ;; KLUDGE: It's probably not quite safely right either to do
119 ;; this in *BEFORE-SAVE-INITIALIZATIONS* (since consing, or even
120 ;; worse, something which depended on (GET-BYTES-CONSED), might
121 ;; happen after that) or in *AFTER-SAVE-INITIALIZATIONS*. But
122 ;; it's probably not a big problem, and there seems to be no
123 ;; other obvious time to do it. -- WHN 2001-07-30
124 *after-save-initializations*)
126 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
127 (defun get-bytes-consed ()
128 #!+sb-doc
129 "Return the number of bytes consed since the program began. Typically
130 this result will be a consed bignum, so if you have an application (e.g.
131 profiling) which can't tolerate the overhead of consing bignums, you'll
132 probably want either to hack in at a lower level (as the code in the
133 SB-PROFILE package does), or to design a more microefficient interface
134 and submit it as a patch."
135 (+ (dynamic-usage)
136 *n-bytes-freed-or-purified*))
138 ;;;; variables and constants
140 ;;; the minimum amount of dynamic space which must be consed before a
141 ;;; GC will be triggered
143 ;;; Unlike CMU CL, we don't export this variable. (There's no need to,
144 ;;; since our BYTES-CONSED-BETWEEN-GCS function is SETFable.)
145 (defvar *bytes-consed-between-gcs*
146 #!+gencgc (* 4 (expt 10 6))
147 ;; Stop-and-copy GC is really really slow when used too often. CSR
148 ;; reported that even on his old 64 Mb SPARC, 20 Mb is much faster
149 ;; than 4 Mb when rebuilding SBCL ca. 0.7.1. For modern machines
150 ;; with >> 128 Mb memory, the optimum could be significantly more
151 ;; than this, but at least 20 Mb should be better than 4 Mb.
152 #!-gencgc (* 20 (expt 10 6)))
153 (declaim (type index *bytes-consed-between-gcs*))
155 ;;;; GC hooks
157 (defvar *before-gc-hooks* nil ; actually initialized in cold init
158 #!+sb-doc
159 "A list of functions that are called before garbage collection occurs.
160 The functions should take no arguments.")
162 (defvar *after-gc-hooks* nil ; actually initialized in cold init
163 #!+sb-doc
164 "A list of functions that are called after garbage collection occurs.
165 The functions should take no arguments.")
167 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
168 #!+sb-doc
169 "When non-NIL, this must be a STREAM; and the functions bound to
170 *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
171 STREAM value before and after a garbage collection occurs
172 respectively.")
174 (defvar *gc-run-time* 0
175 #!+sb-doc
176 "the total CPU time spent doing garbage collection (as reported by
177 GET-INTERNAL-RUN-TIME)")
178 (declaim (type index *gc-run-time*))
180 ;;; a limit to help catch programs which allocate too much memory,
181 ;;; since a hard heap overflow is so hard to recover from
183 ;;; FIXME: Like *GC-TRIGGER*, this variable (1) should probably be
184 ;;; denominated in a larger unit than bytes and (2) should probably be
185 ;;; renamed so that it's clear from the name what unit it's
186 ;;; denominated in.
187 (declaim (type (or unsigned-byte null) *soft-heap-limit*))
188 (defvar *soft-heap-limit*
189 ;; As long as *GC-TRIGGER* is DECLAIMed as INDEX, we know that
190 ;; MOST-POSITIVE-FIXNUM is a hard limit on how much memory can be
191 ;; allocated. (Not necessarily *the* hard limit, which is fairly
192 ;; likely something like a Unix per-process limit that we don't know
193 ;; about, but a hard limit anyway.) And this gives us a reasonable
194 ;; conservative default for the soft limit...
195 (- most-positive-fixnum
196 *bytes-consed-between-gcs*))
198 ;;;; The following specials are used to control when garbage
199 ;;;; collection occurs.
201 ;;; When the dynamic usage increases beyond this amount, the system
202 ;;; notes that a garbage collection needs to occur by setting
203 ;;; *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
204 ;;; nobody has figured out what it should be yet.
206 ;;; FIXME: *GC-TRIGGER* seems to be denominated in bytes, not words.
207 ;;; And limiting it to INDEX is fairly reasonable in order to avoid
208 ;;; bignum arithmetic on every allocation, and to minimize the need
209 ;;; for thought about weird gotchas of the GC-control mechanism itself
210 ;;; consing as it operates. But as of sbcl-0.7.5, 512Mbytes of memory
211 ;;; costs $54.95 at Fry's in Dallas but cheap consumer 64-bit machines
212 ;;; are still over the horizon, so gratuitously limiting our heap size
213 ;;; to FIXNUM bytes seems fairly stupid. It'd be reasonable to
214 ;;; (1) allow arbitrary UNSIGNED-BYTE values of *GC-TRIGGER*, or
215 ;;; (2) redenominate this variable in words instead of bytes, postponing
216 ;;; the problem to heaps which exceed 50% of the machine's address
217 ;;; space, or even
218 ;;; (3) redemoninate this variable in CONS-sized two-word units,
219 ;;; allowing it to cover the entire memory space at the price of
220 ;;; possible loss of clarity.
221 ;;; (And whatever is done, it'd also be good to rename the variable so
222 ;;; that it's clear what unit it's denominated in.)
223 (declaim (type (or index null) *gc-trigger*))
224 (defvar *gc-trigger* nil)
226 ;;; When >0, inhibits garbage collection.
227 (defvar *gc-inhibit*) ; initialized in cold init
229 ;;; This flag is used to prevent recursive entry into the garbage
230 ;;; collector.
231 (defvar *already-maybe-gcing*) ; initialized in cold init
233 ;;; When T, indicates that the dynamic usage has exceeded the value
234 ;;; *GC-TRIGGER*.
235 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
237 (defun default-gc-notify-before (notify-stream bytes-in-use)
238 (declare (type stream notify-stream))
239 (format
240 notify-stream
241 "~&; GC is beginning with ~:D bytes in use at internal runtime ~:D.~%"
242 bytes-in-use
243 (get-internal-run-time))
244 (finish-output notify-stream))
245 (defparameter *gc-notify-before* #'default-gc-notify-before
246 #!+sb-doc
247 "The function bound to this variable is invoked before GC'ing (unless
248 *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
249 current amount of dynamic usage (in bytes). It should notify the
250 user that the system is going to GC.")
252 (defun default-gc-notify-after (notify-stream
253 bytes-retained
254 bytes-freed
255 new-trigger)
256 (declare (type stream notify-stream))
257 (format notify-stream
258 "~&; GC has finished with ~:D bytes in use (~:D bytes freed)~@
259 ; at internal runtime ~:D. The new GC trigger is ~:D bytes.~%"
260 bytes-retained
261 bytes-freed
262 (get-internal-run-time)
263 new-trigger)
264 (finish-output notify-stream))
265 (defparameter *gc-notify-after* #'default-gc-notify-after
266 #!+sb-doc
267 "The function bound to this variable is invoked after GC'ing with the
268 value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in bytes) now
269 free, the number of bytes freed by the GC, and the new GC trigger
270 threshold; or if *GC-NOTIFY-STREAM* is NIL, it's not invoked. The
271 function should notify the user that the system has finished GC'ing.")
273 ;;;; internal GC
275 (sb!alien:define-alien-routine collect-garbage sb!alien:int
276 (#!+gencgc last-gen #!-gencgc ignore sb!alien:int))
278 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
279 (dynamic-usage sb!alien:unsigned-long))
281 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien:void)
283 ;;; This variable contains the function that does the real GC. This is
284 ;;; for low-level GC experimentation. Do not touch it if you do not
285 ;;; know what you are doing.
286 (defvar *internal-gc* #'collect-garbage)
288 ;;;; SUB-GC
290 ;;; This is used to carefully invoke hooks.
291 (eval-when (:compile-toplevel :execute)
292 (sb!xc:defmacro carefully-funcall (function &rest args)
293 `(handler-case (funcall ,function ,@args)
294 (error (cond)
295 (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
296 nil))))
298 ;;; SUB-GC decides when and if to do a garbage collection. The FORCE-P
299 ;;; flags controls whether a GC should occur even if the dynamic usage
300 ;;; is not greater than *GC-TRIGGER*.
302 ;;; For GENCGC all generations < GEN will be GC'ed.
304 ;;; XXX need (1) some kind of locking to ensure that only one thread
305 ;;; at a time is trying to GC, (2) to look at all these specials and
306 ;;; work out how much of this "do we really need to GC now?" stuff is
307 ;;; actually necessary: I think we actually end up GCing every time we
308 ;;; hit this code
310 (defun sub-gc (&key force-p (gen 0))
311 (/show0 "entering SUB-GC")
312 (unless *already-maybe-gcing*
313 (let* ((*already-maybe-gcing* t)
314 (start-time (get-internal-run-time))
315 (pre-gc-dynamic-usage (dynamic-usage))
316 ;; Currently we only check *SOFT-HEAP-LIMIT* at GC time,
317 ;; not for every allocation. That makes it cheap to do,
318 ;; even if it is a little ugly.
319 (soft-heap-limit-exceeded? (and *soft-heap-limit*
320 (> pre-gc-dynamic-usage
321 *soft-heap-limit*)))
322 (*soft-heap-limit* (if soft-heap-limit-exceeded?
323 (+ pre-gc-dynamic-usage
324 *bytes-consed-between-gcs*)
325 *soft-heap-limit*)))
326 (when soft-heap-limit-exceeded?
327 (cerror "Continue with GC."
328 "soft heap limit exceeded (temporary new limit=~W)"
329 *soft-heap-limit*))
330 (when (and *gc-trigger* (> pre-gc-dynamic-usage *gc-trigger*))
331 (setf *need-to-collect-garbage* t))
332 (when (or force-p
333 (and *need-to-collect-garbage* (zerop *gc-inhibit*)))
334 ;; KLUDGE: Wow, we really mask interrupts all the time we're
335 ;; collecting garbage? That seems like a long time.. -- WHN 19991129
336 (without-interrupts
337 ;; FIXME: We probably shouldn't do this evil thing to
338 ;; *STANDARD-OUTPUT* in a binding which is wrapped around
339 ;; calls to user-settable GC hook functions.
340 (let ((*standard-output* *terminal-io*))
341 (when *gc-notify-stream*
342 (if (streamp *gc-notify-stream*)
343 (carefully-funcall *gc-notify-before*
344 *gc-notify-stream*
345 pre-gc-dynamic-usage)
346 (warn
347 "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
348 (dolist (hook *before-gc-hooks*)
349 (carefully-funcall hook))
350 (when *gc-trigger*
351 (clear-auto-gc-trigger))
352 (let* (;; We do DYNAMIC-USAGE once more here in order to
353 ;; get a more accurate measurement of the space
354 ;; actually freed, since the messing around, e.g.
355 ;; GC-notify stuff, since the DYNAMIC-USAGE which
356 ;; triggered GC could've done a fair amount of
357 ;; consing.)
358 (pre-internal-gc-dynamic-usage (dynamic-usage))
359 (ignore-me (funcall *internal-gc* gen))
360 (post-gc-dynamic-usage (dynamic-usage))
361 (n-bytes-freed (- pre-internal-gc-dynamic-usage
362 post-gc-dynamic-usage))
363 ;; In sbcl-0.6.12.39, the raw N-BYTES-FREED from
364 ;; GENCGC could sometimes be substantially negative
365 ;; (e.g. -5872). I haven't looked into what causes
366 ;; that, but I suspect it has to do with
367 ;; fluctuating inefficiency in the way that the
368 ;; GENCGC packs things into page boundaries.
369 ;; Bumping the raw result up to 0 is a little ugly,
370 ;; but shouldn't be a problem, and it's even
371 ;; possible to sort of justify it: the packing
372 ;; inefficiency which has caused (DYNAMIC-USAGE) to
373 ;; grow is effectively consing, or at least
374 ;; overhead of consing, so it's sort of correct to
375 ;; add it to the running total of consing. ("Man
376 ;; isn't a rational animal, he's a rationalizing
377 ;; animal.":-) -- WHN 2001-06-23
378 (eff-n-bytes-freed (max 0 n-bytes-freed)))
379 (declare (ignore ignore-me))
380 (/show0 "got (DYNAMIC-USAGE) and EFF-N-BYTES-FREED")
381 (incf *n-bytes-freed-or-purified*
382 eff-n-bytes-freed)
383 (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
384 (setf *need-to-collect-garbage* nil)
385 (/show0 "calculating NEW-GC-TRIGGER")
386 (let ((new-gc-trigger (+ post-gc-dynamic-usage
387 *bytes-consed-between-gcs*)))
388 (/show0 "setting *GC-TRIGGER*")
389 (setf *gc-trigger* new-gc-trigger))
390 (/show0 "calling SET-AUTO-GC-TRIGGER")
391 (set-auto-gc-trigger *gc-trigger*)
392 (dolist (hook *after-gc-hooks*)
393 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
394 ;; FIXME: This hook should be called with the same
395 ;; kind of information as *GC-NOTIFY-AFTER*. In
396 ;; particular, it would be nice for the hook function
397 ;; to be able to adjust *GC-TRIGGER* intelligently to
398 ;; e.g. 108% of total memory usage.
399 (carefully-funcall hook))
400 (when *gc-notify-stream*
401 (if (streamp *gc-notify-stream*)
402 (carefully-funcall *gc-notify-after*
403 *gc-notify-stream*
404 post-gc-dynamic-usage
405 eff-n-bytes-freed
406 *gc-trigger*)
407 (warn
408 "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
409 (scrub-control-stack))) ;XXX again? we did this from C ...
410 (incf *gc-run-time* (- (get-internal-run-time)
411 start-time))))
412 ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
413 nil)
415 ;;; This routine is called by the allocation miscops to decide whether
416 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
417 ;;; object which must be returned to the caller.
418 (defun maybe-gc (&optional object)
419 (sub-gc)
420 object)
422 ;;; This is the user-advertised garbage collection function.
423 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
424 #!+(and sb-doc gencgc)
425 "Initiate a garbage collection. GEN controls the number of generations
426 to garbage collect."
427 #!+(and sb-doc (not gencgc))
428 "Initiate a garbage collection. GEN may be provided for compatibility with
429 generational garbage collectors, but is ignored in this implementation."
430 (sub-gc :force-p t :gen (if full 6 gen)))
433 ;;;; auxiliary functions
435 (defun bytes-consed-between-gcs ()
436 #!+sb-doc
437 "Return the amount of memory that will be allocated before the next garbage
438 collection is initiated. This can be set with SETF."
439 *bytes-consed-between-gcs*)
440 (defun (setf bytes-consed-between-gcs) (val)
441 ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
442 ;; be for a strictly positive number type, e.g.
443 ;; (AND (INTEGER 1) FIXNUM)?
444 (declare (type index val))
445 (let ((old *bytes-consed-between-gcs*))
446 (setf *bytes-consed-between-gcs* val)
447 (when *gc-trigger*
448 (setf *gc-trigger* (+ *gc-trigger* (- val old)))
449 (cond ((<= (dynamic-usage) *gc-trigger*)
450 (clear-auto-gc-trigger)
451 (set-auto-gc-trigger *gc-trigger*))
453 ;; FIXME: If SCRUB-CONTROL-STACK is required here, why
454 ;; isn't it built into SUB-GC? And *is* it required here?
455 (sb!sys:scrub-control-stack)
456 (sub-gc)))))
457 val)
459 (defun gc-on ()
460 #!+sb-doc
461 "Enable the garbage collector."
462 (setq *gc-inhibit* 0)
463 (when *need-to-collect-garbage*
464 (sub-gc))
465 nil)
467 (defun gc-off ()
468 #!+sb-doc
469 "Disable the garbage collector."
470 (setq *gc-inhibit* 1)
471 nil)
473 ;;;; initialization stuff
475 (defun gc-reinit ()
476 (when *gc-trigger*
477 (if (< *gc-trigger* (dynamic-usage))
478 (sub-gc)
479 (set-auto-gc-trigger *gc-trigger*))))