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