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