0.6.11.30:
[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-notify-stream* nil ; (actually initialized in cold init)
157   #!+sb-doc
158   "When non-NIL, this must be a STREAM; and the functions bound to
159   *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
160   STREAM value before and after a garbage collection occurs
161   respectively.")
162
163 (defvar *gc-run-time* 0
164   #!+sb-doc
165   "The total CPU time spent doing garbage collection (as reported by
166    GET-INTERNAL-RUN-TIME.)")
167 (declaim (type index *gc-run-time*))
168
169 ;;; a limit to help catch programs which allocate too much memory,
170 ;;; since a hard heap overflow is so hard to recover from. 
171 (declaim (type (or unsigned-byte null) *soft-heap-limit*))
172 (defvar *soft-heap-limit* nil)
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.
264 ;;; The FORCE-P flags controls if a GC should occur even if
265 ;;; the dynamic usage is not greater than *GC-TRIGGER*.
266 ;;;
267 ;;; For GENCGC all generations < GEN will be GC'ed.
268 ;;;
269 (defun sub-gc (&key force-p #!+gencgc (gen 0))
270   (/show0 "entering SUB-GC")
271   (unless *already-maybe-gcing*
272     (/show0 "not *ALREADY-MAYBE-GCING*")
273     (let* ((*already-maybe-gcing* t)
274            (start-time (get-internal-run-time))
275            (pre-gc-dyn-usage (dynamic-usage))
276            ;; Currently we only check *SOFT-HEAP-LIMIT* at GC time,
277            ;; not for every allocation. That makes it cheap to do,
278            ;; even if it is a little ugly.
279            (soft-heap-limit-exceeded? (and *soft-heap-limit*
280                                            (> pre-gc-dyn-usage
281                                               *soft-heap-limit*)))
282            (*soft-heap-limit* (if soft-heap-limit-exceeded?
283                                   (+ pre-gc-dyn-usage
284                                      *bytes-consed-between-gcs*)
285                                   *soft-heap-limit*)))
286       (when soft-heap-limit-exceeded?
287         (cerror "Continue with GC."
288                 "soft heap limit exceeded (temporary new limit=~D)"
289                 *soft-heap-limit*))
290       (unless (integerp (symbol-value '*bytes-consed-between-gcs*))
291         ;; The noise w/ symbol-value above is to keep the compiler
292         ;; from optimizing the test away because of the type declaim
293         ;; for *bytes-consed-between-gcs*.
294         ;;
295         ;; FIXME: I'm inclined either to get rid of the DECLAIM or to
296         ;; trust it, instead of doing this weird hack. It's not
297         ;; particularly trustable, since (SETF
298         ;; *BYTES-CONSED-BETWEEN-GCS* 'SEVEN) works. But it's also not
299         ;; very nice to have the type of the variable specified in two
300         ;; places which can (and in CMU CL 2.4.8 did, INTEGER vs.
301         ;; INDEX) drift apart. So perhaps we should just add a note to
302         ;; the variable documentation for *BYTES-CONSED-BETWEEN-GCS*
303         ;; that it must be an INDEX, and remove the DECLAIM. Or we
304         ;; could make a SETFable (BYTES-CONSED-BETWEEN-GCS) function
305         ;; and enforce the typing that way. And in fact the SETFable
306         ;; function already exists, so all we need do is make the
307         ;; variable private, and then we can trust the DECLAIM.
308         (warn "The value of *BYTES-CONSED-BETWEEN-GCS*, ~S, is not an ~
309                integer. Resetting it to ~D."
310               *bytes-consed-between-gcs*
311                default-bytes-consed-between-gcs)
312         (setf *bytes-consed-between-gcs* default-bytes-consed-between-gcs))
313       (when (and *gc-trigger* (> pre-gc-dyn-usage *gc-trigger*))
314         (/show0 "setting *NEED-TO-COLLECT-GARBAGE* to T")
315         (setf *need-to-collect-garbage* t))
316       (when (or force-p
317                 (and *need-to-collect-garbage* (not *gc-inhibit*)))
318         (/show0 "Evidently we ought to collect garbage..")
319         (when (and (not force-p)
320                    *gc-inhibit-hook*
321                    (carefully-funcall *gc-inhibit-hook* pre-gc-dyn-usage))
322           (/show0 "..but we're inhibited.")
323           (setf *gc-inhibit* t)
324           (return-from sub-gc nil))
325         ;; KLUDGE: Wow, we really mask interrupts all the time we're
326         ;; collecting garbage? That seems like a long time.. -- WHN 19991129
327         (without-interrupts
328          ;; FIXME: We probably shouldn't do this evil thing to
329          ;; *STANDARD-OUTPUT* in a binding which is wrapped around
330          ;; calls to user-settable GC hook functions.
331           (let ((*standard-output* *terminal-io*))
332             (when *gc-notify-stream*
333               (/show0 "doing the *GC-NOTIFY-BEFORE* thing")
334               (if (streamp *gc-notify-stream*)
335                   (carefully-funcall *gc-notify-before*
336                                      *gc-notify-stream*
337                                      pre-gc-dyn-usage)
338                   (warn
339                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
340             (dolist (hook *before-gc-hooks*)
341               (/show0 "doing a hook from *BEFORE-GC-HOOKS*")
342               (carefully-funcall hook))
343             (when *gc-trigger*
344               (clear-auto-gc-trigger))
345             (/show0 "FUNCALLing *INTERNAL-GC*, one way or another")
346             #!-gencgc (funcall *internal-gc*)
347             ;; FIXME: This EQ test is pretty gross. Among its other
348             ;; nastinesses, it looks as though it could break if we
349             ;; recompile COLLECT-GARBAGE.
350             #!+gencgc (if (eq *internal-gc* #'collect-garbage)
351                           (funcall *internal-gc* gen)
352                           (funcall *internal-gc*))
353             (/show0 "back from FUNCALL to *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                 (/show0 "doing the *GC-NOTIFY-AFTER* thing")
382                 (if (streamp *gc-notify-stream*)
383                     (carefully-funcall *gc-notify-after*
384                                        *gc-notify-stream*
385                                        post-gc-dyn-usage
386                                        bytes-freed
387                                        *gc-trigger*)
388                     (warn
389                      "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
390           (/show0 "scrubbing control stack")
391           (scrub-control-stack)))
392       (/show0 "updating *GC-RUN-TIME*")
393       (incf *gc-run-time* (- (get-internal-run-time)
394                              start-time))))
395   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
396   (/show0 "returning from tail of SUB-GC")
397   nil)
398
399 ;;; This routine is called by the allocation miscops to decide whether
400 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
401 ;;; object which must be returned to the caller.
402 (defun maybe-gc (&optional object)
403   (sub-gc)
404   object)
405
406 ;;; This is the user-advertised garbage collection function.
407 ;;;
408 ;;; KLUDGE: GC shouldn't have different parameters depending on what
409 ;;; garbage collector we use. -- WHN 19991020
410 #!-gencgc
411 (defun gc ()
412   #!+sb-doc
413   "Initiates a garbage collection."
414   (sub-gc :force-p t))
415 #!+gencgc
416 (defun gc (&key (gen 0) (full nil))
417   #!+sb-doc
418   "Initiates a garbage collection.
419   GEN controls the number of generations to garbage collect."
420   ;; FIXME: The bare 6 here (corresponding to a bare 6 in
421   ;; the gencgc.c sources) is nasty.
422   (sub-gc :force-p t :gen (if full 6 gen)))
423 \f
424 ;;;; auxiliary functions
425
426 (defun bytes-consed-between-gcs ()
427   #!+sb-doc
428   "Return the amount of memory that will be allocated before the next garbage
429    collection is initiated. This can be set with SETF."
430   *bytes-consed-between-gcs*)
431 (defun (setf bytes-consed-between-gcs) (val)
432   ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
433   ;; be for a strictly positive number type, e.g.
434   ;; (AND (INTEGER 1) FIXNUM)?
435   (declare (type index val))
436   (let ((old *bytes-consed-between-gcs*))
437     (setf *bytes-consed-between-gcs* val)
438     (when *gc-trigger*
439       (setf *gc-trigger* (+ *gc-trigger* (- val old)))
440       (cond ((<= (dynamic-usage) *gc-trigger*)
441              (clear-auto-gc-trigger)
442              (set-auto-gc-trigger *gc-trigger*))
443             (t
444              (sb!sys:scrub-control-stack)
445              (sub-gc)))))
446   val)
447
448 (defun gc-on ()
449   #!+sb-doc
450   "Enables the garbage collector."
451   (setq *gc-inhibit* nil)
452   (when *need-to-collect-garbage*
453     (sub-gc))
454   nil)
455
456 (defun gc-off ()
457   #!+sb-doc
458   "Disables the garbage collector."
459   (setq *gc-inhibit* t)
460   nil)
461 \f
462 ;;;; initialization stuff
463
464 (defun gc-cold-init-or-reinit ()
465   (when *gc-trigger*
466     (if (< *gc-trigger* (dynamic-usage))
467         (sub-gc)
468         (set-auto-gc-trigger *gc-trigger*))))