0.7.1.21:
[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*
144   #+gencgc (* 4 (expt 10 6))
145   ;; Stop-and-copy GC is really really slow when used too often. CSR
146   ;; reported that even on his old 64 Mb SPARC, 20 Mb is much faster
147   ;; than 4 Mb when rebuilding SBCL ca. 0.7.1. For modern machines
148   ;; with >> 128 Mb memory, the optimum could be significantly more
149   ;; than this, but at least 20 Mb should be better than 4 Mb.
150   #-gencgc (* 20 (expt 10 6)))
151 (declaim (type index *bytes-consed-between-gcs*))
152
153 ;;;; GC hooks
154
155 (defvar *before-gc-hooks* nil ; actually initialized in cold init
156   #!+sb-doc
157   "A list of functions that are called before garbage collection occurs.
158   The functions should take no arguments.")
159
160 (defvar *after-gc-hooks* nil ; actually initialized in cold init
161   #!+sb-doc
162   "A list of functions that are called after garbage collection occurs.
163   The functions should take no arguments.")
164
165 (defvar *gc-notify-stream* nil ; (actually initialized in cold init)
166   #!+sb-doc
167   "When non-NIL, this must be a STREAM; and the functions bound to
168   *GC-NOTIFY-BEFORE* and *GC-NOTIFY-AFTER* are called with the
169   STREAM value before and after a garbage collection occurs
170   respectively.")
171
172 (defvar *gc-run-time* 0
173   #!+sb-doc
174   "the total CPU time spent doing garbage collection (as reported by
175    GET-INTERNAL-RUN-TIME)")
176 (declaim (type index *gc-run-time*))
177
178 ;;; a limit to help catch programs which allocate too much memory,
179 ;;; since a hard heap overflow is so hard to recover from
180 (declaim (type (or unsigned-byte null) *soft-heap-limit*))
181 (defvar *soft-heap-limit* nil)
182
183 ;;; When the dynamic usage increases beyond this amount, the system
184 ;;; notes that a garbage collection needs to occur by setting
185 ;;; *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
186 ;;; nobody has figured out what it should be yet.
187 (defvar *gc-trigger* nil)
188
189 (declaim (type (or index null) *gc-trigger*))
190
191 ;;; On the X86, we store the GC trigger in a ``static'' symbol instead
192 ;;; of letting magic C code handle it. It gets initialized by the
193 ;;; startup code.
194 #!+x86
195 (defvar sb!vm::*internal-gc-trigger*)
196
197 ;;;; The following specials are used to control when garbage collection
198 ;;;; occurs.
199
200 ;;; When non-NIL, inhibits garbage collection.
201 (defvar *gc-inhibit*) ; initialized in cold init
202
203 ;;; This flag is used to prevent recursive entry into the garbage
204 ;;; collector.
205 (defvar *already-maybe-gcing*) ; initialized in cold init
206
207 ;;; When T, indicates that the dynamic usage has exceeded the value
208 ;;; *GC-TRIGGER*.
209 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
210 \f
211 (defun default-gc-notify-before (notify-stream bytes-in-use)
212   (declare (type stream notify-stream))
213   (format
214    notify-stream
215    "~&; GC is beginning with ~:D bytes in use at internal runtime ~:D.~%"
216    bytes-in-use
217    (get-internal-run-time))
218   (finish-output notify-stream))
219 (defparameter *gc-notify-before* #'default-gc-notify-before
220   #!+sb-doc
221   "This function bound to this variable is invoked before GC'ing (unless
222   *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
223   current amount of dynamic usage (in bytes). It should notify the
224   user that the system is going to GC.")
225
226 (defun default-gc-notify-after (notify-stream
227                                 bytes-retained
228                                 bytes-freed
229                                 new-trigger)
230   (declare (type stream notify-stream))
231   (format notify-stream
232           "~&; GC has finished with ~:D bytes in use (~:D bytes freed)~@
233            ; at internal runtime ~:D. The new GC trigger is ~:D bytes.~%"
234           bytes-retained
235           bytes-freed
236           (get-internal-run-time)
237           new-trigger)
238   (finish-output notify-stream))
239 (defparameter *gc-notify-after* #'default-gc-notify-after
240   #!+sb-doc
241   "The function bound to this variable is invoked after GC'ing with the
242 value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in bytes) now
243 free, the number of bytes freed by the GC, and the new GC trigger
244 threshold; or if *GC-NOTIFY-STREAM* is NIL, it's not invoked. The
245 function should notify the user that the system has finished GC'ing.")
246 \f
247 ;;;; internal GC
248
249 (sb!alien:define-alien-routine collect-garbage sb!alien:int
250   #!+gencgc (last-gen sb!alien:int))
251
252 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
253   (dynamic-usage sb!alien:unsigned-long))
254
255 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien: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 ;;; This is 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. The FORCE-P
273 ;;; flags controls whether a GC should occur even if the dynamic usage
274 ;;; 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-dynamic-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-dynamic-usage
288                                               *soft-heap-limit*)))
289            (*soft-heap-limit* (if soft-heap-limit-exceeded?
290                                   (+ pre-gc-dynamic-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=~W)"
296                 *soft-heap-limit*))
297       (when (and *gc-trigger* (> pre-gc-dynamic-usage *gc-trigger*))
298         (setf *need-to-collect-garbage* t))
299       (when (or force-p
300                 (and *need-to-collect-garbage* (not *gc-inhibit*)))
301         ;; KLUDGE: Wow, we really mask interrupts all the time we're
302         ;; collecting garbage? That seems like a long time.. -- WHN 19991129
303         (without-interrupts
304          ;; FIXME: We probably shouldn't do this evil thing to
305          ;; *STANDARD-OUTPUT* in a binding which is wrapped around
306          ;; calls to user-settable GC hook functions.
307           (let ((*standard-output* *terminal-io*))
308             (when *gc-notify-stream*
309               (if (streamp *gc-notify-stream*)
310                   (carefully-funcall *gc-notify-before*
311                                      *gc-notify-stream*
312                                      pre-gc-dynamic-usage)
313                   (warn
314                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
315             (dolist (hook *before-gc-hooks*)
316               (carefully-funcall hook))
317             (when *gc-trigger*
318               (clear-auto-gc-trigger))
319             (let* (;; We do DYNAMIC-USAGE once more here in order to
320                    ;; get a more accurate measurement of the space
321                    ;; actually freed, since the messing around, e.g.
322                    ;; GC-notify stuff, since the DYNAMIC-USAGE which
323                    ;; triggered GC could've done a fair amount of
324                    ;; consing.)
325                    (pre-internal-gc-dynamic-usage (dynamic-usage))
326                    (ignore-me
327                     #!-gencgc (funcall *internal-gc*)
328                     ;; FIXME: This EQ test is pretty gross. Among its other
329                     ;; nastinesses, it looks as though it could break if we
330                     ;; recompile COLLECT-GARBAGE. We should probably just
331                     ;; straighten out the interface so that all *INTERNAL-GC*
332                     ;; functions accept a GEN argument (and then the
333                     ;; non-generational ones just ignore it).
334                     #!+gencgc (if (eq *internal-gc* #'collect-garbage)
335                                   (funcall *internal-gc* gen)
336                                   (funcall *internal-gc*)))
337                    (post-gc-dynamic-usage (dynamic-usage))
338                    (n-bytes-freed (- pre-internal-gc-dynamic-usage
339                                      post-gc-dynamic-usage))
340                    ;; In sbcl-0.6.12.39, the raw N-BYTES-FREED from
341                    ;; GENCGC could sometimes be substantially negative
342                    ;; (e.g. -5872). I haven't looked into what causes
343                    ;; that, but I suspect it has to do with
344                    ;; fluctuating inefficiency in the way that the
345                    ;; GENCGC packs things into page boundaries.
346                    ;; Bumping the raw result up to 0 is a little ugly,
347                    ;; but shouldn't be a problem, and it's even
348                    ;; possible to sort of justify it: the packing
349                    ;; inefficiency which has caused (DYNAMIC-USAGE) to
350                    ;; grow is effectively consing, or at least
351                    ;; overhead of consing, so it's sort of correct to
352                    ;; add it to the running total of consing. ("Man
353                    ;; isn't a rational animal, he's a rationalizing
354                    ;; animal.":-) -- WHN 2001-06-23
355                    (eff-n-bytes-freed (max 0 n-bytes-freed)))
356               (declare (ignore ignore-me))
357               (/show0 "got (DYNAMIC-USAGE) and EFF-N-BYTES-FREED")
358               (incf *n-bytes-freed-or-purified*
359                     eff-n-bytes-freed)
360               (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
361               (setf *need-to-collect-garbage* nil)
362               (/show0 "calculating NEW-GC-TRIGGER")
363               (let ((new-gc-trigger (+ post-gc-dynamic-usage
364                                        *bytes-consed-between-gcs*)))
365                 (/show0 "setting *GC-TRIGGER*")
366                 (setf *gc-trigger* new-gc-trigger))
367               (/show0 "calling SET-AUTO-GC-TRIGGER")
368               (set-auto-gc-trigger *gc-trigger*)
369               (dolist (hook *after-gc-hooks*)
370                 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
371                 ;; FIXME: This hook should be called with the same
372                 ;; kind of information as *GC-NOTIFY-AFTER*. In
373                 ;; particular, it would be nice for the hook function
374                 ;; to be able to adjust *GC-TRIGGER* intelligently to
375                 ;; e.g. 108% of total memory usage.
376                 (carefully-funcall hook))
377               (when *gc-notify-stream*
378                 (if (streamp *gc-notify-stream*)
379                     (carefully-funcall *gc-notify-after*
380                                        *gc-notify-stream*
381                                        post-gc-dynamic-usage
382                                        eff-n-bytes-freed
383                                        *gc-trigger*)
384                     (warn
385                      "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
386           (scrub-control-stack)))       ;XXX again?  we did this from C ...
387       (incf *gc-run-time* (- (get-internal-run-time)
388                              start-time))))
389   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
390   nil)
391
392 ;;; This routine is called by the allocation miscops to decide whether
393 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
394 ;;; object which must be returned to the caller.
395 (defun maybe-gc (&optional object)
396   (sub-gc)
397   object)
398
399 ;;; This is the user-advertised garbage collection function.
400 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
401   #!+(and sb-doc gencgc)
402   "Initiate a garbage collection. GEN controls the number of generations
403   to garbage collect."
404   #!+(and sb-doc (not gencgc))
405   "Initiate a garbage collection. GEN may be provided for compatibility with
406   generational garbage collectors, but is ignored in this implementation."
407   (sub-gc :force-p t :gen (if full 6 gen)))
408
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              ;; FIXME: If SCRUB-CONTROL-STACK is required here, why
431              ;; isn't it built into SUB-GC? And *is* it required here?
432              (sb!sys:scrub-control-stack)
433              (sub-gc)))))
434   val)
435
436 (defun gc-on ()
437   #!+sb-doc
438   "Enable 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   "Disable the garbage collector."
447   (setq *gc-inhibit* t)
448   nil)
449 \f
450 ;;;; initialization stuff
451
452 (defun gc-reinit ()
453   (when *gc-trigger*
454     (if (< *gc-trigger* (dynamic-usage))
455         (sub-gc)
456         (set-auto-gc-trigger *gc-trigger*))))