0.7.1.29:
[sbcl.git] / src / code / gc.lisp
1 ;;;; garbage collection and allocation-related code
2
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.
11
12 (in-package "SB!KERNEL")
13 \f
14 ;;;; DYNAMIC-USAGE and friends
15
16 (declaim (special sb!vm:*read-only-space-free-pointer*
17                   sb!vm:*static-space-free-pointer*))
18
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))))))
25
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"))
33
34 #!-sb-fluid
35 (declaim (inline dynamic-usage)) ; to reduce PROFILEd call overhead
36 #!+(or cgc gencgc)
37 (def-c-var-frob dynamic-usage "bytes_allocated")
38 #!-(or cgc 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))))
43
44 (defun static-space-usage ()
45   (- (* sb!vm:*static-space-free-pointer* sb!vm:n-word-bytes)
46      sb!vm:static-space-start))
47
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))
51
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
56                              (sb!sys:sap-int
57                               (sb!c::control-stack-pointer-sap))))
58
59 (defun binding-stack-usage ()
60   (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
61      sb!vm:binding-stack-start))
62 \f
63 ;;;; ROOM
64
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~].~%"
72           *gc-inhibit*))
73
74 (defun room-intermediate-info ()
75   (room-minimal-info)
76   (sb!vm:memory-usage :count-spaces '(:dynamic)
77                       :print-spaces t
78                       :cutoff 0.05s0
79                       :print-summary nil))
80
81 (defun room-maximal-info ()
82   (room-minimal-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))
86
87 (defun room (&optional (verbosity :default))
88   #!+sb-doc
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."
95   (fresh-line)
96   (ecase verbosity
97     ((t)
98      (room-maximal-info))
99     ((nil)
100      (room-minimal-info))
101     (:default
102      (room-intermediate-info)))
103   (values))
104 \f
105 ;;;; GET-BYTES-CONSED
106
107 ;;; the total number of bytes freed so far (including any freeing
108 ;;; which goes on in PURIFY)
109 ;;;
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)
115 (push (lambda ()
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*)
124
125 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
126 (defun get-bytes-consed ()
127   #!+sb-doc
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."
134   (+ (dynamic-usage)
135      *n-bytes-freed-or-purified*))
136 \f
137 ;;;; variables and constants
138
139 ;;; the minimum amount of dynamic space which must be consed before a
140 ;;; GC will be triggered
141 ;;;
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*))
153
154 ;;;; GC hooks
155
156 (defvar *before-gc-hooks* nil ; actually initialized in cold init
157   #!+sb-doc
158   "A list of functions that are called before garbage collection occurs.
159   The functions should take no arguments.")
160
161 (defvar *after-gc-hooks* nil ; actually initialized in cold init
162   #!+sb-doc
163   "A list of functions that are called after garbage collection occurs.
164   The functions should take no arguments.")
165
166 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
167   #!+sb-doc
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
171   respectively.")
172
173 (defvar *gc-run-time* 0
174   #!+sb-doc
175   "the total CPU time spent doing garbage collection (as reported by
176    GET-INTERNAL-RUN-TIME)")
177 (declaim (type index *gc-run-time*))
178
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)
183
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)
189
190 (declaim (type (or index null) *gc-trigger*))
191
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
194 ;;; startup code.
195 #!+x86
196 (defvar sb!vm::*internal-gc-trigger*)
197
198 ;;;; The following specials are used to control when garbage collection
199 ;;;; occurs.
200
201 ;;; When non-NIL, inhibits garbage collection.
202 (defvar *gc-inhibit*) ; initialized in cold init
203
204 ;;; This flag is used to prevent recursive entry into the garbage
205 ;;; collector.
206 (defvar *already-maybe-gcing*) ; initialized in cold init
207
208 ;;; When T, indicates that the dynamic usage has exceeded the value
209 ;;; *GC-TRIGGER*.
210 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
211 \f
212 (defun default-gc-notify-before (notify-stream bytes-in-use)
213   (declare (type stream notify-stream))
214   (format
215    notify-stream
216    "~&; GC is beginning with ~:D bytes in use at internal runtime ~:D.~%"
217    bytes-in-use
218    (get-internal-run-time))
219   (finish-output notify-stream))
220 (defparameter *gc-notify-before* #'default-gc-notify-before
221   #!+sb-doc
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.")
226
227 (defun default-gc-notify-after (notify-stream
228                                 bytes-retained
229                                 bytes-freed
230                                 new-trigger)
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.~%"
235           bytes-retained
236           bytes-freed
237           (get-internal-run-time)
238           new-trigger)
239   (finish-output notify-stream))
240 (defparameter *gc-notify-after* #'default-gc-notify-after
241   #!+sb-doc
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.")
247 \f
248 ;;;; internal GC
249
250 (sb!alien:define-alien-routine collect-garbage sb!alien:int
251   #!+gencgc (last-gen sb!alien:int))
252
253 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
254   (dynamic-usage sb!alien:unsigned-long))
255
256 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien:void)
257
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)
262 \f
263 ;;;; SUB-GC
264
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)
269        (error (cond)
270               (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
271               nil))))
272
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*.
276 ;;;
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
289                                               *soft-heap-limit*)))
290            (*soft-heap-limit* (if soft-heap-limit-exceeded?
291                                   (+ pre-gc-dynamic-usage
292                                      *bytes-consed-between-gcs*)
293                                   *soft-heap-limit*)))
294       (when soft-heap-limit-exceeded?
295         (cerror "Continue with GC."
296                 "soft heap limit exceeded (temporary new limit=~W)"
297                 *soft-heap-limit*))
298       (when (and *gc-trigger* (> pre-gc-dynamic-usage *gc-trigger*))
299         (setf *need-to-collect-garbage* t))
300       (when (or force-p
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
304         (without-interrupts
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*
312                                      *gc-notify-stream*
313                                      pre-gc-dynamic-usage)
314                   (warn
315                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
316             (dolist (hook *before-gc-hooks*)
317               (carefully-funcall hook))
318             (when *gc-trigger*
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
325                    ;; consing.)
326                    (pre-internal-gc-dynamic-usage (dynamic-usage))
327                    (ignore-me
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*
360                     eff-n-bytes-freed)
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*
381                                        *gc-notify-stream*
382                                        post-gc-dynamic-usage
383                                        eff-n-bytes-freed
384                                        *gc-trigger*)
385                     (warn
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)
389                              start-time))))
390   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
391   nil)
392
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)
397   (sub-gc)
398   object)
399
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
404   to garbage collect."
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)))
409
410 \f
411 ;;;; auxiliary functions
412
413 (defun bytes-consed-between-gcs ()
414   #!+sb-doc
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)
425     (when *gc-trigger*
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*))
430             (t
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)
434              (sub-gc)))))
435   val)
436
437 (defun gc-on ()
438   #!+sb-doc
439   "Enable the garbage collector."
440   (setq *gc-inhibit* nil)
441   (when *need-to-collect-garbage*
442     (sub-gc))
443   nil)
444
445 (defun gc-off ()
446   #!+sb-doc
447   "Disable the garbage collector."
448   (setq *gc-inhibit* t)
449   nil)
450 \f
451 ;;;; initialization stuff
452
453 (defun gc-reinit ()
454   (when *gc-trigger*
455     (if (< *gc-trigger* (dynamic-usage))
456         (sub-gc)
457         (set-auto-gc-trigger *gc-trigger*))))