0.7.1.46:
[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.05s0
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 ;;; On the X86, we store the GC trigger in a ``static'' symbol instead
194 ;;; of letting magic C code handle it. It gets initialized by the
195 ;;; startup code.
196 #!+x86
197 (defvar sb!vm::*internal-gc-trigger*)
198
199 ;;;; The following specials are used to control when garbage collection
200 ;;;; occurs.
201
202 ;;; When non-NIL, inhibits garbage collection.
203 (defvar *gc-inhibit*) ; initialized in cold init
204
205 ;;; This flag is used to prevent recursive entry into the garbage
206 ;;; collector.
207 (defvar *already-maybe-gcing*) ; initialized in cold init
208
209 ;;; When T, indicates that the dynamic usage has exceeded the value
210 ;;; *GC-TRIGGER*.
211 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
212 \f
213 (defun default-gc-notify-before (notify-stream bytes-in-use)
214   (declare (type stream notify-stream))
215   (format
216    notify-stream
217    "~&; GC is beginning with ~:D bytes in use at internal runtime ~:D.~%"
218    bytes-in-use
219    (get-internal-run-time))
220   (finish-output notify-stream))
221 (defparameter *gc-notify-before* #'default-gc-notify-before
222   #!+sb-doc
223   "This function bound to this variable is invoked before GC'ing (unless
224   *GC-NOTIFY-STREAM* is NIL) with the value of *GC-NOTIFY-STREAM* and
225   current amount of dynamic usage (in bytes). It should notify the
226   user that the system is going to GC.")
227
228 (defun default-gc-notify-after (notify-stream
229                                 bytes-retained
230                                 bytes-freed
231                                 new-trigger)
232   (declare (type stream notify-stream))
233   (format notify-stream
234           "~&; GC has finished with ~:D bytes in use (~:D bytes freed)~@
235            ; at internal runtime ~:D. The new GC trigger is ~:D bytes.~%"
236           bytes-retained
237           bytes-freed
238           (get-internal-run-time)
239           new-trigger)
240   (finish-output notify-stream))
241 (defparameter *gc-notify-after* #'default-gc-notify-after
242   #!+sb-doc
243   "The function bound to this variable is invoked after GC'ing with the
244 value of *GC-NOTIFY-STREAM*, the amount of dynamic usage (in bytes) now
245 free, the number of bytes freed by the GC, and the new GC trigger
246 threshold; or if *GC-NOTIFY-STREAM* is NIL, it's not invoked. The
247 function should notify the user that the system has finished GC'ing.")
248 \f
249 ;;;; internal GC
250
251 (sb!alien:define-alien-routine collect-garbage sb!alien:int
252   #!+gencgc (last-gen sb!alien:int))
253
254 (sb!alien:define-alien-routine set-auto-gc-trigger sb!alien:void
255   (dynamic-usage sb!alien:unsigned-long))
256
257 (sb!alien:define-alien-routine clear-auto-gc-trigger sb!alien:void)
258
259 ;;; This variable contains the function that does the real GC. This is
260 ;;; for low-level GC experimentation. Do not touch it if you do not
261 ;;; know what you are doing.
262 (defvar *internal-gc* #'collect-garbage)
263 \f
264 ;;;; SUB-GC
265
266 ;;; This is used to carefully invoke hooks.
267 (eval-when (:compile-toplevel :execute)
268   (sb!xc:defmacro carefully-funcall (function &rest args)
269     `(handler-case (funcall ,function ,@args)
270        (error (cond)
271               (warn "(FUNCALL ~S~{ ~S~}) lost:~%~A" ',function ',args cond)
272               nil))))
273
274 ;;; SUB-GC decides when and if to do a garbage collection. The FORCE-P
275 ;;; flags controls whether a GC should occur even if the dynamic usage
276 ;;; is not greater than *GC-TRIGGER*.
277 ;;;
278 ;;; For GENCGC all generations < GEN will be GC'ed.
279 (defun sub-gc (&key force-p (gen 0))
280   (/show0 "entering SUB-GC")
281   (unless *already-maybe-gcing*
282     (let* ((*already-maybe-gcing* t)
283            (start-time (get-internal-run-time))
284            (pre-gc-dynamic-usage (dynamic-usage))
285            ;; Currently we only check *SOFT-HEAP-LIMIT* at GC time,
286            ;; not for every allocation. That makes it cheap to do,
287            ;; even if it is a little ugly.
288            (soft-heap-limit-exceeded? (and *soft-heap-limit*
289                                            (> pre-gc-dynamic-usage
290                                               *soft-heap-limit*)))
291            (*soft-heap-limit* (if soft-heap-limit-exceeded?
292                                   (+ pre-gc-dynamic-usage
293                                      *bytes-consed-between-gcs*)
294                                   *soft-heap-limit*)))
295       (when soft-heap-limit-exceeded?
296         (cerror "Continue with GC."
297                 "soft heap limit exceeded (temporary new limit=~W)"
298                 *soft-heap-limit*))
299       (when (and *gc-trigger* (> pre-gc-dynamic-usage *gc-trigger*))
300         (setf *need-to-collect-garbage* t))
301       (when (or force-p
302                 (and *need-to-collect-garbage* (not *gc-inhibit*)))
303         ;; KLUDGE: Wow, we really mask interrupts all the time we're
304         ;; collecting garbage? That seems like a long time.. -- WHN 19991129
305         (without-interrupts
306          ;; FIXME: We probably shouldn't do this evil thing to
307          ;; *STANDARD-OUTPUT* in a binding which is wrapped around
308          ;; calls to user-settable GC hook functions.
309           (let ((*standard-output* *terminal-io*))
310             (when *gc-notify-stream*
311               (if (streamp *gc-notify-stream*)
312                   (carefully-funcall *gc-notify-before*
313                                      *gc-notify-stream*
314                                      pre-gc-dynamic-usage)
315                   (warn
316                    "*GC-NOTIFY-STREAM* is set, but not a STREAM -- ignored.")))
317             (dolist (hook *before-gc-hooks*)
318               (carefully-funcall hook))
319             (when *gc-trigger*
320               (clear-auto-gc-trigger))
321             (let* (;; We do DYNAMIC-USAGE once more here in order to
322                    ;; get a more accurate measurement of the space
323                    ;; actually freed, since the messing around, e.g.
324                    ;; GC-notify stuff, since the DYNAMIC-USAGE which
325                    ;; triggered GC could've done a fair amount of
326                    ;; consing.)
327                    (pre-internal-gc-dynamic-usage (dynamic-usage))
328                    (ignore-me
329                     #!-gencgc (funcall *internal-gc*)
330                     ;; FIXME: This EQ test is pretty gross. Among its other
331                     ;; nastinesses, it looks as though it could break if we
332                     ;; recompile COLLECT-GARBAGE. We should probably just
333                     ;; straighten out the interface so that all *INTERNAL-GC*
334                     ;; functions accept a GEN argument (and then the
335                     ;; non-generational ones just ignore it).
336                     #!+gencgc (if (eq *internal-gc* #'collect-garbage)
337                                   (funcall *internal-gc* gen)
338                                   (funcall *internal-gc*)))
339                    (post-gc-dynamic-usage (dynamic-usage))
340                    (n-bytes-freed (- pre-internal-gc-dynamic-usage
341                                      post-gc-dynamic-usage))
342                    ;; In sbcl-0.6.12.39, the raw N-BYTES-FREED from
343                    ;; GENCGC could sometimes be substantially negative
344                    ;; (e.g. -5872). I haven't looked into what causes
345                    ;; that, but I suspect it has to do with
346                    ;; fluctuating inefficiency in the way that the
347                    ;; GENCGC packs things into page boundaries.
348                    ;; Bumping the raw result up to 0 is a little ugly,
349                    ;; but shouldn't be a problem, and it's even
350                    ;; possible to sort of justify it: the packing
351                    ;; inefficiency which has caused (DYNAMIC-USAGE) to
352                    ;; grow is effectively consing, or at least
353                    ;; overhead of consing, so it's sort of correct to
354                    ;; add it to the running total of consing. ("Man
355                    ;; isn't a rational animal, he's a rationalizing
356                    ;; animal.":-) -- WHN 2001-06-23
357                    (eff-n-bytes-freed (max 0 n-bytes-freed)))
358               (declare (ignore ignore-me))
359               (/show0 "got (DYNAMIC-USAGE) and EFF-N-BYTES-FREED")
360               (incf *n-bytes-freed-or-purified*
361                     eff-n-bytes-freed)
362               (/show0 "clearing *NEED-TO-COLLECT-GARBAGE*")
363               (setf *need-to-collect-garbage* nil)
364               (/show0 "calculating NEW-GC-TRIGGER")
365               (let ((new-gc-trigger (+ post-gc-dynamic-usage
366                                        *bytes-consed-between-gcs*)))
367                 (/show0 "setting *GC-TRIGGER*")
368                 (setf *gc-trigger* new-gc-trigger))
369               (/show0 "calling SET-AUTO-GC-TRIGGER")
370               (set-auto-gc-trigger *gc-trigger*)
371               (dolist (hook *after-gc-hooks*)
372                 (/show0 "doing a hook from *AFTER-GC--HOOKS*")
373                 ;; FIXME: This hook should be called with the same
374                 ;; kind of information as *GC-NOTIFY-AFTER*. In
375                 ;; particular, it would be nice for the hook function
376                 ;; to be able to adjust *GC-TRIGGER* intelligently to
377                 ;; e.g. 108% of total memory usage.
378                 (carefully-funcall hook))
379               (when *gc-notify-stream*
380                 (if (streamp *gc-notify-stream*)
381                     (carefully-funcall *gc-notify-after*
382                                        *gc-notify-stream*
383                                        post-gc-dynamic-usage
384                                        eff-n-bytes-freed
385                                        *gc-trigger*)
386                     (warn
387                      "*GC-NOTIFY-STREAM* is set, but not a stream -- ignored.")))))
388           (scrub-control-stack)))       ;XXX again?  we did this from C ...
389       (incf *gc-run-time* (- (get-internal-run-time)
390                              start-time))))
391   ;; FIXME: should probably return (VALUES), here and in RETURN-FROM
392   nil)
393
394 ;;; This routine is called by the allocation miscops to decide whether
395 ;;; a GC should occur. The argument, OBJECT, is the newly allocated
396 ;;; object which must be returned to the caller.
397 (defun maybe-gc (&optional object)
398   (sub-gc)
399   object)
400
401 ;;; This is the user-advertised garbage collection function.
402 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
403   #!+(and sb-doc gencgc)
404   "Initiate a garbage collection. GEN controls the number of generations
405   to garbage collect."
406   #!+(and sb-doc (not gencgc))
407   "Initiate a garbage collection. GEN may be provided for compatibility with
408   generational garbage collectors, but is ignored in this implementation."
409   (sub-gc :force-p t :gen (if full 6 gen)))
410
411 \f
412 ;;;; auxiliary functions
413
414 (defun bytes-consed-between-gcs ()
415   #!+sb-doc
416   "Return the amount of memory that will be allocated before the next garbage
417    collection is initiated. This can be set with SETF."
418   *bytes-consed-between-gcs*)
419 (defun (setf bytes-consed-between-gcs) (val)
420   ;; FIXME: Shouldn't this (and the DECLAIM for the underlying variable)
421   ;; be for a strictly positive number type, e.g.
422   ;; (AND (INTEGER 1) FIXNUM)?
423   (declare (type index val))
424   (let ((old *bytes-consed-between-gcs*))
425     (setf *bytes-consed-between-gcs* val)
426     (when *gc-trigger*
427       (setf *gc-trigger* (+ *gc-trigger* (- val old)))
428       (cond ((<= (dynamic-usage) *gc-trigger*)
429              (clear-auto-gc-trigger)
430              (set-auto-gc-trigger *gc-trigger*))
431             (t
432              ;; FIXME: If SCRUB-CONTROL-STACK is required here, why
433              ;; isn't it built into SUB-GC? And *is* it required here?
434              (sb!sys:scrub-control-stack)
435              (sub-gc)))))
436   val)
437
438 (defun gc-on ()
439   #!+sb-doc
440   "Enable the garbage collector."
441   (setq *gc-inhibit* nil)
442   (when *need-to-collect-garbage*
443     (sub-gc))
444   nil)
445
446 (defun gc-off ()
447   #!+sb-doc
448   "Disable the garbage collector."
449   (setq *gc-inhibit* t)
450   nil)
451 \f
452 ;;;; initialization stuff
453
454 (defun gc-reinit ()
455   (when *gc-trigger*
456     (if (< *gc-trigger* (dynamic-usage))
457         (sub-gc)
458         (set-auto-gc-trigger *gc-trigger*))))