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