Declare EXPLICIT-CHECK on CONCATENATE, MAKE-STRING, SET-PPRINT-DISPATCH.
[sbcl.git] / src / code / gc.lisp
blob4360017577aca2ccf7e50619d46e848e62e2a3cf
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 #!-sb-fluid
17 (declaim (inline current-dynamic-space-start))
18 #!+gencgc
19 (defun current-dynamic-space-start () sb!vm:dynamic-space-start)
20 #!-gencgc
21 (defun current-dynamic-space-start ()
22 (extern-alien "current_dynamic_space" unsigned-long))
24 #!-sb-fluid
25 (declaim (inline dynamic-usage))
26 #!+gencgc
27 (defun dynamic-usage ()
28 (extern-alien "bytes_allocated" os-vm-size-t))
29 #!-gencgc
30 (defun dynamic-usage ()
31 (truly-the word
32 (- (sap-int (sb!c::dynamic-space-free-pointer))
33 (current-dynamic-space-start))))
35 (defun static-space-usage ()
36 (- (ash sb!vm:*static-space-free-pointer* sb!vm:n-fixnum-tag-bits)
37 sb!vm:static-space-start))
39 (defun read-only-space-usage ()
40 (- (ash sb!vm::*read-only-space-free-pointer* sb!vm:n-fixnum-tag-bits)
41 sb!vm:read-only-space-start))
43 (defun control-stack-usage ()
44 #!-stack-grows-downward-not-upward
45 (- (sap-int (sb!c::control-stack-pointer-sap))
46 (sap-int (sb!di::descriptor-sap sb!vm:*control-stack-start*)))
47 #!+stack-grows-downward-not-upward
48 (- (sap-int (sb!di::descriptor-sap sb!vm:*control-stack-end*))
49 (sap-int (sb!c::control-stack-pointer-sap))))
51 (defun binding-stack-usage ()
52 (- (sap-int (sb!c::binding-stack-pointer-sap))
53 (sap-int (sb!di::descriptor-sap sb!vm:*binding-stack-start*))))
55 ;;;; ROOM
57 (defun room-minimal-info ()
58 (format t "Dynamic space usage is: ~10:D bytes.~%" (dynamic-usage))
59 (format t "Read-only space usage is: ~10:D bytes.~%" (read-only-space-usage))
60 (format t "Static space usage is: ~10:D bytes.~%" (static-space-usage))
61 (format t "Control stack usage is: ~10:D bytes.~%" (control-stack-usage))
62 (format t "Binding stack usage is: ~10:D bytes.~%" (binding-stack-usage))
63 #!+sb-thread
64 (format t
65 "Control and binding stack usage is for the current thread only.~%")
66 (format t "Garbage collection is currently ~:[enabled~;DISABLED~].~%"
67 *gc-inhibit*))
69 (defun room-intermediate-info ()
70 (room-minimal-info)
71 (sb!vm:memory-usage :count-spaces '(:dynamic)
72 :print-spaces t
73 :cutoff 0.05f0
74 :print-summary nil))
76 (defun room-maximal-info ()
77 ;; FIXME: SB!VM:INSTANCE-USAGE calls suppressed until bug 344 is fixed
78 (room-intermediate-info)
79 ;; old way, could be restored when bug 344 fixed:
80 ;;x (room-minimal-info)
81 ;;x (sb!vm:memory-usage :count-spaces '(:static :dynamic))
82 ;;x (sb!vm:instance-usage :dynamic :top-n 10)
83 ;;x (sb!vm:instance-usage :static :top-n 10)
86 (defun room (&optional (verbosity :default))
87 #!+sb-doc
88 "Print to *STANDARD-OUTPUT* information about the state of internal
89 storage and its management. The optional argument controls the
90 verbosity of output. If it is T, ROOM prints out a maximal amount of
91 information. If it is NIL, ROOM prints out a minimal amount of
92 information. If it is :DEFAULT or it is not supplied, ROOM prints out
93 an intermediate amount of information."
94 (fresh-line)
95 (ecase verbosity
96 ((t)
97 (room-maximal-info))
98 ((nil)
99 (room-minimal-info))
100 (:default
101 (room-intermediate-info)))
102 (values))
104 ;;;; GET-BYTES-CONSED
106 ;;; the total number of bytes freed so far (including any freeing
107 ;;; which goes on in PURIFY)
109 ;;; (We save this so that we can calculate the total number of bytes
110 ;;; ever allocated by adding this to the number of bytes currently
111 ;;; allocated and never freed.)
112 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
113 (defvar *n-bytes-freed-or-purified* 0)
114 (defun gc-reinit ()
115 (setq *gc-inhibit* nil)
116 (gc)
117 (setf *n-bytes-freed-or-purified* 0
118 *gc-run-time* 0
119 ;; See comment in interr.lisp
120 *heap-exhausted-error-condition* (make-condition 'heap-exhausted-error)))
122 (declaim (ftype (sfunction () unsigned-byte) get-bytes-consed))
123 (defun get-bytes-consed ()
124 #!+sb-doc
125 "Return the number of bytes consed since the program began. Typically
126 this result will be a consed bignum, so if you have an application (e.g.
127 profiling) which can't tolerate the overhead of consing bignums, you'll
128 probably want either to hack in at a lower level (as the code in the
129 SB-PROFILE package does), or to design a more microefficient interface
130 and submit it as a patch."
131 (+ (dynamic-usage)
132 *n-bytes-freed-or-purified*))
134 ;;;; GC hooks
136 (!defvar *after-gc-hooks* nil
137 #!+sb-doc
138 "Called after each garbage collection, except for garbage collections
139 triggered during thread exits. In a multithreaded environment these hooks may
140 run in any thread.")
143 ;;;; internal GC
145 (define-alien-routine collect-garbage int
146 (#!+gencgc last-gen #!-gencgc ignore int))
148 #!+sb-thread
149 (progn
150 (define-alien-routine gc-stop-the-world void)
151 (define-alien-routine gc-start-the-world void))
152 #!-sb-thread
153 (progn
154 (defun gc-stop-the-world ())
155 (defun gc-start-the-world ()))
157 #!+gencgc
158 (progn
159 (define-alien-variable ("gc_logfile" %gc-logfile) (* char))
160 (defun (setf gc-logfile) (pathname)
161 (let ((new (when pathname
162 (make-alien-string
163 (native-namestring (translate-logical-pathname pathname)
164 :as-file t))))
165 (old %gc-logfile))
166 (setf %gc-logfile new)
167 (when old
168 (free-alien old))
169 pathname))
170 (defun gc-logfile ()
171 #!+sb-doc
172 "Return the pathname used to log garbage collections. Can be SETF.
173 Default is NIL, meaning collections are not logged. If non-null, the
174 designated file is opened before and after each collection, and generation
175 statistics are appended to it."
176 (let ((val (cast %gc-logfile c-string)))
177 (when val
178 (native-pathname val))))
179 (declaim (inline dynamic-space-size))
180 (defun dynamic-space-size ()
181 #!+sb-doc
182 "Size of the dynamic space in bytes."
183 (extern-alien "dynamic_space_size" os-vm-size-t)))
185 ;;;; SUB-GC
187 ;;; SUB-GC does a garbage collection. This is called from three places:
188 ;;; (1) The C runtime will call here when it detects that we've consed
189 ;;; enough to exceed the gc trigger threshold. This is done in
190 ;;; alloc() for gencgc or interrupt_maybe_gc() for cheneygc
191 ;;; (2) The user may request a collection using GC, below
192 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
193 ;;; *NEED-TO-COLLECT-GARBAGE* is true
195 ;;; This is different from the behaviour in 0.7 and earlier: it no
196 ;;; longer decides whether to GC based on thresholds. If you call
197 ;;; SUB-GC you will definitely get a GC either now or when the
198 ;;; WITHOUT-GCING is over
200 ;;; For GENCGC all generations < GEN will be GC'ed.
202 (defvar *already-in-gc* (sb!thread:make-mutex :name "GC lock"))
204 ;;; A unique GC id. This is supplied for code that needs to detect
205 ;;; whether a GC has happened since some earlier point in time. For
206 ;;; example:
208 ;;; (let ((epoch *gc-epoch*))
209 ;;; ...
210 ;;; (unless (eql epoch *gc-epoch)
211 ;;; ....))
213 ;;; This isn't just a fixnum counter since then we'd have theoretical
214 ;;; problems when exactly 2^29 GCs happen between epoch
215 ;;; comparisons. Unlikely, but the cost of using a cons instead is too
216 ;;; small to measure. -- JES, 2007-09-30
217 (declaim (type cons *gc-epoch*))
218 (!defvar *gc-epoch* '(nil . nil))
220 (defun sub-gc (&key (gen 0))
221 (cond (*gc-inhibit*
222 (setf *gc-pending* t)
223 nil)
225 (flet ((perform-gc ()
226 ;; Called from WITHOUT-GCING and WITHOUT-INTERRUPTS
227 ;; after the world has been stopped, but it's an
228 ;; awkwardly long piece of code to nest so deeply.
229 (let ((old-usage (dynamic-usage))
230 (new-usage 0)
231 (start-time (get-internal-run-time)))
232 (collect-garbage gen)
233 (setf *gc-epoch* (cons nil nil))
234 (let ((run-time (- (get-internal-run-time) start-time)))
235 ;; KLUDGE: Sometimes we see the second getrusage() call
236 ;; return a smaller value than the first, which can
237 ;; lead to *GC-RUN-TIME* to going negative, which in
238 ;; turn is a type-error.
239 (when (plusp run-time)
240 (incf *gc-run-time* run-time)))
241 #!+sb-safepoint
242 (setf *stop-for-gc-pending* nil)
243 (setf *gc-pending* nil
244 new-usage (dynamic-usage))
245 #!+sb-thread
246 (assert (not *stop-for-gc-pending*))
247 (gc-start-the-world)
248 ;; In a multithreaded environment the other threads
249 ;; will see *n-b-f-o-p* change a little late, but
250 ;; that's OK.
251 ;; N.B. the outer without-gcing prevents this
252 ;; function from being entered, so no need for
253 ;; locking.
254 (let ((freed (- old-usage new-usage)))
255 ;; GENCGC occasionally reports negative here, but
256 ;; the current belief is that it is part of the
257 ;; normal order of things and not a bug.
258 (when (plusp freed)
259 (incf *n-bytes-freed-or-purified* freed))))))
260 (declare (inline perform-gc))
261 ;; Let's make sure we're not interrupted and that none of
262 ;; the deadline or deadlock detection stuff triggers.
263 (without-interrupts
264 (sb!thread::without-thread-waiting-for
265 (:already-without-interrupts t)
266 (let ((sb!impl::*deadline* nil)
267 (sb!impl::*deadline-seconds* nil)
268 (epoch *gc-epoch*))
269 (loop
270 ;; GCing must be done without-gcing to avoid
271 ;; recursive GC... but we can't block on
272 ;; *already-in-gc* inside without-gcing: that would
273 ;; cause a deadlock.
274 (without-gcing
275 ;; Try to grab that mutex. On acquisition, stop
276 ;; the world from with the mutex held, and then
277 ;; execute the remainder of the GC: stopping the
278 ;; world with interrupts disabled is the mother of
279 ;; all critical sections.
280 (cond ((sb!thread:with-mutex (*already-in-gc* :wait-p nil)
281 (unsafe-clear-roots gen)
282 (gc-stop-the-world)
284 ;; Success! GC.
285 (perform-gc)
286 ;; Return, but leave *gc-pending* as is: we
287 ;; did allocate a tiny bit after GCing. In
288 ;; theory, this could lead to a long chain
289 ;; of tail-recursive (but not in explicit
290 ;; tail position) GCs, but that doesn't
291 ;; seem likely to happen too often... And
292 ;; the old code already suffered from this
293 ;; problem.
294 (return t))
296 ;; Some other thread is trying to GC. Clear
297 ;; *gc-pending* (we already know we want a
298 ;; GC to happen) and either let
299 ;; without-gcing figure out that the world
300 ;; is stopping, or try again.
301 (setf *gc-pending* nil))))
302 ;; we just wanted a minor GC, and a GC has
303 ;; occurred. Leave, but don't execute after-gc
304 ;; hooks.
306 ;; Return a 0 for easy ternary logic in the C
307 ;; runtime.
308 (when (and (eql gen 0)
309 (neq epoch *gc-pending*))
310 (return 0))))))))))
312 (defun post-gc ()
313 ;; Outside the mutex, interrupts may be enabled: these may cause
314 ;; another GC. FIXME: it can potentially exceed maximum interrupt
315 ;; nesting by triggering GCs.
317 ;; Can that be avoided by having the finalizers and hooks run only
318 ;; from the outermost SUB-GC? If the nested GCs happen in interrupt
319 ;; handlers that's not enough.
321 ;; KLUDGE: Don't run the hooks in GC's if:
323 ;; A) this thread is dying, so that user-code never runs with
324 ;; (thread-alive-p *current-thread*) => nil
326 ;; B) interrupts are disabled somewhere up the call chain since we
327 ;; don't want to run user code in such a case.
329 ;; The long-term solution will be to keep a separate thread for
330 ;; finalizers and after-gc hooks.
331 (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
332 (when *allow-with-interrupts*
333 (sb!thread::without-thread-waiting-for ()
334 (with-interrupts
335 (run-pending-finalizers)
336 (call-hooks "after-GC" *after-gc-hooks* :on-error :warn))))))
338 ;;; This is the user-advertised garbage collection function.
339 (defun gc (&key (full nil) (gen 0) &allow-other-keys)
340 #!+(and sb-doc gencgc)
341 "Initiate a garbage collection.
343 The default is to initiate a nursery collection, which may in turn
344 trigger a collection of one or more older generations as well. If FULL
345 is true, all generations are collected. If GEN is provided, it can be
346 used to specify the oldest generation guaranteed to be collected.
348 On CheneyGC platforms arguments FULL and GEN take no effect: a full
349 collection is always performed."
350 #!+(and sb-doc (not gencgc))
351 "Initiate a garbage collection.
353 The collection is always a full collection.
355 Arguments FULL and GEN can be used for compatibility with GENCGC
356 platforms: there the default is to initiate a nursery collection,
357 which may in turn trigger a collection of one or more older
358 generations as well. If FULL is true, all generations are collected.
359 If GEN is provided, it can be used to specify the oldest generation
360 guaranteed to be collected."
361 #!-gencgc (declare (ignore full))
362 (let (#!+gencgc (gen (if full sb!vm:+pseudo-static-generation+ gen)))
363 (when (eq t (sub-gc :gen gen))
364 (post-gc))))
366 (define-alien-routine scrub-control-stack void)
368 (defun unsafe-clear-roots (gen)
369 #!-gencgc (declare (ignore gen))
370 ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
371 ;; as having these cons more then we have space left leads to huge
372 ;; badness.
373 (scrub-control-stack)
374 ;; Power cache of the bignum printer: drops overly large bignums and
375 ;; removes duplicate entries.
376 (scrub-power-cache)
377 ;; Clear caches depending on the generation being collected.
378 #!+gencgc
379 (cond ((eql 0 gen))
380 ((eql 1 gen)
381 (ctype-of-cache-clear))
383 (drop-all-hash-caches)))
384 #!-gencgc
385 (drop-all-hash-caches))
387 ;;;; auxiliary functions
389 (defun bytes-consed-between-gcs ()
390 #!+sb-doc
391 "The amount of memory that will be allocated before the next garbage
392 collection is initiated. This can be set with SETF.
394 On GENCGC platforms this is the nursery size, and defaults to 5% of dynamic
395 space size.
397 Note: currently changes to this value are lost when saving core."
398 (extern-alien "bytes_consed_between_gcs" os-vm-size-t))
400 (defun (setf bytes-consed-between-gcs) (val)
401 (declare (type index val))
402 (setf (extern-alien "bytes_consed_between_gcs" os-vm-size-t)
403 val))
405 (declaim (inline maybe-handle-pending-gc))
406 (defun maybe-handle-pending-gc ()
407 (when (and (not *gc-inhibit*)
408 (or #!+sb-thread *stop-for-gc-pending*
409 *gc-pending*))
410 (sb!unix::receive-pending-interrupt)))
412 ;;;; GENCGC specifics
413 ;;;;
414 ;;;; For documentation convenience, these have stubs on non-GENCGC platforms
415 ;;;; as well.
416 #!+gencgc
417 (deftype generation-index ()
418 '(integer 0 #.sb!vm:+pseudo-static-generation+))
420 ;;; FIXME: GENERATION (and PAGE, as seen in room.lisp) should probably be
421 ;;; defined in Lisp, and written to header files by genesis, instead of this
422 ;;; OAOOMiness -- this duplicates the struct definition in gencgc.c.
423 #!+gencgc
424 (define-alien-type generation
425 (struct generation
426 (alloc-start-page page-index-t)
427 (alloc-unboxed-start-page page-index-t)
428 (alloc-large-start-page page-index-t)
429 (alloc-large-unboxed-start-page page-index-t)
430 (bytes-allocated os-vm-size-t)
431 (gc-trigger os-vm-size-t)
432 (bytes-consed-between-gcs os-vm-size-t)
433 (number-of-gcs int)
434 (number-of-gcs-before-promotion int)
435 (cum-sum-bytes-allocated os-vm-size-t)
436 (minimum-age-before-gc double)))
438 #!+gencgc
439 (define-alien-variable generations
440 (array generation #.(1+ sb!vm:+pseudo-static-generation+)))
442 (macrolet ((def (slot doc &optional setfp)
443 (declare (ignorable doc))
444 `(progn
445 (defun ,(symbolicate "GENERATION-" slot) (generation)
446 #!+sb-doc
447 ,doc
448 #!+gencgc
449 (declare (generation-index generation))
450 #!-gencgc
451 (declare (ignore generation))
452 #!-gencgc
453 (error "~S is a GENCGC only function and unavailable in this build"
454 ',slot)
455 #!+gencgc
456 (slot (deref generations generation) ',slot))
457 ,@(when setfp
458 `((defun (setf ,(symbolicate "GENERATION-" slot)) (value generation)
459 #!+gencgc
460 (declare (generation-index generation))
461 #!-gencgc
462 (declare (ignore value generation))
463 #!-gencgc
464 (error "(SETF ~S) is a GENCGC only function and unavailable in this build"
465 ',slot)
466 #!+gencgc
467 (setf (slot (deref generations generation) ',slot) value)))))))
468 (def bytes-consed-between-gcs
469 "Number of bytes that can be allocated to GENERATION before that
470 generation is considered for garbage collection. This value is meaningless for
471 generation 0 (the nursery): see BYTES-CONSED-BETWEEN-GCS instead. Default is
472 5% of the dynamic space size divided by the number of non-nursery generations.
473 Can be assigned to using SETF. Available on GENCGC platforms only.
475 Experimental: interface subject to change."
477 (def minimum-age-before-gc
478 "Minimum average age of objects allocated to GENERATION before that
479 generation is may be garbage collected. Default is 0.75. See also
480 GENERATION-AVERAGE-AGE. Can be assigned to using SETF. Available on GENCGC
481 platforms only.
483 Experimental: interface subject to change."
485 (def number-of-gcs-before-promotion
486 "Number of times garbage collection is done on GENERATION before
487 automatic promotion to the next generation is triggered. Default is 1. Can be
488 assigned to using SETF. Available on GENCGC platforms only.
490 Experimental: interface subject to change."
492 (def bytes-allocated
493 "Number of bytes allocated to GENERATION currently. Available on GENCGC
494 platforms only.
496 Experimental: interface subject to change.")
497 (def number-of-gcs
498 "Number of times garbage collection has been done on GENERATION without
499 promotion. Available on GENCGC platforms only.
501 Experimental: interface subject to change."))
502 (defun generation-average-age (generation)
503 #!+sb-doc
504 "Average age of memory allocated to GENERATION: average number of times
505 objects allocated to the generation have seen younger objects promoted to it.
506 Available on GENCGC platforms only.
508 Experimental: interface subject to change."
509 #!+gencgc
510 (declare (generation-index generation))
511 #!-gencgc (declare (ignore generation))
512 #!-gencgc
513 (error "~S is a GENCGC only function and unavailable in this build."
514 'generation-average-age)
515 #!+gencgc
516 (alien-funcall (extern-alien "generation_average_age"
517 (function double generation-index-t))
518 generation))