0.pre7.140:
[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   #!-x86 (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
54             sb!vm:control-stack-start)
55   #!+x86 (- sb!vm:control-stack-end
56             (sb!sys:sap-int (sb!c::control-stack-pointer-sap))))
57
58 (defun binding-stack-usage ()
59   (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
60      sb!vm:binding-stack-start))
61 \f
62 ;;;; ROOM
63
64 (defun room-minimal-info ()
65   (format t "Dynamic space usage is:   ~10:D bytes.~%" (dynamic-usage))
66   (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
67   (format t "Static space usage is:    ~10:D bytes.~%" (static-space-usage))
68   (format t "Control stack usage is:   ~10:D bytes.~%" (control-stack-usage))
69   (format t "Binding stack usage is:   ~10:D bytes.~%" (binding-stack-usage))
70   (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
71           *gc-inhibit*))
72
73 (defun room-intermediate-info ()
74   (room-minimal-info)
75   (sb!vm:memory-usage :count-spaces '(:dynamic)
76                       :print-spaces t
77                       :cutoff 0.05s0
78                       :print-summary nil))
79
80 (defun room-maximal-info ()
81   (room-minimal-info)
82   (sb!vm:memory-usage :count-spaces '(:static :dynamic))
83   (sb!vm:instance-usage :dynamic :top-n 10)
84   (sb!vm:instance-usage :static :top-n 10))
85
86 (defun room (&optional (verbosity :default))
87   #!+sb-doc
88   "Print to *STANDARD-OUTPUT* information about the state of internal
89   storage and its management. The optional argument controls the
90   verbosity of output. If it is T, ROOM prints out a maximal amount of
91   information. If it is NIL, ROOM prints out a minimal amount of
92   information. If it is :DEFAULT or it is not supplied, ROOM prints out
93   an intermediate amount of information."
94   (fresh-line)
95   (ecase verbosity
96     ((t)
97      (room-maximal-info))
98     ((nil)
99      (room-minimal-info))
100     (:default
101      (room-intermediate-info)))
102   (values))
103 \f
104 ;;;; GET-BYTES-CONSED
105
106 ;;; the total number of bytes freed so far (including any freeing
107 ;;; which goes on in PURIFY)
108 ;;;
109 ;;; (We save this so that we can calculate the total number of bytes
110 ;;; ever allocated by adding this to the number of bytes currently
111 ;;; allocated and never freed.)
112 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
113 (defvar *n-bytes-freed-or-purified* 0)
114 (push (lambda ()
115         (setf *n-bytes-freed-or-purified* 0))
116       ;; KLUDGE: It's probably not quite safely right either to do
117       ;; this in *BEFORE-SAVE-INITIALIZATIONS* (since consing, or even
118       ;; worse, something which depended on (GET-BYTES-CONSED), might
119       ;; happen after that) or in *AFTER-SAVE-INITIALIZATIONS*. But
120       ;; it's probably not a big problem, and there seems to be no
121       ;; other obvious time to do it. -- WHN 2001-07-30
122       *after-save-initializations*)
123
124 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
125 (defun get-bytes-consed ()
126   #!+sb-doc
127   "Return the number of bytes consed since the program began. Typically
128 this result will be a consed bignum, so if you have an application (e.g.
129 profiling) which can't tolerate the overhead of consing bignums, you'll
130 probably want either to hack in at a lower level (as the code in the
131 SB-PROFILE package does), or to design a more microefficient interface
132 and submit it as a patch."
133   (+ (dynamic-usage)
134      *n-bytes-freed-or-purified*))
135 \f
136 ;;;; variables and constants
137
138 ;;; the minimum amount of dynamic space which must be consed before a
139 ;;; GC will be triggered
140 ;;;
141 ;;; Unlike CMU CL, we don't export this variable. (There's no need to,
142 ;;; since our BYTES-CONSED-BETWEEN-GCS function is SETFable.)
143 (defvar *bytes-consed-between-gcs* (* 4 (expt 10 6)))
144 (declaim (type index *bytes-consed-between-gcs*))
145
146 ;;;; GC hooks
147
148 (defvar *before-gc-hooks* nil ; actually initialized in cold init
149   #!+sb-doc
150   "A list of functions that are called before garbage collection occurs.
151   The functions should take no arguments.")
152
153 (defvar *after-gc-hooks* nil ; actually initialized in cold init
154   #!+sb-doc
155   "A list of functions that are called after garbage collection occurs.
156   The functions should take no arguments.")
157
158 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
159   #!+sb-doc
160   "When non-NIL, this must be a STREAM; and the functions bound to
161   *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
162   STREAM value before and after a garbage collection occurs
163   respectively.")
164
165 (defvar *gc-run-time* 0
166   #!+sb-doc
167   "the total CPU time spent doing garbage collection (as reported by
168    GET-INTERNAL-RUN-TIME)")
169 (declaim (type index *gc-run-time*))
170
171 ;;; a limit to help catch programs which allocate too much memory,
172 ;;; since a hard heap overflow is so hard to recover from
173 (declaim (type (or unsigned-byte null) *soft-heap-limit*))
174 (defvar *soft-heap-limit* nil)
175
176 ;;; When the dynamic usage increases beyond this amount, the system
177 ;;; notes that a garbage collection needs to occur by setting
178 ;;; *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
179 ;;; nobody has figured out what it should be yet.
180 (defvar *gc-trigger* nil)
181
182 (declaim (type (or index null) *gc-trigger*))
183
184 ;;; On the X86, we store the GC trigger in a ``static'' symbol instead
185 ;;; of letting magic C code handle it. It gets initialized by the
186 ;;; startup code.
187 #!+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
207    notify-stream
208    "~&; GC is beginning with ~:D bytes in use at internal runtime ~:D.~%"
209    bytes-in-use
210    (get-internal-run-time))
211   (finish-output notify-stream))
212 (defparameter *gc-notify-before* #'default-gc-notify-before
213   #!+sb-doc
214   "This function bound to this variable is invoked before GC'ing (unless
215   *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
216   current amount of dynamic usage (in bytes). It should notify the
217   user that the system is going to GC.")
218
219 (defun default-gc-notify-after (notify-stream
220                                 bytes-retained
221                                 bytes-freed
222                                 new-trigger)
223   (declare (type stream notify-stream))
224   (format notify-stream
225           "~&; GC has finished with ~:D bytes in use (~:D bytes freed)~@
226            ; at internal runtime ~:D. The new GC trigger is ~:D bytes.~%"
227           bytes-retained
228           bytes-freed
229           (get-internal-run-time)
230           new-trigger)
231   (finish-output notify-stream))
232 (defparameter *gc-notify-after* #'default-gc-notify-after
233   #!+sb-doc
234   "The function bound to this variable is invoked after GC'ing with the
235 value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in bytes) now
236 free, the number of bytes freed by the GC, and the new GC trigger
237 threshold; or if *GC-NOTIFY-STREAM* is NIL, it's not invoked. The
238 function should notify the user that the system has finished GC'ing.")
239 \f
240 ;;;; internal GC
241
242 (sb!alien:define-alien-routine collect-garbage sb!alien:int
243   #!+gencgc (last-gen sb!alien:int))
244
245 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
246   (dynamic-usage sb!alien:unsigned-long))
247
248 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien:void)
249
250 ;;; This variable contains the function that does the real GC. This is
251 ;;; for low-level GC experimentation. Do not touch it if you do not
252 ;;; know what you are doing.
253 (defvar *internal-gc* #'collect-garbage)
254 \f
255 ;;;; SUB-GC
256
257 ;;; This is used to carefully invoke hooks.
258 (eval-when (:compile-toplevel :execute)
259   (sb!xc:defmacro carefully-funcall (function &rest args)
260     `(handler-case (funcall ,function ,@args)
261        (error (cond)
262               (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
263               nil))))
264
265 ;;; SUB-GC decides when and if to do a garbage collection. The FORCE-P
266 ;;; flags controls whether a GC should occur even if the dynamic usage
267 ;;; is not greater than *GC-TRIGGER*.
268 ;;;
269 ;;; For GENCGC all generations < GEN will be GC'ed.
270 (defun sub-gc (&key force-p (gen 0))
271   (/show0 "entering SUB-GC")
272   (unless *already-maybe-gcing*
273     (let* ((*already-maybe-gcing* t)
274            (start-time (get-internal-run-time))
275            (pre-gc-dynamic-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-dynamic-usage
281                                               *soft-heap-limit*)))
282            (*soft-heap-limit* (if soft-heap-limit-exceeded?
283                                   (+ pre-gc-dynamic-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=~W)"
289                 *soft-heap-limit*))
290       (when (and *gc-trigger* (> pre-gc-dynamic-usage *gc-trigger*))
291         (setf *need-to-collect-garbage* t))
292       (when (or force-p
293                 (and *need-to-collect-garbage* (not *gc-inhibit*)))
294         ;; KLUDGE: Wow, we really mask interrupts all the time we're
295         ;; collecting garbage? That seems like a long time.. -- WHN 19991129
296         (without-interrupts
297          ;; FIXME: We probably shouldn't do this evil thing to
298          ;; *STANDARD-OUTPUT* in a binding which is wrapped around
299          ;; calls to user-settable GC hook functions.
300           (let ((*standard-output* *terminal-io*))
301             (when *gc-notify-stream*
302               (if (streamp *gc-notify-stream*)
303                   (carefully-funcall *gc-notify-before*
304                                      *gc-notify-stream*
305                                      pre-gc-dynamic-usage)
306                   (warn
307                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
308             (dolist (hook *before-gc-hooks*)
309               (carefully-funcall hook))
310             (when *gc-trigger*
311               (clear-auto-gc-trigger))
312             (let* (;; We do DYNAMIC-USAGE once more here in order to
313                    ;; get a more accurate measurement of the space
314                    ;; actually freed, since the messing around, e.g.
315                    ;; GC-notify stuff, since the DYNAMIC-USAGE which
316                    ;; triggered GC could've done a fair amount of
317                    ;; consing.)
318                    (pre-internal-gc-dynamic-usage (dynamic-usage))
319                    (ignore-me
320                     #!-gencgc (funcall *internal-gc*)
321                     ;; FIXME: This EQ test is pretty gross. Among its other
322                     ;; nastinesses, it looks as though it could break if we
323                     ;; recompile COLLECT-GARBAGE. We should probably just
324                     ;; straighten out the interface so that all *INTERNAL-GC*
325                     ;; functions accept a GEN argument (and then the
326                     ;; non-generational ones just ignore it).
327                     #!+gencgc (if (eq *internal-gc* #'collect-garbage)
328                                   (funcall *internal-gc* gen)
329                                   (funcall *internal-gc*)))
330                    (post-gc-dynamic-usage (dynamic-usage))
331                    (n-bytes-freed (- pre-internal-gc-dynamic-usage
332                                      post-gc-dynamic-usage))
333                    ;; In sbcl-0.6.12.39, the raw N-BYTES-FREED from
334                    ;; GENCGC could sometimes be substantially negative
335                    ;; (e.g. -5872). I haven't looked into what causes
336                    ;; that, but I suspect it has to do with
337                    ;; fluctuating inefficiency in the way that the
338                    ;; GENCGC packs things into page boundaries.
339                    ;; Bumping the raw result up to 0 is a little ugly,
340                    ;; but shouldn't be a problem, and it's even
341                    ;; possible to sort of justify it: the packing
342                    ;; inefficiency which has caused (DYNAMIC-USAGE) to
343                    ;; grow is effectively consing, or at least
344                    ;; overhead of consing, so it's sort of correct to
345                    ;; add it to the running total of consing. ("Man
346                    ;; isn't a rational animal, he's a rationalizing
347                    ;; animal.":-) -- WHN 2001-06-23
348                    (eff-n-bytes-freed (max 0 n-bytes-freed)))
349               (declare (ignore ignore-me))
350               (/show0 "got (DYNAMIC-USAGE) and EFF-N-BYTES-FREED")
351               (incf *n-bytes-freed-or-purified*
352                     eff-n-bytes-freed)
353               (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
354               (setf *need-to-collect-garbage* nil)
355               (/show0 "calculating NEW-GC-TRIGGER")
356               (let ((new-gc-trigger (+ post-gc-dynamic-usage
357                                        *bytes-consed-between-gcs*)))
358                 (/show0 "setting *GC-TRIGGER*")
359                 (setf *gc-trigger* new-gc-trigger))
360               (/show0 "calling SET-AUTO-GC-TRIGGER")
361               (set-auto-gc-trigger *gc-trigger*)
362               (dolist (hook *after-gc-hooks*)
363                 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
364                 ;; FIXME: This hook should be called with the same
365                 ;; kind of information as *GC-NOTIFY-AFTER*. In
366                 ;; particular, it would be nice for the hook function
367                 ;; to be able to adjust *GC-TRIGGER* intelligently to
368                 ;; e.g. 108% of total memory usage.
369                 (carefully-funcall hook))
370               (when *gc-notify-stream*
371                 (if (streamp *gc-notify-stream*)
372                     (carefully-funcall *gc-notify-after*
373                                        *gc-notify-stream*
374                                        post-gc-dynamic-usage
375                                        eff-n-bytes-freed
376                                        *gc-trigger*)
377                     (warn
378                      "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
379           (scrub-control-stack)))       ;XXX again?  we did this from C ...
380       (incf *gc-run-time* (- (get-internal-run-time)
381                              start-time))))
382   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
383   nil)
384
385 ;;; This routine is called by the allocation miscops to decide whether
386 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
387 ;;; object which must be returned to the caller.
388 (defun maybe-gc (&optional object)
389   (sub-gc)
390   object)
391
392 ;;; This is the user-advertised garbage collection function.
393 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
394   #!+(and sb-doc gencgc)
395   "Initiate a garbage collection. GEN controls the number of generations
396   to garbage collect."
397   #!+(and sb-doc (not gencgc))
398   "Initiate a garbage collection. GEN may be provided for compatibility with
399   generational garbage collectors, but is ignored in this implementation."
400   (sub-gc :force-p t :gen (if full 6 gen)))
401
402 \f
403 ;;;; auxiliary functions
404
405 (defun bytes-consed-between-gcs ()
406   #!+sb-doc
407   "Return the amount of memory that will be allocated before the next garbage
408    collection is initiated. This can be set with SETF."
409   *bytes-consed-between-gcs*)
410 (defun (setf bytes-consed-between-gcs) (val)
411   ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
412   ;; be for a strictly positive number type, e.g.
413   ;; (AND (INTEGER 1) FIXNUM)?
414   (declare (type index val))
415   (let ((old *bytes-consed-between-gcs*))
416     (setf *bytes-consed-between-gcs* val)
417     (when *gc-trigger*
418       (setf *gc-trigger* (+ *gc-trigger* (- val old)))
419       (cond ((<= (dynamic-usage) *gc-trigger*)
420              (clear-auto-gc-trigger)
421              (set-auto-gc-trigger *gc-trigger*))
422             (t
423              ;; FIXME: If SCRUB-CONTROL-STACK is required here, why
424              ;; isn't it built into SUB-GC? And *is* it required here?
425              (sb!sys:scrub-control-stack)
426              (sub-gc)))))
427   val)
428
429 (defun gc-on ()
430   #!+sb-doc
431   "Enable the garbage collector."
432   (setq *gc-inhibit* nil)
433   (when *need-to-collect-garbage*
434     (sub-gc))
435   nil)
436
437 (defun gc-off ()
438   #!+sb-doc
439   "Disable the garbage collector."
440   (setq *gc-inhibit* t)
441   nil)
442 \f
443 ;;;; initialization stuff
444
445 (defun gc-reinit ()
446   (when *gc-trigger*
447     (if (< *gc-trigger* (dynamic-usage))
448         (sub-gc)
449         (set-auto-gc-trigger *gc-trigger*))))