DCE: delete :optional functionals.
[sbcl.git] / src / code / gc.lisp
blobb5e1a45a232b885497d0eaf9845fe867ece7563a
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 #!+(and relocatable-heap gencgc)
17 (define-alien-variable ("DYNAMIC_SPACE_START" sb!vm:dynamic-space-start) unsigned-long)
18 #!-sb-fluid
19 (declaim (inline current-dynamic-space-start))
20 (defun current-dynamic-space-start ()
21 #!+gencgc sb!vm:dynamic-space-start
22 #!-gencgc (extern-alien "current_dynamic_space" unsigned-long))
24 #!+(or x86 x86-64)
25 (progn
26 (declaim (inline dynamic-space-free-pointer))
27 (defun dynamic-space-free-pointer ()
28 (extern-alien "dynamic_space_free_pointer" system-area-pointer)))
30 #!-sb-fluid
31 (declaim (inline dynamic-usage))
32 #!+gencgc
33 (defun dynamic-usage ()
34 (extern-alien "bytes_allocated" os-vm-size-t))
35 #!-gencgc
36 (defun dynamic-usage ()
37 (truly-the word
38 (- (sap-int (sb!c::dynamic-space-free-pointer))
39 (current-dynamic-space-start))))
41 #!+immobile-space
42 (progn
43 (define-alien-variable sb!vm:varyobj-space-size (unsigned 32))
44 #!+relocatable-heap
45 (progn
46 (define-alien-variable ("FIXEDOBJ_SPACE_START" sb!vm:fixedobj-space-start) unsigned-long)
47 (define-alien-variable ("VARYOBJ_SPACE_START" sb!vm:varyobj-space-start) unsigned-long))
48 (define-alien-variable ("varyobj_free_pointer" sb!vm:*varyobj-space-free-pointer*)
49 system-area-pointer)
50 (define-alien-variable ("fixedobj_free_pointer" sb!vm:*fixedobj-space-free-pointer*)
51 system-area-pointer)
52 (defun immobile-space-addr-p (addr)
53 (declare (type word addr))
54 (or (let ((start sb!vm:fixedobj-space-start))
55 (<= start addr (truly-the word (+ start (1- sb!vm:fixedobj-space-size)))))
56 (let ((start sb!vm:varyobj-space-start))
57 (<= start addr (truly-the word (+ start (1- sb!vm:varyobj-space-size)))))))
58 (defun immobile-space-obj-p (obj)
59 (immobile-space-addr-p (get-lisp-obj-address obj))))
61 (defun static-space-usage ()
62 (- (sap-int sb!vm:*static-space-free-pointer*) sb!vm:static-space-start))
64 (defun read-only-space-usage ()
65 (- (sap-int sb!vm:*read-only-space-free-pointer*) sb!vm:read-only-space-start))
67 ;;; Convert the descriptor into a SAP. The bits all stay the same, we just
68 ;;; change our notion of what we think they are.
69 (declaim (inline descriptor-sap))
70 (defun descriptor-sap (x) (int-sap (get-lisp-obj-address x)))
72 (defun control-stack-usage ()
73 #!-stack-grows-downward-not-upward
74 (sap- (control-stack-pointer-sap) (descriptor-sap sb!vm:*control-stack-start*))
75 #!+stack-grows-downward-not-upward
76 (sap- (descriptor-sap sb!vm:*control-stack-end*) (control-stack-pointer-sap)))
78 (defun binding-stack-usage ()
79 (sap- (binding-stack-pointer-sap) (descriptor-sap sb!vm:*binding-stack-start*)))
81 ;;;; GET-BYTES-CONSED
83 ;;; the total number of bytes freed so far (including any freeing
84 ;;; which goes on in PURIFY)
85 ;;;
86 ;;; (We save this so that we can calculate the total number of bytes
87 ;;; ever allocated by adding this to the number of bytes currently
88 ;;; allocated and never freed.)
89 (declaim (type unsigned-byte *n-bytes-freed-or-purified*))
90 (defglobal *n-bytes-freed-or-purified* 0)
91 (defun gc-reinit ()
92 (setq *gc-inhibit* nil)
93 (gc)
94 (setf *n-bytes-freed-or-purified* 0
95 *gc-run-time* 0))
97 (declaim (ftype (sfunction () unsigned-byte) get-bytes-consed))
98 (defun get-bytes-consed ()
99 "Return the number of bytes consed since the program began. Typically
100 this result will be a consed bignum, so if you have an application (e.g.
101 profiling) which can't tolerate the overhead of consing bignums, you'll
102 probably want either to hack in at a lower level (as the code in the
103 SB-PROFILE package does), or to design a more microefficient interface
104 and submit it as a patch."
105 (+ (dynamic-usage)
106 *n-bytes-freed-or-purified*))
108 ;;;; GC hooks
110 (!defvar *after-gc-hooks* nil
111 "Called after each garbage collection, except for garbage collections
112 triggered during thread exits. In a multithreaded environment these hooks may
113 run in any thread.")
116 ;;;; internal GC
118 (define-alien-routine collect-garbage int
119 (#!+gencgc last-gen #!-gencgc ignore int))
121 #!+(or sb-thread sb-safepoint)
122 (progn
123 (define-alien-routine gc-stop-the-world void)
124 (define-alien-routine gc-start-the-world void))
125 #!-(or sb-thread sb-safepoint)
126 (progn
127 (defun gc-stop-the-world ())
128 (defun gc-start-the-world ()))
130 #!+gencgc
131 (progn
132 (define-alien-variable ("gc_logfile" %gc-logfile) (* char))
133 (defun (setf gc-logfile) (pathname)
134 (let ((new (when pathname
135 (make-alien-string
136 (native-namestring (translate-logical-pathname pathname)
137 :as-file t))))
138 (old %gc-logfile))
139 (setf %gc-logfile new)
140 (when old
141 (free-alien old))
142 pathname))
143 (defun gc-logfile ()
144 "Return the pathname used to log garbage collections. Can be SETF.
145 Default is NIL, meaning collections are not logged. If non-null, the
146 designated file is opened before and after each collection, and generation
147 statistics are appended to it."
148 (let ((val (cast %gc-logfile c-string)))
149 (when val
150 (native-pathname val)))))
152 (declaim (inline dynamic-space-size))
153 (defun dynamic-space-size ()
154 "Size of the dynamic space in bytes."
155 (extern-alien "dynamic_space_size" os-vm-size-t))
156 #!+gencgc
157 (define-symbol-macro sb!vm:dynamic-space-end
158 (+ (dynamic-space-size) sb!vm:dynamic-space-start))
160 ;;;; SUB-GC
162 ;;; SUB-GC does a garbage collection. This is called from three places:
163 ;;; (1) The C runtime will call here when it detects that we've consed
164 ;;; enough to exceed the gc trigger threshold. This is done in
165 ;;; alloc() for gencgc or interrupt_maybe_gc() for cheneygc
166 ;;; (2) The user may request a collection using GC, below
167 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
168 ;;; *NEED-TO-COLLECT-GARBAGE* is true
170 ;;; This is different from the behaviour in 0.7 and earlier: it no
171 ;;; longer decides whether to GC based on thresholds. If you call
172 ;;; SUB-GC you will definitely get a GC either now or when the
173 ;;; WITHOUT-GCING is over
175 ;;; For GENCGC all generations < GEN will be GC'ed.
177 (define-load-time-global *already-in-gc* (sb!thread:make-mutex :name "GC lock"))
179 (defun sub-gc (gen)
180 (cond (*gc-inhibit*
181 (setf *gc-pending* t)
182 nil)
184 (flet ((perform-gc ()
185 ;; Called from WITHOUT-GCING and WITHOUT-INTERRUPTS
186 ;; after the world has been stopped, but it's an
187 ;; awkwardly long piece of code to nest so deeply.
188 (let ((old-usage (dynamic-usage))
189 (new-usage 0)
190 (start-time (get-internal-run-time)))
191 (collect-garbage gen)
192 (setf *gc-epoch* (cons 0 0))
193 (let ((run-time (- (get-internal-run-time) start-time)))
194 ;; KLUDGE: Sometimes we see the second getrusage() call
195 ;; return a smaller value than the first, which can
196 ;; lead to *GC-RUN-TIME* to going negative, which in
197 ;; turn is a type-error.
198 (when (plusp run-time)
199 (incf *gc-run-time* run-time)))
200 #!+(and sb-thread sb-safepoint)
201 (setf *stop-for-gc-pending* nil)
202 (setf *gc-pending* nil
203 new-usage (dynamic-usage))
204 #!+sb-thread
205 (aver (not *stop-for-gc-pending*))
206 (gc-start-the-world)
207 ;; In a multithreaded environment the other threads
208 ;; will see *n-b-f-o-p* change a little late, but
209 ;; that's OK.
210 ;; N.B. the outer without-gcing prevents this
211 ;; function from being entered, so no need for
212 ;; locking.
213 (let ((freed (- old-usage new-usage)))
214 ;; GENCGC occasionally reports negative here, but
215 ;; the current belief is that it is part of the
216 ;; normal order of things and not a bug.
217 (when (plusp freed)
218 (incf *n-bytes-freed-or-purified* freed))))))
219 (declare (inline perform-gc))
220 ;; Let's make sure we're not interrupted and that none of
221 ;; the deadline or deadlock detection stuff triggers.
222 (without-interrupts
223 (sb!thread::without-thread-waiting-for
224 (:already-without-interrupts t)
225 (let ((sb!impl::*deadline* nil)
226 (epoch *gc-epoch*))
227 (loop
228 ;; GCing must be done without-gcing to avoid
229 ;; recursive GC... but we can't block on
230 ;; *already-in-gc* inside without-gcing: that would
231 ;; cause a deadlock.
232 (without-gcing
233 ;; Try to grab that mutex. On acquisition, stop
234 ;; the world from with the mutex held, and then
235 ;; execute the remainder of the GC: stopping the
236 ;; world with interrupts disabled is the mother of
237 ;; all critical sections.
238 (cond ((sb!thread:with-mutex (*already-in-gc* :wait-p nil)
239 (unsafe-clear-roots gen)
240 (gc-stop-the-world)
242 ;; Success! GC.
243 (perform-gc)
244 ;; Return, but leave *gc-pending* as is: we
245 ;; did allocate a tiny bit after GCing. In
246 ;; theory, this could lead to a long chain
247 ;; of tail-recursive (but not in explicit
248 ;; tail position) GCs, but that doesn't
249 ;; seem likely to happen too often... And
250 ;; the old code already suffered from this
251 ;; problem.
252 (return t))
254 ;; Some other thread is trying to GC. Clear
255 ;; *gc-pending* (we already know we want a
256 ;; GC to happen) and either let
257 ;; without-gcing figure out that the world
258 ;; is stopping, or try again.
259 (setf *gc-pending* nil))))
260 ;; we just wanted a minor GC, and a GC has
261 ;; occurred. Leave, but don't execute after-gc
262 ;; hooks.
264 ;; Return a 0 for easy ternary logic in the C
265 ;; runtime.
266 (when (and (eql gen 0)
267 (neq epoch *gc-pending*))
268 (return 0))))))))))
270 (defun post-gc ()
271 ;; Outside the mutex, interrupts may be enabled: these may cause
272 ;; another GC. FIXME: it can potentially exceed maximum interrupt
273 ;; nesting by triggering GCs.
275 ;; Can that be avoided by having the finalizers and hooks run only
276 ;; from the outermost SUB-GC? If the nested GCs happen in interrupt
277 ;; handlers that's not enough.
279 ;; KLUDGE: Don't run the hooks in GC's if:
281 ;; A) this thread is dying, so that user-code never runs with
282 ;; (thread-alive-p *current-thread*) => nil
284 ;; B) interrupts are disabled somewhere up the call chain since we
285 ;; don't want to run user code in such a case.
287 ;; The long-term solution will be to keep a separate thread for
288 ;; finalizers and after-gc hooks.
289 (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
290 (when *allow-with-interrupts*
291 (sb!thread::without-thread-waiting-for ()
292 (with-interrupts
293 (run-pending-finalizers)
294 (call-hooks "after-GC" *after-gc-hooks* :on-error :warn))))))
296 ;;; This is the user-advertised garbage collection function.
297 (defun gc (&key (full nil) (gen 0) &allow-other-keys)
298 #!+gencgc
299 "Initiate a garbage collection.
301 The default is to initiate a nursery collection, which may in turn
302 trigger a collection of one or more older generations as well. If FULL
303 is true, all generations are collected. If GEN is provided, it can be
304 used to specify the oldest generation guaranteed to be collected.
306 On CheneyGC platforms arguments FULL and GEN take no effect: a full
307 collection is always performed."
308 #!-gencgc
309 "Initiate a garbage collection.
311 The collection is always a full collection.
313 Arguments FULL and GEN can be used for compatibility with GENCGC
314 platforms: there the default is to initiate a nursery collection,
315 which may in turn trigger a collection of one or more older
316 generations as well. If FULL is true, all generations are collected.
317 If GEN is provided, it can be used to specify the oldest generation
318 guaranteed to be collected."
319 #!-gencgc (declare (ignore full))
320 (let (#!+gencgc (gen (if full sb!vm:+pseudo-static-generation+ gen)))
321 (when (eq t (sub-gc gen))
322 (post-gc))))
324 (define-alien-routine scrub-control-stack void)
326 (defun unsafe-clear-roots (gen)
327 #!-gencgc (declare (ignore gen))
328 ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
329 ;; as having these cons more than we have space left leads to huge
330 ;; badness.
331 (scrub-control-stack)
332 ;; Power cache of the bignum printer: drops overly large bignums and
333 ;; removes duplicate entries.
334 (scrub-power-cache)
335 ;; Clear caches depending on the generation being collected.
336 #!+gencgc
337 (cond ((eql 0 gen)
338 ;; Drop strings because the hash is pointer-hash
339 ;; but there is no automatic cache rehashing after GC.
340 (sb!format::tokenize-control-string-cache-clear))
341 ((eql 1 gen)
342 (sb!format::tokenize-control-string-cache-clear)
343 (ctype-of-cache-clear))
345 (drop-all-hash-caches)))
346 #!-gencgc
347 (drop-all-hash-caches))
349 ;;;; auxiliary functions
351 (defun bytes-consed-between-gcs ()
352 "The amount of memory that will be allocated before the next garbage
353 collection is initiated. This can be set with SETF.
355 On GENCGC platforms this is the nursery size, and defaults to 5% of dynamic
356 space size.
358 Note: currently changes to this value are lost when saving core."
359 (extern-alien "bytes_consed_between_gcs" os-vm-size-t))
361 (defun (setf bytes-consed-between-gcs) (val)
362 (declare (type index val))
363 (setf (extern-alien "bytes_consed_between_gcs" os-vm-size-t)
364 val))
366 (declaim (inline maybe-handle-pending-gc))
367 (defun maybe-handle-pending-gc ()
368 (when (and (not *gc-inhibit*)
369 (or #!+sb-thread *stop-for-gc-pending*
370 *gc-pending*))
371 (sb!unix::receive-pending-interrupt)))
373 ;;;; GENCGC specifics
374 ;;;;
375 ;;;; For documentation convenience, these have stubs on non-GENCGC platforms
376 ;;;; as well.
377 #!+gencgc
378 (deftype generation-index ()
379 '(integer 0 #.sb!vm:+pseudo-static-generation+))
381 ;;; FIXME: GENERATION (and PAGE, as seen in room.lisp) should probably be
382 ;;; defined in Lisp, and written to header files by genesis, instead of this
383 ;;; OAOOMiness -- this duplicates the struct definition in gencgc.c.
384 #!+gencgc
385 (define-alien-type generation
386 (struct generation
387 (alloc-large-start-page page-index-t)
388 (alloc-start-page page-index-t)
389 (alloc-unboxed-start-page page-index-t)
390 (alloc-code-start-page page-index-t)
391 (bytes-allocated os-vm-size-t)
392 (gc-trigger os-vm-size-t)
393 (bytes-consed-between-gcs os-vm-size-t)
394 (number-of-gcs int)
395 (number-of-gcs-before-promotion int)
396 (cum-sum-bytes-allocated os-vm-size-t)
397 (minimum-age-before-gc double)))
399 #!+gencgc
400 (define-alien-variable generations
401 (array generation #.(1+ sb!vm:+pseudo-static-generation+)))
403 (macrolet ((def (slot doc &optional setfp)
404 `(progn
405 (defun ,(symbolicate "GENERATION-" slot) (generation)
406 ,doc
407 #!+gencgc
408 (declare (generation-index generation))
409 #!-gencgc
410 (declare (ignore generation))
411 #!-gencgc
412 (error "~S is a GENCGC only function and unavailable in this build"
413 ',slot)
414 #!+gencgc
415 (slot (deref generations generation) ',slot))
416 ,@(when setfp
417 `((defun (setf ,(symbolicate "GENERATION-" slot)) (value generation)
418 #!+gencgc
419 (declare (generation-index generation))
420 #!-gencgc
421 (declare (ignore value generation))
422 #!-gencgc
423 (error "(SETF ~S) is a GENCGC only function and unavailable in this build"
424 ',slot)
425 #!+gencgc
426 (setf (slot (deref generations generation) ',slot) value)))))))
427 (def bytes-consed-between-gcs
428 "Number of bytes that can be allocated to GENERATION before that
429 generation is considered for garbage collection. This value is meaningless for
430 generation 0 (the nursery): see BYTES-CONSED-BETWEEN-GCS instead. Default is
431 5% of the dynamic space size divided by the number of non-nursery generations.
432 Can be assigned to using SETF. Available on GENCGC platforms only.
434 Experimental: interface subject to change."
436 (def minimum-age-before-gc
437 "Minimum average age of objects allocated to GENERATION before that
438 generation is may be garbage collected. Default is 0.75. See also
439 GENERATION-AVERAGE-AGE. Can be assigned to using SETF. Available on GENCGC
440 platforms only.
442 Experimental: interface subject to change."
444 (def number-of-gcs-before-promotion
445 "Number of times garbage collection is done on GENERATION before
446 automatic promotion to the next generation is triggered. Default is 1. Can be
447 assigned to using SETF. Available on GENCGC platforms only.
449 Experimental: interface subject to change."
451 (def bytes-allocated
452 "Number of bytes allocated to GENERATION currently. Available on GENCGC
453 platforms only.
455 Experimental: interface subject to change.")
456 (def number-of-gcs
457 "Number of times garbage collection has been done on GENERATION without
458 promotion. Available on GENCGC platforms only.
460 Experimental: interface subject to change."))
461 (defun generation-average-age (generation)
462 "Average age of memory allocated to GENERATION: average number of times
463 objects allocated to the generation have seen younger objects promoted to it.
464 Available on GENCGC platforms only.
466 Experimental: interface subject to change."
467 #!+gencgc
468 (declare (generation-index generation))
469 #!-gencgc (declare (ignore generation))
470 #!-gencgc
471 (error "~S is a GENCGC only function and unavailable in this build."
472 'generation-average-age)
473 #!+gencgc
474 (alien-funcall (extern-alien "generation_average_age"
475 (function double generation-index-t))
476 generation))