0.6.12.28:
[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 #!+(or cgc gencgc) (progn
27 #!-sb-fluid (declaim (inline dynamic-usage))
28 (def-c-var-frob dynamic-usage "bytes_allocated"))
29
30 #!-(or cgc gencgc)
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))))
35
36 #!-gencgc (progn
37 #!-sb-fluid (declaim (inline current-dynamic-space-start))
38 (def-c-var-frob current-dynamic-space-start "current_dynamic_space"))
39
40 (defun static-space-usage ()
41   (- (* sb!vm:*static-space-free-pointer* sb!vm:word-bytes)
42      sb!vm:static-space-start))
43
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))
47
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))))
53
54 (defun binding-stack-usage ()
55   (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
56      sb!vm:binding-stack-start))
57 \f
58 ;;;; ROOM
59
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~].~%"
67           *gc-inhibit*))
68
69 (defun room-intermediate-info ()
70   (room-minimal-info)
71   (sb!vm:memory-usage :count-spaces '(:dynamic)
72                       :print-spaces t
73                       :cutoff 0.05s0
74                       :print-summary nil))
75
76 (defun room-maximal-info ()
77   (room-minimal-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))
81
82 (defun room (&optional (verbosity :default))
83   #!+sb-doc
84   "Prints to *STANDARD-OUTPUT* information about the state of internal
85   storage and its management. The optional argument controls the
86   verbosity of ROOM. 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. See also VM:MEMORY-USAGE and
90   VM:INSTANCE-USAGE for finer report control."
91   (fresh-line)
92   (ecase verbosity
93     ((t)
94      (room-maximal-info))
95     ((nil)
96      (room-minimal-info))
97     (:default
98      (room-intermediate-info)))
99   (values))
100 \f
101 ;;;; GET-BYTES-CONSED
102
103 ;;; internal state
104 (defvar *last-bytes-in-use* nil)
105 (defvar *total-bytes-consed* 0)
106 (declaim (type (or index null) *last-bytes-in-use*))
107 (declaim (type unsigned-byte *total-bytes-consed*))
108
109 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
110 (defun get-bytes-consed ()
111   #!+sb-doc
112   "Return the number of bytes consed since the first time this function
113   was called. The first time it is called, it returns zero."
114   (declare (optimize (speed 3) (safety 0)))
115   (cond ((null *last-bytes-in-use*)
116          (setq *last-bytes-in-use* (dynamic-usage))
117          (setq *total-bytes-consed* 0))
118         (t
119          (let ((bytes (dynamic-usage)))
120            (incf *total-bytes-consed*
121                  (the index (- bytes *last-bytes-in-use*)))
122            (setq *last-bytes-in-use* bytes))))
123   ;; FIXME: We should really use something like PCOUNTER to make this
124   ;; hold reliably.
125   (aver (not (minusp *total-bytes-consed*)))
126   *total-bytes-consed*)
127 \f
128 ;;;; variables and constants
129
130 ;;; the default value of *BYTES-CONSED-BETWEEN-GCS* and *GC-TRIGGER*
131 (defconstant default-bytes-consed-between-gcs 2000000)
132
133 ;;; the minimum amount of dynamic space which must be consed before a
134 ;;; GC will be triggered
135 ;;;
136 ;;; Unlike CMU CL, we don't export this variable. (There's no need to,
137 ;;; since the BYTES-CONSED-BETWEEN-GCS function is SETFable.)
138 (defvar *bytes-consed-between-gcs* default-bytes-consed-between-gcs)
139 (declaim (type index *bytes-consed-between-gcs*))
140
141 ;;;; GC hooks
142
143 ;;; These variables are a list of functions which are run before and
144 ;;; after garbage collection occurs.
145 (defvar *before-gc-hooks* nil ; actually initialized in cold init
146   #!+sb-doc
147   "A list of functions that are called before garbage collection occurs.
148   The functions should take no arguments.")
149 (defvar *after-gc-hooks* nil ; actually initialized in cold init
150   #!+sb-doc
151   "A list of functions that are called after garbage collection occurs.
152   The functions should take no arguments.")
153
154 ;;; This hook is invoked whenever SUB-GC intends to GC (unless the GC
155 ;;; was explicitly forced by calling SB!EXT:GC). If the hook function
156 ;;; returns NIL then the GC procedes; otherwise, the GC is inhibited and
157 ;;; *GC-INHIBIT* and *NEED-TO-COLLECT-GARBAGE* are left bound to T.
158 ;;; Presumably someone will call GC-ON later to collect the garbage.
159 (defvar *gc-inhibit-hook* nil
160   #!+sb-doc
161   "Should be bound to a function or NIL. If it is a function, this
162   function should take one argument, the current amount of dynamic
163   usage. The function should return NIL if garbage collection should
164   continue and non-NIL if it should be inhibited. Use with caution.")
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 ;;; Internal trigger. When the dynamic usage increases beyond this
185 ;;; amount, the system notes that a garbage collection needs to occur by
186 ;;; setting *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 notify-stream
215           "~&; GC is beginning with ~:D bytes in use.~%"
216           bytes-in-use)
217   (finish-output notify-stream))
218 (defparameter *gc-notify-before* #'default-gc-notify-before
219   #!+sb-doc
220   "This function bound to this variable is invoked before GC'ing (unless
221   *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
222   current amount of dynamic usage (in bytes). It should notify the
223   user that the system is going to GC.")
224
225 (defun default-gc-notify-after (notify-stream
226                                 bytes-retained
227                                 bytes-freed
228                                 new-trigger)
229   (declare (type stream notify-stream))
230   (format notify-stream
231           "~&; GC has finished with ~:D bytes in use (~:D bytes freed).~%"
232           bytes-retained
233           bytes-freed)
234   (format notify-stream
235           "~&; The new GC trigger is ~:D bytes.~%"
236           new-trigger)
237   (finish-output notify-stream))
238 (defparameter *gc-notify-after* #'default-gc-notify-after
239   #!+sb-doc
240   "The function bound to this variable is invoked after GC'ing with
241 the value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in
242 bytes) now free, the number of bytes freed by the GC, and the new GC
243 trigger threshold. The function should notify the user that the system
244 has finished GC'ing.")
245 \f
246 ;;;; internal GC
247
248 (sb!alien:def-alien-routine collect-garbage sb!c-call:int
249   #!+gencgc (last-gen sb!c-call:int))
250
251
252 (sb!alien:def-alien-routine set-auto-gc-trigger sb!c-call:void
253   (dynamic-usage sb!c-call:unsigned-long))
254
255 (sb!alien:def-alien-routine clear-auto-gc-trigger sb!c-call:void)
256
257 ;;; This variable contains the function that does the real GC. This is
258 ;;; for low-level GC experimentation. Do not touch it if you do not
259 ;;; know what you are doing.
260 (defvar *internal-gc* #'collect-garbage)
261 \f
262 ;;;; SUB-GC
263
264 ;;; Used to carefully invoke hooks.
265 (eval-when (:compile-toplevel :execute)
266   (sb!xc:defmacro carefully-funcall (function &rest args)
267     `(handler-case (funcall ,function ,@args)
268        (error (cond)
269               (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
270               nil))))
271
272 ;;; SUB-GC decides when and if to do a garbage collection.
273 ;;; The FORCE-P flags controls if a GC should occur even if
274 ;;; the dynamic usage is not greater than *GC-TRIGGER*.
275 ;;;
276 ;;; For GENCGC all generations < GEN will be GC'ed.
277 (defun sub-gc (&key  force-p (gen 0))
278   (/show0 "entering SUB-GC")
279   (unless *already-maybe-gcing*
280     (let* ((*already-maybe-gcing* t)
281            (start-time (get-internal-run-time))
282            (pre-gc-dyn-usage (dynamic-usage))
283            ;; Currently we only check *SOFT-HEAP-LIMIT* at GC time,
284            ;; not for every allocation. That makes it cheap to do,
285            ;; even if it is a little ugly.
286            (soft-heap-limit-exceeded? (and *soft-heap-limit*
287                                            (> pre-gc-dyn-usage
288                                               *soft-heap-limit*)))
289            (*soft-heap-limit* (if soft-heap-limit-exceeded?
290                                   (+ pre-gc-dyn-usage
291                                      *bytes-consed-between-gcs*)
292                                   *soft-heap-limit*)))
293       (when soft-heap-limit-exceeded?
294         (cerror "Continue with GC."
295                 "soft heap limit exceeded (temporary new limit=~D)"
296                 *soft-heap-limit*))
297       (unless (integerp (symbol-value '*bytes-consed-between-gcs*))
298         ;; The noise w/ symbol-value above is to keep the compiler
299         ;; from optimizing the test away because of the type declaim
300         ;; for *bytes-consed-between-gcs*.
301         ;;
302         ;; FIXME: I'm inclined either to get rid of the DECLAIM or to
303         ;; trust it, instead of doing this weird hack. It's not
304         ;; particularly trustable, since (SETF
305         ;; *BYTES-CONSED-BETWEEN-GCS* 'SEVEN) works. But it's also not
306         ;; very nice to have the type of the variable specified in two
307         ;; places which can (and in CMU CL 2.4.8 did, INTEGER vs.
308         ;; INDEX) drift apart. So perhaps we should just add a note to
309         ;; the variable documentation for *BYTES-CONSED-BETWEEN-GCS*
310         ;; that it must be an INDEX, and remove the DECLAIM. Or we
311         ;; could make a SETFable (BYTES-CONSED-BETWEEN-GCS) function
312         ;; and enforce the typing that way. And in fact the SETFable
313         ;; function already exists, so all we need do is make the
314         ;; variable private, and then we can trust the DECLAIM.
315         (warn "The value of *BYTES-CONSED-BETWEEN-GCS*, ~S, is not an ~
316                integer. Resetting it to ~D."
317               *bytes-consed-between-gcs*
318                default-bytes-consed-between-gcs)
319         (setf *bytes-consed-between-gcs* default-bytes-consed-between-gcs))
320       (when (and *gc-trigger* (> pre-gc-dyn-usage *gc-trigger*))
321         (setf *need-to-collect-garbage* t))
322       (when (or force-p
323                 (and *need-to-collect-garbage* (not *gc-inhibit*)))
324         (when (and (not force-p)
325                    *gc-inhibit-hook*
326                    (carefully-funcall *gc-inhibit-hook* pre-gc-dyn-usage))
327           (setf *gc-inhibit* t)
328           (return-from sub-gc nil))
329         ;; KLUDGE: Wow, we really mask interrupts all the time we're
330         ;; collecting garbage? That seems like a long time.. -- WHN 19991129
331         (without-interrupts
332          ;; FIXME: We probably shouldn't do this evil thing to
333          ;; *STANDARD-OUTPUT* in a binding which is wrapped around
334          ;; calls to user-settable GC hook functions.
335           (let ((*standard-output* *terminal-io*))
336             (when *gc-notify-stream*
337               (if (streamp *gc-notify-stream*)
338                   (carefully-funcall *gc-notify-before*
339                                      *gc-notify-stream*
340                                      pre-gc-dyn-usage)
341                   (warn
342                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
343             (dolist (hook *before-gc-hooks*)
344               (carefully-funcall hook))
345             (when *gc-trigger*
346               (clear-auto-gc-trigger))
347             #!-gencgc (funcall *internal-gc*)
348             ;; FIXME: This EQ test is pretty gross. Among its other
349             ;; nastinesses, it looks as though it could break if we
350             ;; recompile COLLECT-GARBAGE.
351             #!+gencgc (if (eq *internal-gc* #'collect-garbage)
352                           (funcall *internal-gc* gen)
353                           (funcall *internal-gc*))
354             (let* ((post-gc-dyn-usage (dynamic-usage))
355                    (bytes-freed (- pre-gc-dyn-usage post-gc-dyn-usage)))
356               (/show0 "got (DYNAMIC-USAGE) and BYTES-FREED")
357               (when *last-bytes-in-use*
358                 (/show0 "doing *LAST-BYTES-IN-USE* thing")
359                 (incf *total-bytes-consed*
360                       (- pre-gc-dyn-usage *last-bytes-in-use*))
361                 (/show0 "setting *LAST-BYTES-IN-USE*")
362                 (setq *last-bytes-in-use* post-gc-dyn-usage))
363               (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
364               (setf *need-to-collect-garbage* nil)
365               (/show0 "calculating NEW-GC-TRIGGER")
366               (let ((new-gc-trigger (+ post-gc-dyn-usage
367                                        *bytes-consed-between-gcs*)))
368                 (/show0 "setting *GC-TRIGGER*")
369                 (setf *gc-trigger* new-gc-trigger))
370               (/show0 "calling SET-AUTO-GC-TRIGGER")
371               (set-auto-gc-trigger *gc-trigger*)
372               (dolist (hook *after-gc-hooks*)
373                 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
374                 ;; FIXME: This hook should be called with the same
375                 ;; kind of information as *GC-NOTIFY-AFTER*. In
376                 ;; particular, it would be nice for the hook function
377                 ;; to be able to adjust *GC-TRIGGER* intelligently to
378                 ;; e.g. 108% of total memory usage.
379                 (carefully-funcall hook))
380               (when *gc-notify-stream*
381                 (if (streamp *gc-notify-stream*)
382                     (carefully-funcall *gc-notify-after*
383                                        *gc-notify-stream*
384                                        post-gc-dyn-usage
385                                        bytes-freed
386                                        *gc-trigger*)
387                     (warn
388                      "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
389           (scrub-control-stack)))       ;XXX again?  we did this from C ...
390       (incf *gc-run-time* (- (get-internal-run-time)
391                              start-time))))
392   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
393   nil)
394
395 ;;; This routine is called by the allocation miscops to decide whether
396 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
397 ;;; object which must be returned to the caller.
398 (defun maybe-gc (&optional object)
399   (sub-gc)
400   object)
401
402 ;;; This is the user-advertised garbage collection function.
403
404 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
405   #!+(and sb-doc gencgc)
406   "Initiates a garbage collection.  GEN controls the number of generations to garbage collect"
407   #!+(and sb-doc (not gencgc))
408   "Initiates a garbage collection.  GEN may be provided for compatibility, but is ignored"
409   (sub-gc :force-p t :gen (if full 6 gen)))
410
411 \f
412 ;;;; auxiliary functions
413
414 (defun bytes-consed-between-gcs ()
415   #!+sb-doc
416   "Return the amount of memory that will be allocated before the next garbage
417    collection is initiated. This can be set with SETF."
418   *bytes-consed-between-gcs*)
419 (defun (setf bytes-consed-between-gcs) (val)
420   ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
421   ;; be for a strictly positive number type, e.g.
422   ;; (AND (INTEGER 1) FIXNUM)?
423   (declare (type index val))
424   (let ((old *bytes-consed-between-gcs*))
425     (setf *bytes-consed-between-gcs* val)
426     (when *gc-trigger*
427       (setf *gc-trigger* (+ *gc-trigger* (- val old)))
428       (cond ((<= (dynamic-usage) *gc-trigger*)
429              (clear-auto-gc-trigger)
430              (set-auto-gc-trigger *gc-trigger*))
431             (t
432              (sb!sys:scrub-control-stack)
433              (sub-gc)))))
434   val)
435
436 (defun gc-on ()
437   #!+sb-doc
438   "Enables the garbage collector."
439   (setq *gc-inhibit* nil)
440   (when *need-to-collect-garbage*
441     (sub-gc))
442   nil)
443
444 (defun gc-off ()
445   #!+sb-doc
446   "Disables the garbage collector."
447   (setq *gc-inhibit* t)
448   nil)
449 \f
450 ;;;; initialization stuff
451
452 (defun gc-cold-init-or-reinit ()
453   (when *gc-trigger*
454     (if (< *gc-trigger* (dynamic-usage))
455         (sub-gc)
456         (set-auto-gc-trigger *gc-trigger*))))