0.6.8.6: applied MNA megapatch (will be edited shortly)
[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 #!-sb-fluid (declaim (inline dynamic-usage))
27 (def-c-var-frob dynamic-usage "bytes_allocated")
28
29 (defun static-space-usage ()
30   (- (* sb!vm:*static-space-free-pointer* sb!vm:word-bytes)
31      sb!vm:static-space-start))
32
33 (defun read-only-space-usage ()
34   (- (* sb!vm::*read-only-space-free-pointer* sb!vm:word-bytes)
35      sb!vm:read-only-space-start))
36
37 (defun control-stack-usage ()
38   #!-x86 (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
39             sb!vm:control-stack-start)
40   #!+x86 (- sb!vm:control-stack-end
41             (sb!sys:sap-int (sb!c::control-stack-pointer-sap))))
42
43 (defun binding-stack-usage ()
44   (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
45      sb!vm:binding-stack-start))
46 \f
47 ;;;; ROOM
48
49 (defun room-minimal-info ()
50   (format t "Dynamic space usage is:   ~10:D bytes.~%" (dynamic-usage))
51   (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
52   (format t "Static space usage is:    ~10:D bytes.~%" (static-space-usage))
53   (format t "Control stack usage is:   ~10:D bytes.~%" (control-stack-usage))
54   (format t "Binding stack usage is:   ~10:D bytes.~%" (binding-stack-usage))
55   (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
56           *gc-inhibit*))
57
58 (defun room-intermediate-info ()
59   (room-minimal-info)
60   (sb!vm:memory-usage :count-spaces '(:dynamic)
61                       :print-spaces t
62                       :cutoff 0.05s0
63                       :print-summary nil))
64
65 (defun room-maximal-info ()
66   (room-minimal-info)
67   (sb!vm:memory-usage :count-spaces '(:static :dynamic))
68   (sb!vm:instance-usage :dynamic :top-n 10)
69   (sb!vm:instance-usage :static :top-n 10))
70
71 (defun room (&optional (verbosity :default))
72   #!+sb-doc
73   "Prints to *STANDARD-OUTPUT* information about the state of internal
74   storage and its management. The optional argument controls the
75   verbosity of ROOM. If it is T, ROOM prints out a maximal amount of
76   information. If it is NIL, ROOM prints out a minimal amount of
77   information. If it is :DEFAULT or it is not supplied, ROOM prints out
78   an intermediate amount of information. See also VM:MEMORY-USAGE and
79   VM:INSTANCE-USAGE for finer report control."
80   (fresh-line)
81   (ecase verbosity
82     ((t)
83      (room-maximal-info))
84     ((nil)
85      (room-minimal-info))
86     (:default
87      (room-intermediate-info)))
88   (values))
89 \f
90 ;;;; GET-BYTES-CONSED
91
92 ;;; internal state
93 (defvar *last-bytes-in-use* nil)
94 (defvar *total-bytes-consed* 0)
95 (declaim (type (or index null) *last-bytes-in-use*))
96 (declaim (type integer *total-bytes-consed*))
97
98 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
99 (defun get-bytes-consed ()
100   #!+sb-doc
101   "Returns the number of bytes consed since the first time this function
102   was called. The first time it is called, it returns zero."
103   (declare (optimize (speed 3) (safety 0)))
104   (cond ((null *last-bytes-in-use*)
105          (setq *last-bytes-in-use* (dynamic-usage))
106          (setq *total-bytes-consed* 0))
107         (t
108          (let ((bytes (dynamic-usage)))
109            (incf *total-bytes-consed*
110                  (the index (- bytes *last-bytes-in-use*)))
111            (setq *last-bytes-in-use* bytes))))
112   *total-bytes-consed*)
113 \f
114 ;;;; variables and constants
115
116 ;;; the default value of *BYTES-CONSED-BETWEEN-GCS* and *GC-TRIGGER*
117 (defconstant default-bytes-consed-between-gcs 2000000)
118
119 ;;; This variable is the user-settable variable that specifies the
120 ;;; minimum amount of dynamic space which must be consed before a GC
121 ;;; will be triggered.
122 ;;;
123 ;;; Unlike CMU CL, we don't export this variable. (There's no need to, since
124 ;;; the BYTES-CONSED-BETWEEN-GCS function is SETFable.)
125 (defvar *bytes-consed-between-gcs* default-bytes-consed-between-gcs
126   #!+sb-doc
127   "This number specifies the minimum number of bytes of dynamic space
128    that must be consed before the next GC will occur.")
129 (declaim (type index *bytes-consed-between-gcs*))
130
131 ;;;; GC hooks
132
133 ;;; These variables are a list of functions which are run before and
134 ;;; after garbage collection occurs.
135 (defvar *before-gc-hooks* nil ; actually initialized in cold init
136   #!+sb-doc
137   "A list of functions that are called before garbage collection occurs.
138   The functions should take no arguments.")
139 (defvar *after-gc-hooks* nil ; actually initialized in cold init
140   #!+sb-doc
141   "A list of functions that are called after garbage collection occurs.
142   The functions should take no arguments.")
143
144 ;;; This hook is invoked whenever SUB-GC intends to GC (unless the GC
145 ;;; was explicitly forced by calling SB!EXT:GC). If the hook function
146 ;;; returns NIL then the GC procedes; otherwise, the GC is inhibited and
147 ;;; *GC-INHIBIT* and *NEED-TO-COLLECT-GARBAGE* are left bound to T.
148 ;;; Presumably someone will call GC-ON later to collect the garbage.
149 (defvar *gc-inhibit-hook* nil
150   #!+sb-doc
151   "Should be bound to a function or NIL. If it is a function, this
152   function should take one argument, the current amount of dynamic
153   usage. The function should return NIL if garbage collection should
154   continue and non-NIL if it should be inhibited. Use with caution.")
155
156 (defvar *gc-verbose* nil ; (actually initialized in cold init)
157   #!+sb-doc
158   "Should low-level GC functions produce verbose diagnostic output?")
159
160 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
161   #!+sb-doc
162   "When non-NIL, this must be a STREAM; and the functions bound to
163   *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
164   STREAM value before and after a garbage collection occurs
165   respectively.")
166
167 (defvar *gc-run-time* 0
168   #!+sb-doc
169   "The total CPU time spent doing garbage collection (as reported by
170    GET-INTERNAL-RUN-TIME.)")
171
172 (declaim (type index *gc-run-time*))
173
174 ;;; Internal trigger. When the dynamic usage increases beyond this
175 ;;; amount, the system notes that a garbage collection needs to occur by
176 ;;; setting *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
177 ;;; nobody has figured out what it should be yet.
178 (defvar *gc-trigger* nil)
179
180 (declaim (type (or index null) *gc-trigger*))
181
182 ;;; On the RT, we store the GC trigger in a ``static'' symbol instead of
183 ;;; letting magic C code handle it. It gets initialized by the startup
184 ;;; code. The X86 port defines this here because it uses the `ibmrt'
185 ;;; feature in the C code for allocation and binding stack access and
186 ;;; a lot of stuff wants this INTERNAL_GC_TRIGGER available as well.
187 #!+(or ibmrt x86)
188 (defvar sb!vm::*internal-gc-trigger*)
189
190 ;;;; The following specials are used to control when garbage collection
191 ;;;; occurs.
192
193 ;;; When non-NIL, inhibits garbage collection.
194 (defvar *gc-inhibit*) ; initialized in cold init
195
196 ;;; This flag is used to prevent recursive entry into the garbage
197 ;;; collector.
198 (defvar *already-maybe-gcing*) ; initialized in cold init
199
200 ;;; When T, indicates that the dynamic usage has exceeded the value
201 ;;; *GC-TRIGGER*.
202 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
203 \f
204 (defun default-gc-notify-before (notify-stream bytes-in-use)
205   (declare (type stream notify-stream))
206   (format notify-stream
207           "~&; GC is beginning with ~:D bytes in use.~%"
208           bytes-in-use)
209   (finish-output notify-stream))
210 (defparameter *gc-notify-before* #'default-gc-notify-before
211   #!+sb-doc
212   "This function bound to this variable is invoked before GC'ing (unless
213   *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
214   current amount of dynamic usage (in bytes). It should notify the
215   user that the system is going to GC.")
216
217 (defun default-gc-notify-after (notify-stream
218                                 bytes-retained
219                                 bytes-freed
220                                 new-trigger)
221   (declare (type stream notify-stream))
222   (format notify-stream
223           "~&; GC has finished with ~:D bytes in use (~:D bytes freed).~%"
224           bytes-retained
225           bytes-freed)
226   (format notify-stream
227           "~&; The new GC trigger is ~:D bytes.~%"
228           new-trigger)
229   (finish-output notify-stream))
230 (defparameter *gc-notify-after* #'default-gc-notify-after
231   #!+sb-doc
232   "The function bound to this variable is invoked after GC'ing (unless
233   *GC-VERBOSE* is NIL) with the value of *GC-NOTIFY-STREAM*,
234   the amount of dynamic usage (in bytes) now free, the number of
235   bytes freed by the GC, and the new GC trigger threshold. The function
236   should notify the user that the system has finished GC'ing.")
237 \f
238 ;;;; internal GC
239
240 (sb!alien:def-alien-routine collect-garbage sb!c-call:int
241   #!+gencgc (last-gen sb!c-call:int))
242
243 (sb!alien:def-alien-routine set-auto-gc-trigger sb!c-call:void
244   (dynamic-usage sb!c-call:unsigned-long))
245
246 (sb!alien:def-alien-routine clear-auto-gc-trigger sb!c-call:void)
247
248 ;;; This variable contains the function that does the real GC. This is
249 ;;; for low-level GC experimentation. Do not touch it if you do not
250 ;;; know what you are doing.
251 (defvar *internal-gc* #'collect-garbage)
252 \f
253 ;;;; SUB-GC
254
255 ;;; Used to carefully invoke hooks.
256 (eval-when (:compile-toplevel :execute)
257   (sb!xc:defmacro carefully-funcall (function &rest args)
258     `(handler-case (funcall ,function ,@args)
259        (error (cond)
260               (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
261               nil))))
262
263 ;;; SUB-GC decides when and if to do a garbage collection. The
264 ;;; VERBOSE-P flag controls whether or not the notify functions are
265 ;;; called. The FORCE-P flags controls if a GC should occur even if
266 ;;; the dynamic usage is not greater than *GC-TRIGGER*.
267 ;;;
268 ;;; For GENCGC all generations < GEN will be GC'ed.
269 ;;;
270 ;;; FIXME: The VERBOSE-P stuff is no longer used.
271 (defun sub-gc (&key (verbose-p *gc-verbose*) force-p #!+gencgc (gen 0))
272   (/show0 "entering SUB-GC")
273   (unless *already-maybe-gcing*
274     (/show0 "not *ALREADY-MAYBE-GCING*")
275     (let* ((*already-maybe-gcing* t)
276            (start-time (get-internal-run-time))
277            (pre-gc-dyn-usage (dynamic-usage)))
278       (unless (integerp (symbol-value '*bytes-consed-between-gcs*))
279         ;; The noise w/ symbol-value above is to keep the compiler
280         ;; from optimizing the test away because of the type declaim
281         ;; for *bytes-consed-between-gcs*.
282         ;;
283         ;; FIXME: I'm inclined either to get rid of the DECLAIM or to
284         ;; trust it, instead of doing this weird hack. It's not
285         ;; particularly trustable, since (SETF
286         ;; *BYTES-CONSED-BETWEEN-GCS* 'SEVEN) works. But it's also not
287         ;; very nice to have the type of the variable specified in two
288         ;; places which can (and in CMU CL 2.4.8 did, INTEGER vs.
289         ;; INDEX) drift apart. So perhaps we should just add a note to
290         ;; the variable documentation for *BYTES-CONSED-BETWEEN-GCS*
291         ;; that it must be an INDEX, and remove the DECLAIM. Or we
292         ;; could make a SETFable (BYTES-CONSED-BETWEEN-GCS) function
293         ;; and enforce the typing that way. And in fact the SETFable
294         ;; function already exists, so all we need do is make the
295         ;; variable private, and then we can trust the DECLAIM.
296         (warn "The value of *BYTES-CONSED-BETWEEN-GCS*, ~S, is not an ~
297                integer. Resetting it to ~D."
298               *bytes-consed-between-gcs*
299                default-bytes-consed-between-gcs)
300         (setf *bytes-consed-between-gcs* default-bytes-consed-between-gcs))
301       (when (and *gc-trigger* (> pre-gc-dyn-usage *gc-trigger*))
302         (/show0 "setting *NEED-TO-COLLECT-GARBAGE* to T")
303         (setf *need-to-collect-garbage* t))
304       (when (or force-p
305                 (and *need-to-collect-garbage* (not *gc-inhibit*)))
306         (/show0 "Evidently we ought to collect garbage..")
307         (when (and (not force-p)
308                    *gc-inhibit-hook*
309                    (carefully-funcall *gc-inhibit-hook* pre-gc-dyn-usage))
310           (/show0 "..but we're inhibited.")
311           (setf *gc-inhibit* t)
312           (return-from sub-gc nil))
313         ;; KLUDGE: Wow, we really mask interrupts all the time we're
314         ;; collecting garbage? That seems like a long time.. -- WHN 19991129
315         (without-interrupts
316          ;; FIXME: We probably shouldn't do this evil thing to
317          ;; *STANDARD-OUTPUT* in a binding which is wrapped around
318          ;; calls to user-settable GC hook functions.
319           (let ((*standard-output* *terminal-io*))
320             (when *gc-notify-stream*
321               (/show0 "doing the *GC-NOTIFY-BEFORE* thing")
322               (if (streamp *gc-notify-stream*)
323                   (carefully-funcall *gc-notify-before*
324                                      *gc-notify-stream*
325                                      pre-gc-dyn-usage)
326                   (warn
327                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
328             (dolist (hook *before-gc-hooks*)
329               (/show0 "doing a hook from *BEFORE-GC-HOOKS*")
330               (carefully-funcall hook))
331             (when *gc-trigger*
332               (clear-auto-gc-trigger))
333             (/show0 "FUNCALLing *INTERNAL-GC*, one way or another")
334             #!-gencgc (funcall *internal-gc*)
335             ;; FIXME: This EQ test is pretty gross. Among its other
336             ;; nastinesses, it looks as though it could break if we
337             ;; recompile COLLECT-GARBAGE.
338             #!+gencgc (if (eq *internal-gc* #'collect-garbage)
339                           (funcall *internal-gc* gen)
340                           (funcall *internal-gc*))
341             (/show0 "back from FUNCALL to *INTERNAL-GC*")
342             (let* ((post-gc-dyn-usage (dynamic-usage))
343                    (bytes-freed (- pre-gc-dyn-usage post-gc-dyn-usage)))
344               (when *last-bytes-in-use*
345                 (incf *total-bytes-consed*
346                       (- pre-gc-dyn-usage *last-bytes-in-use*))
347                 (setq *last-bytes-in-use* post-gc-dyn-usage))
348               (setf *need-to-collect-garbage* nil)
349               (let ((new-gc-trigger (+ post-gc-dyn-usage
350                                        *bytes-consed-between-gcs*)))
351                 (setf *gc-trigger* new-gc-trigger))
352               (set-auto-gc-trigger *gc-trigger*)
353               (dolist (hook *after-gc-hooks*)
354                 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
355                 ;; FIXME: This hook should be called with the
356                 ;; same kind of information as *GC-NOTIFY-AFTER*.
357                 ;; In particular, it would be nice for the
358                 ;; hook function to be able to adjust *GC-TRIGGER*
359                 ;; intelligently to e.g. 108% of total memory usage.
360                 (carefully-funcall hook))
361               (when *gc-notify-stream*
362                 (/show0 "doing the *GC-NOTIFY-AFTER* thing")
363                 (if (streamp *gc-notify-stream*)
364                     (carefully-funcall *gc-notify-after*
365                                        *gc-notify-stream*
366                                        post-gc-dyn-usage
367                                        bytes-freed
368                                        *gc-trigger*)
369                     (warn
370                      "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
371           (/show0 "scrubbing control stack")
372           (scrub-control-stack)))
373       (/show0 "updating *GC-RUN-TIME*")
374       (incf *gc-run-time* (- (get-internal-run-time)
375                              start-time))))
376   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
377   (/show0 "returning from tail of SUB-GC")
378   nil)
379
380 ;;; This routine is called by the allocation miscops to decide whether
381 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
382 ;;; object which must be returned to the caller.
383 (defun maybe-gc (&optional object)
384   (sub-gc)
385   object)
386
387 ;;; This is the user-advertised garbage collection function.
388 ;;;
389 ;;; KLUDGE: GC shouldn't have different parameters depending on what
390 ;;; garbage collector we use. -- WHN 19991020
391 #!-gencgc
392 (defun gc (&optional (verbose-p *gc-verbose*))
393   #!+sb-doc
394   "Initiates a garbage collection. VERBOSE-P controls
395   whether or not GC statistics are printed."
396   (sub-gc :verbose-p verbose-p :force-p t))
397 #!+gencgc
398 (defun gc (&key (verbose *gc-verbose*) (gen 0) (full nil))
399   #!+sb-doc
400   "Initiates a garbage collection. VERBOSE controls whether or not GC
401   statistics are printed. GEN controls the number of generations to garbage
402   collect."
403   ;; FIXME: The bare 6 here (corresponding to a bare 6 in
404   ;; the gencgc.c sources) is nasty.
405   (sub-gc :verbose-p verbose :force-p t :gen (if full 6 gen)))
406 \f
407 ;;;; auxiliary functions
408
409 (defun bytes-consed-between-gcs ()
410   #!+sb-doc
411   "Return the amount of memory that will be allocated before the next garbage
412    collection is initiated. This can be set with SETF."
413   *bytes-consed-between-gcs*)
414 (defun (setf bytes-consed-between-gcs) (val)
415   ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
416   ;; be for a strictly positive number type, e.g.
417   ;; (AND (INTEGER 1) FIXNUM)?
418   (declare (type index val))
419   (let ((old *bytes-consed-between-gcs*))
420     (setf *bytes-consed-between-gcs* val)
421     (when *gc-trigger*
422       (setf *gc-trigger* (+ *gc-trigger* (- val old)))
423       (cond ((<= (dynamic-usage) *gc-trigger*)
424              (clear-auto-gc-trigger)
425              (set-auto-gc-trigger *gc-trigger*))
426             (t
427              (sb!sys:scrub-control-stack)
428              (sub-gc)))))
429   val)
430
431 (defun gc-on ()
432   #!+sb-doc
433   "Enables the garbage collector."
434   (setq *gc-inhibit* nil)
435   (when *need-to-collect-garbage*
436     (sub-gc))
437   nil)
438
439 (defun gc-off ()
440   #!+sb-doc
441   "Disables the garbage collector."
442   (setq *gc-inhibit* t)
443   nil)
444 \f
445 ;;;; initialization stuff
446
447 (defun gc-cold-init-or-reinit ()
448   (when *gc-trigger*
449     (if (< *gc-trigger* (dynamic-usage))
450         (sub-gc)
451         (set-auto-gc-trigger *gc-trigger*))))