0.8.21.23: rewritten SUB-GC & finalization
[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   ;; FIXME: SB!VM:INSTANCE-USAGE calls suppressed until bug 344 is fixed
87   (room-intermediate-info)
88   ;; old way, could be restored when bug 344 fixed:
89   ;;x (room-minimal-info)
90   ;;x (sb!vm:memory-usage :count-spaces '(:static :dynamic))
91   ;;x (sb!vm:instance-usage :dynamic :top-n 10)
92   ;;x (sb!vm:instance-usage :static :top-n 10)
93   )
94
95 (defun room (&optional (verbosity :default))
96   #!+sb-doc
97   "Print to *STANDARD-OUTPUT* information about the state of internal
98   storage and its management. The optional argument controls the
99   verbosity of output. If it is T, ROOM prints out a maximal amount of
100   information. If it is NIL, ROOM prints out a minimal amount of
101   information. If it is :DEFAULT or it is not supplied, ROOM prints out
102   an intermediate amount of information."
103   (fresh-line)
104   (ecase verbosity
105     ((t)
106      (room-maximal-info))
107     ((nil)
108      (room-minimal-info))
109     (:default
110      (room-intermediate-info)))
111   (values))
112 \f
113 ;;;; GET-BYTES-CONSED
114
115 ;;; the total number of bytes freed so far (including any freeing
116 ;;; which goes on in PURIFY)
117 ;;;
118 ;;; (We save this so that we can calculate the total number of bytes
119 ;;; ever allocated by adding this to the number of bytes currently
120 ;;; allocated and never freed.)
121 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
122 (defvar *n-bytes-freed-or-purified* 0)
123 (defun gc-reinit ()
124   (gc-on)
125   (gc)
126   (setf *n-bytes-freed-or-purified* 0))
127
128 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
129 (defun get-bytes-consed ()
130   #!+sb-doc
131   "Return the number of bytes consed since the program began. Typically
132 this result will be a consed bignum, so if you have an application (e.g.
133 profiling) which can't tolerate the overhead of consing bignums, you'll
134 probably want either to hack in at a lower level (as the code in the
135 SB-PROFILE package does), or to design a more microefficient interface
136 and submit it as a patch."
137   (+ (dynamic-usage)
138      *n-bytes-freed-or-purified*))
139 \f
140 ;;;; GC hooks
141
142 (defvar *after-gc-hooks* nil
143   "Called after each garbage collection. In a multithreaded
144 environment these hooks may run in any thread.")
145
146 ;;;; The following specials are used to control when garbage
147 ;;;; collection occurs.
148
149 ;;; When the dynamic usage increases beyond this amount, the system
150 ;;; notes that a garbage collection needs to occur by setting
151 ;;; *NEED-TO-COLLECT-GARBAGE* to T. It starts out as NIL meaning
152 ;;; nobody has figured out what it should be yet.
153 ;;;
154 ;;; FIXME: *GC-TRIGGER* seems to be denominated in bytes, not words.
155 ;;; And limiting it to INDEX is fairly reasonable in order to avoid
156 ;;; bignum arithmetic on every allocation, and to minimize the need
157 ;;; for thought about weird gotchas of the GC-control mechanism itself
158 ;;; consing as it operates. But as of sbcl-0.7.5, 512Mbytes of memory
159 ;;; costs $54.95 at Fry's in Dallas but cheap consumer 64-bit machines
160 ;;; are still over the horizon, so gratuitously limiting our heap size
161 ;;; to FIXNUM bytes seems fairly stupid. It'd be reasonable to
162 ;;; (1) allow arbitrary UNSIGNED-BYTE values of *GC-TRIGGER*, or
163 ;;; (2) redenominate this variable in words instead of bytes, postponing
164 ;;;     the problem to heaps which exceed 50% of the machine's address
165 ;;;     space, or even
166 ;;; (3) redemoninate this variable in CONS-sized two-word units,
167 ;;;     allowing it to cover the entire memory space at the price of
168 ;;;     possible loss of clarity.
169 ;;; (And whatever is done, it'd also be good to rename the variable so
170 ;;; that it's clear what unit it's denominated in.)
171 (declaim (type (or index null) *gc-trigger*))
172 (defvar *gc-trigger* nil)
173
174 ;;; When T, indicates that a GC should have happened but did not due to 
175 ;;; *GC-INHIBIT*. 
176 (defvar *need-to-collect-garbage* nil) ; initialized in cold init
177 \f
178 ;;;; internal GC
179
180 (sb!alien:define-alien-routine collect-garbage sb!alien:int
181   (#!+gencgc last-gen #!-gencgc ignore sb!alien:int))
182
183 #!+sb-thread
184 (progn
185   (sb!alien:define-alien-routine gc-stop-the-world sb!alien:void)
186   (sb!alien:define-alien-routine gc-start-the-world sb!alien:void))
187 #!-sb-thread
188 (progn
189   (defun gc-stop-the-world ())
190   (defun gc-start-the-world ()))
191
192 \f
193 ;;;; SUB-GC
194
195 ;;; SUB-GC does a garbage collection.  This is called from three places:
196 ;;; (1) The C runtime will call here when it detects that we've consed 
197 ;;;     enough to exceed the gc trigger threshold.  This is done in
198 ;;;     alloc() for gencgc or interrupt_maybe_gc() for cheneygc
199 ;;; (2) The user may request a collection using GC, below
200 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
201 ;;;     *NEED-TO-COLLECT-GARBAGE* is true
202 ;;;
203 ;;; This is different from the behaviour in 0.7 and earlier: it no
204 ;;; longer decides whether to GC based on thresholds.  If you call
205 ;;; SUB-GC you will definitely get a GC either now or when the
206 ;;; WITHOUT-GCING is over
207
208 ;;; For GENCGC all generations < GEN will be GC'ed.
209
210 (defvar *already-in-gc* 
211   (sb!thread:make-mutex :name "GC lock") "ID of thread running SUB-GC")
212
213 (defun sub-gc (&key (gen 0))
214   (unless (eql (sb!thread:current-thread-id)
215                (sb!thread::mutex-value *already-in-gc*))
216     (setf *need-to-collect-garbage* t)
217     (when (zerop *gc-inhibit*)
218       (sb!thread:with-mutex (*already-in-gc*)
219         (let ((old-usage (dynamic-usage))
220               (new-usage 0))
221           (unsafe-clear-roots)
222           ;; We need to disable interrupts for GC, but we also want
223           ;; to run as little as possible without them.
224           (without-interrupts
225             (gc-stop-the-world)       
226             (collect-garbage gen)
227             (setf *need-to-collect-garbage* nil
228                   new-usage (dynamic-usage))
229             (gc-start-the-world))
230           ;; Interrupts re-enabled, but still inside the mutex.
231           ;; In a multithreaded environment the other threads will
232           ;; see *n-b-f-o-p* change a little late, but that's OK.
233           (let ((freed (- old-usage new-usage)))
234             ;; GENCGC occasionally reports negative here, but the
235             ;; current belief is that it is part of the normal order
236             ;; of things and not a bug.
237             (when (plusp freed)
238               (incf *n-bytes-freed-or-purified* freed)))
239           (sb!thread::reap-dead-threads)))
240       ;; Outside the mutex, these may cause another GC.
241       (run-pending-finalizers)
242       (dolist (hook *after-gc-hooks*)
243         (handler-case
244             (funcall hook)
245           (error (c)
246             (warn "Error calling after GC hook ~S:~%  ~S" hook c)))))))
247
248 ;;; This is the user-advertised garbage collection function.
249 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
250   #!+(and sb-doc gencgc)
251   "Initiate a garbage collection. GEN controls the number of generations
252   to garbage collect."
253   #!+(and sb-doc (not gencgc))
254   "Initiate a garbage collection. GEN may be provided for compatibility with
255   generational garbage collectors, but is ignored in this implementation."
256   (sub-gc :gen (if full 6 gen)))
257
258 (defun unsafe-clear-roots ()
259   ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
260   ;; as having these cons more then we have space left leads to huge
261   ;; badness.
262   (scrub-control-stack)
263   ;; FIXME: CTYPE-OF-CACHE-CLEAR isn't thread-safe.
264   #!-sb-thread
265   (ctype-of-cache-clear))
266
267 \f
268 ;;;; auxiliary functions
269
270 (defun bytes-consed-between-gcs ()
271   #!+sb-doc
272   "Return the amount of memory that will be allocated before the next garbage
273    collection is initiated. This can be set with SETF."
274   (sb!alien:extern-alien "bytes_consed_between_gcs"
275                          (sb!alien:unsigned 32)))
276
277 (defun (setf bytes-consed-between-gcs) (val)
278   (declare (type index val))
279   (setf (sb!alien:extern-alien "bytes_consed_between_gcs"
280                                (sb!alien:unsigned 32))
281         val))
282
283 ;;; FIXME: Aren't these utterly wrong if called inside WITHOUT-GCING?
284 ;;; Unless something that works there too can be deviced this fact
285 ;;; should be documented.
286 (defun gc-on ()
287   #!+sb-doc
288   "Enable the garbage collector."
289   (setq *gc-inhibit* 0)
290   (when *need-to-collect-garbage*
291     (sub-gc))
292   nil)
293
294 (defun gc-off ()
295   #!+sb-doc
296   "Disable the garbage collector."
297   (setq *gc-inhibit* 1)
298   nil)
299