release, will be tagged as sbcl_1_0_27
[sbcl/tcr.git] / src / code / gc.lisp
blob8a8fe4612fcb0261f9f2ffabf26d5bf12144984d
1 ;;;; garbage collection and allocation-related code
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.
12 (in-package "SB!KERNEL")
14 ;;;; DYNAMIC-USAGE and friends
16 (declaim (special sb!vm:*read-only-space-free-pointer*
17 sb!vm:*static-space-free-pointer*))
19 (eval-when (:compile-toplevel :execute)
20 (sb!xc:defmacro def-c-var-fun (lisp-fun c-var-name)
21 `(defun ,lisp-fun ()
22 (sb!alien:extern-alien ,c-var-name (sb!alien:unsigned 32)))))
24 #!-sb-fluid
25 (declaim (inline current-dynamic-space-start))
26 #!+gencgc
27 (defun current-dynamic-space-start () sb!vm:dynamic-space-start)
28 #!-gencgc
29 (def-c-var-fun current-dynamic-space-start "current_dynamic_space")
31 #!-sb-fluid
32 (declaim (inline dynamic-usage))
33 #!+gencgc
34 (def-c-var-fun dynamic-usage "bytes_allocated")
35 #!-gencgc
36 (defun dynamic-usage ()
37 (the (unsigned-byte 32)
38 (- (sb!sys:sap-int (sb!c::dynamic-space-free-pointer))
39 (current-dynamic-space-start))))
41 (defun static-space-usage ()
42 (- (* sb!vm:*static-space-free-pointer* sb!vm:n-word-bytes)
43 sb!vm:static-space-start))
45 (defun read-only-space-usage ()
46 (- (* sb!vm::*read-only-space-free-pointer* sb!vm:n-word-bytes)
47 sb!vm:read-only-space-start))
49 (defun control-stack-usage ()
50 #!-stack-grows-downward-not-upward
51 (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
52 (sb!sys:sap-int (sb!di::descriptor-sap sb!vm:*control-stack-start*)))
53 #!+stack-grows-downward-not-upward
54 (- (sb!sys:sap-int (sb!di::descriptor-sap sb!vm:*control-stack-end*))
55 (sb!sys:sap-int (sb!c::control-stack-pointer-sap))))
57 (defun binding-stack-usage ()
58 (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
59 (sb!sys:sap-int (sb!di::descriptor-sap sb!vm:*binding-stack-start*))))
61 ;;;; ROOM
63 (defun room-minimal-info ()
64 (format t "Dynamic space usage is: ~10:D bytes.~%" (dynamic-usage))
65 (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
66 (format t "Static space usage is: ~10:D bytes.~%" (static-space-usage))
67 (format t "Control stack usage is: ~10:D bytes.~%" (control-stack-usage))
68 (format t "Binding stack usage is: ~10:D bytes.~%" (binding-stack-usage))
69 #!+sb-thread
70 (format t
71 "Control and binding stack usage is for the current thread only.~%")
72 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
73 *gc-inhibit*))
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))
82 (defun room-maximal-info ()
83 ;; FIXME: SB!VM:INSTANCE-USAGE calls suppressed until bug 344 is fixed
84 (room-intermediate-info)
85 ;; old way, could be restored when bug 344 fixed:
86 ;;x (room-minimal-info)
87 ;;x (sb!vm:memory-usage :count-spaces '(:static :dynamic))
88 ;;x (sb!vm:instance-usage :dynamic :top-n 10)
89 ;;x (sb!vm:instance-usage :static :top-n 10)
92 (defun room (&optional (verbosity :default))
93 #!+sb-doc
94 "Print to *STANDARD-OUTPUT* information about the state of internal
95 storage and its management. The optional argument controls the
96 verbosity of output. If it is T, ROOM prints out a maximal amount of
97 information. If it is NIL, ROOM prints out a minimal amount of
98 information. If it is :DEFAULT or it is not supplied, ROOM prints out
99 an intermediate amount of information."
100 (fresh-line)
101 (ecase verbosity
102 ((t)
103 (room-maximal-info))
104 ((nil)
105 (room-minimal-info))
106 (:default
107 (room-intermediate-info)))
108 (values))
110 ;;;; GET-BYTES-CONSED
112 ;;; the total number of bytes freed so far (including any freeing
113 ;;; which goes on in PURIFY)
115 ;;; (We save this so that we can calculate the total number of bytes
116 ;;; ever allocated by adding this to the number of bytes currently
117 ;;; allocated and never freed.)
118 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
119 (defvar *n-bytes-freed-or-purified* 0)
120 (defun gc-reinit ()
121 (setq *gc-inhibit* nil)
122 (gc)
123 (setf *n-bytes-freed-or-purified* 0
124 *gc-run-time* 0
125 ;; See comment in interr.lisp
126 *heap-exhausted-error-condition* (make-condition 'heap-exhausted-error)))
128 (declaim (ftype (sfunction () 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*))
140 ;;;; GC hooks
142 (defvar *after-gc-hooks* nil
143 "Called after each garbage collection, except for garbage collections
144 triggered during thread exits. In a multithreaded environment these hooks may
145 run in any thread.")
148 ;;;; internal GC
150 (sb!alien:define-alien-routine collect-garbage sb!alien:int
151 (#!+gencgc last-gen #!-gencgc ignore sb!alien:int))
153 #!+sb-thread
154 (progn
155 (sb!alien:define-alien-routine gc-stop-the-world sb!alien:void)
156 (sb!alien:define-alien-routine gc-start-the-world sb!alien:void))
157 #!-sb-thread
158 (progn
159 (defun gc-stop-the-world ())
160 (defun gc-start-the-world ()))
163 ;;;; SUB-GC
165 ;;; SUB-GC does a garbage collection. This is called from three places:
166 ;;; (1) The C runtime will call here when it detects that we've consed
167 ;;; enough to exceed the gc trigger threshold. This is done in
168 ;;; alloc() for gencgc or interrupt_maybe_gc() for cheneygc
169 ;;; (2) The user may request a collection using GC, below
170 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
171 ;;; *NEED-TO-COLLECT-GARBAGE* is true
173 ;;; This is different from the behaviour in 0.7 and earlier: it no
174 ;;; longer decides whether to GC based on thresholds. If you call
175 ;;; SUB-GC you will definitely get a GC either now or when the
176 ;;; WITHOUT-GCING is over
178 ;;; For GENCGC all generations < GEN will be GC'ed.
180 (defvar *already-in-gc* (sb!thread:make-mutex :name "GC lock"))
182 ;;; A unique GC id. This is supplied for code that needs to detect
183 ;;; whether a GC has happened since some earlier point in time. For
184 ;;; example:
186 ;;; (let ((epoch *gc-epoch*))
187 ;;; ...
188 ;;; (unless (eql epoch *gc-epoch)
189 ;;; ....))
191 ;;; This isn't just a fixnum counter since then we'd have theoretical
192 ;;; problems when exactly 2^29 GCs happen between epoch
193 ;;; comparisons. Unlikely, but the cost of using a cons instead is too
194 ;;; small to measure. -- JES, 2007-09-30
195 (declaim (type cons *gc-epoch*))
196 (defvar *gc-epoch* (cons nil nil))
198 (defun sub-gc (&key (gen 0))
199 (cond (*gc-inhibit*
200 (setf *gc-pending* t)
201 nil)
203 (without-interrupts
204 (setf *gc-pending* :in-progress)
205 ;; Tricks to to prevent triggerring a recursive gc. This is
206 ;; like a WITHOUT-GCING inside the lock except that we
207 ;; cannot call MAYBE-HANDLE-PENDING-GC at the end, because
208 ;; that would lead to a recursive attempt on the lock. In
209 ;; case you are wondering, wrapping the lock in a
210 ;; WITHOUT-GCING would also deadlock. The
211 ;; *IN-WITHOUT-GCING* part is used to tell the runtime that
212 ;; it's ok to have a pending gc even though *GC-INHIBIT* is
213 ;; NIL.
215 ;; Now, if GET-MUTEX did not cons, that would be enough.
216 ;; Because it does, we need the :IN-PROGRESS bit above to
217 ;; tell the runtime not to trigger gcs.
218 (let ((sb!impl::*in-without-gcing* t)
219 (sb!impl::*deadline* nil)
220 (sb!impl::*deadline-seconds* nil))
221 (sb!thread:with-mutex (*already-in-gc*)
222 (let ((*gc-inhibit* t))
223 (let ((old-usage (dynamic-usage))
224 (new-usage 0))
225 (unsafe-clear-roots)
226 (gc-stop-the-world)
227 (let ((start-time (get-internal-run-time)))
228 (collect-garbage gen)
229 (setf *gc-epoch* (cons nil nil))
230 (incf *gc-run-time*
231 (- (get-internal-run-time) start-time)))
232 (setf *gc-pending* nil
233 new-usage (dynamic-usage))
234 #!+sb-thread
235 (assert (not *stop-for-gc-pending*))
236 (gc-start-the-world)
237 ;; In a multithreaded environment the other threads
238 ;; will see *n-b-f-o-p* change a little late, but
239 ;; that's OK.
240 (let ((freed (- old-usage new-usage)))
241 ;; GENCGC occasionally reports negative here, but
242 ;; the current belief is that it is part of the
243 ;; normal order of things and not a bug.
244 (when (plusp freed)
245 (incf *n-bytes-freed-or-purified* freed)))))))
246 ;; While holding the mutex we were protected from
247 ;; SIG_STOP_FOR_GC and recursive GCs. Now, in order to
248 ;; preserve the invariant (*GC-PENDING* ->
249 ;; pseudo-atomic-interrupted or *GC-INHIBIT*), let's check
250 ;; explicitly for a pending gc before interrupts are
251 ;; enabled again.
252 (maybe-handle-pending-gc))
253 t)))
255 (defun post-gc ()
256 ;; Outside the mutex, interrupts may be enabled: these may cause
257 ;; another GC. FIXME: it can potentially exceed maximum interrupt
258 ;; nesting by triggering GCs.
260 ;; Can that be avoided by having the finalizers and hooks run only
261 ;; from the outermost SUB-GC? If the nested GCs happen in interrupt
262 ;; handlers that's not enough.
264 ;; KLUDGE: Don't run the hooks in GC's if:
266 ;; A) this thread is dying, so that user-code never runs with
267 ;; (thread-alive-p *current-thread*) => nil
269 ;; B) interrupts are disabled somewhere up the call chain since we
270 ;; don't want to run user code in such a case.
272 ;; The long-term solution will be to keep a separate thread for
273 ;; finalizers and after-gc hooks.
274 (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
275 (when *allow-with-interrupts*
276 (with-interrupts
277 (run-pending-finalizers)
278 (call-hooks "after-GC" *after-gc-hooks* :on-error :warn)))))
280 ;;; This is the user-advertised garbage collection function.
281 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
282 #!+(and sb-doc gencgc)
283 "Initiate a garbage collection. GEN controls the number of generations
284 to garbage collect."
285 #!+(and sb-doc (not gencgc))
286 "Initiate a garbage collection. GEN may be provided for compatibility with
287 generational garbage collectors, but is ignored in this implementation."
288 (when (sub-gc :gen (if full 6 gen))
289 (post-gc)))
291 (defun unsafe-clear-roots ()
292 ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
293 ;; as having these cons more then we have space left leads to huge
294 ;; badness.
295 (scrub-control-stack)
296 ;; Power cache of the bignum printer: drops overly large bignums and
297 ;; removes duplicate entries.
298 (scrub-power-cache)
299 ;; FIXME: CTYPE-OF-CACHE-CLEAR isn't thread-safe.
300 #!-sb-thread
301 (ctype-of-cache-clear))
304 ;;;; auxiliary functions
306 (defun bytes-consed-between-gcs ()
307 #!+sb-doc
308 "Return the amount of memory that will be allocated before the next garbage
309 collection is initiated. This can be set with SETF."
310 (sb!alien:extern-alien "bytes_consed_between_gcs"
311 (sb!alien:unsigned 32)))
313 (defun (setf bytes-consed-between-gcs) (val)
314 (declare (type index val))
315 (setf (sb!alien:extern-alien "bytes_consed_between_gcs"
316 (sb!alien:unsigned 32))
317 val))
319 (declaim (inline maybe-handle-pending-gc))
320 (defun maybe-handle-pending-gc ()
321 (when (and (not *gc-inhibit*)
322 (or #!+sb-thread *stop-for-gc-pending*
323 *gc-pending*))
324 (sb!unix::receive-pending-interrupt)))