GC documentation tweaks
[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 #!-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   (sb!alien:extern-alien "current_dynamic_space" sb!alien:unsigned-long))
23
24 #!-sb-fluid
25 (declaim (inline dynamic-usage))
26 #!+gencgc
27 (defun dynamic-usage ()
28   (sb!alien:extern-alien "bytes_allocated" os-vm-size-t))
29 #!-gencgc
30 (defun dynamic-usage ()
31   (the (unsigned-byte 32)
32        (- (sb!sys:sap-int (sb!c::dynamic-space-free-pointer))
33           (current-dynamic-space-start))))
34
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))
38
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))
42
43 (defun control-stack-usage ()
44   #!-stack-grows-downward-not-upward
45   (- (sb!sys:sap-int (sb!c::control-stack-pointer-sap))
46      (sb!sys:sap-int (sb!di::descriptor-sap sb!vm:*control-stack-start*)))
47   #!+stack-grows-downward-not-upward
48   (- (sb!sys:sap-int (sb!di::descriptor-sap sb!vm:*control-stack-end*))
49      (sb!sys:sap-int (sb!c::control-stack-pointer-sap))))
50
51 (defun binding-stack-usage ()
52   (- (sb!sys:sap-int (sb!c::binding-stack-pointer-sap))
53      (sb!sys:sap-int (sb!di::descriptor-sap sb!vm:*binding-stack-start*))))
54 \f
55 ;;;; ROOM
56
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*))
68
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))
75
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)
84   )
85
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))
103 \f
104 ;;;; GET-BYTES-CONSED
105
106 ;;; the total number of bytes freed so far (including any freeing
107 ;;; which goes on in PURIFY)
108 ;;;
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)))
121
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*))
133 \f
134 ;;;; GC hooks
135
136 (defvar *after-gc-hooks* nil
137   "Called after each garbage collection, except for garbage collections
138 triggered during thread exits. In a multithreaded environment these hooks may
139 run in any thread.")
140
141 \f
142 ;;;; internal GC
143
144 (sb!alien:define-alien-routine collect-garbage sb!alien:int
145   (#!+gencgc last-gen #!-gencgc ignore sb!alien:int))
146
147 #!+sb-thread
148 (progn
149   (sb!alien:define-alien-routine gc-stop-the-world sb!alien:void)
150   (sb!alien:define-alien-routine gc-start-the-world sb!alien:void))
151 #!-sb-thread
152 (progn
153   (defun gc-stop-the-world ())
154   (defun gc-start-the-world ()))
155
156 #!+gencgc
157 (progn
158   (sb!alien:define-alien-variable ("gc_logfile" %gc-logfile) (* char))
159   (defun (setf gc-logfile) (pathname)
160     (let ((new (when pathname
161                  (sb!alien:make-alien-string
162                   (native-namestring (translate-logical-pathname pathname)
163                                      :as-file t))))
164           (old %gc-logfile))
165       (setf %gc-logfile new)
166       (when old
167         (sb!alien:free-alien old))))
168   (defun gc-logfile ()
169     #!+sb-doc
170     "Return the pathname used to log garbage collections. Can be SETF.
171 Default is NIL, meaning collections are not logged. If non-null, the
172 designated file is opened before and after each collection, and generation
173 statistics are appended to it."
174     (let ((val %gc-logfile))
175       (when val
176         (native-pathname (cast val c-string)))))
177   (declaim (inline dynamic-space-size))
178   (defun dynamic-space-size ()
179     "Size of the dynamic space in bytes."
180     (sb!alien:extern-alien "dynamic_space_size" os-vm-size-t)))
181 \f
182 ;;;; SUB-GC
183
184 ;;; SUB-GC does a garbage collection.  This is called from three places:
185 ;;; (1) The C runtime will call here when it detects that we've consed
186 ;;;     enough to exceed the gc trigger threshold.  This is done in
187 ;;;     alloc() for gencgc or interrupt_maybe_gc() for cheneygc
188 ;;; (2) The user may request a collection using GC, below
189 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
190 ;;;     *NEED-TO-COLLECT-GARBAGE* is true
191 ;;;
192 ;;; This is different from the behaviour in 0.7 and earlier: it no
193 ;;; longer decides whether to GC based on thresholds.  If you call
194 ;;; SUB-GC you will definitely get a GC either now or when the
195 ;;; WITHOUT-GCING is over
196
197 ;;; For GENCGC all generations < GEN will be GC'ed.
198
199 (defvar *already-in-gc* (sb!thread:make-mutex :name "GC lock"))
200
201 ;;; A unique GC id. This is supplied for code that needs to detect
202 ;;; whether a GC has happened since some earlier point in time. For
203 ;;; example:
204 ;;;
205 ;;;   (let ((epoch *gc-epoch*))
206 ;;;      ...
207 ;;;      (unless (eql epoch *gc-epoch)
208 ;;;        ....))
209 ;;;
210 ;;; This isn't just a fixnum counter since then we'd have theoretical
211 ;;; problems when exactly 2^29 GCs happen between epoch
212 ;;; comparisons. Unlikely, but the cost of using a cons instead is too
213 ;;; small to measure. -- JES, 2007-09-30
214 (declaim (type cons *gc-epoch*))
215 (defvar *gc-epoch* (cons nil nil))
216
217 (defun sub-gc (&key (gen 0))
218   (cond (*gc-inhibit*
219          (setf *gc-pending* t)
220          nil)
221         (t
222          (without-interrupts
223            (setf *gc-pending* :in-progress)
224            ;; Tricks to to prevent triggerring a recursive gc. This is
225            ;; like a WITHOUT-GCING inside the lock except that we
226            ;; cannot call MAYBE-HANDLE-PENDING-GC at the end, because
227            ;; that would lead to a recursive attempt on the lock. In
228            ;; case you are wondering, wrapping the lock in a
229            ;; WITHOUT-GCING would also deadlock. The
230            ;; *IN-WITHOUT-GCING* part is used to tell the runtime that
231            ;; it's ok to have a pending gc even though *GC-INHIBIT* is
232            ;; NIL.
233            ;;
234            ;; Now, if GET-MUTEX did not cons, that would be enough.
235            ;; Because it does, we need the :IN-PROGRESS bit above to
236            ;; tell the runtime not to trigger gcs.
237            (sb!thread::without-thread-waiting-for (:already-without-interrupts t)
238              (let* ((sb!impl::*in-without-gcing* t)
239                     (sb!impl::*deadline* nil)
240                     (sb!impl::*deadline-seconds* nil))
241                (sb!thread:with-mutex (*already-in-gc*)
242                  (let ((*gc-inhibit* t))
243                    (let ((old-usage (dynamic-usage))
244                          (new-usage 0))
245                      (unsafe-clear-roots gen)
246                      (gc-stop-the-world)
247                      (let ((start-time (get-internal-run-time)))
248                        (collect-garbage gen)
249                        (setf *gc-epoch* (cons nil nil))
250                        (let ((run-time (- (get-internal-run-time) start-time)))
251                          ;; KLUDGE: Sometimes we see the second getrusage() call
252                          ;; return a smaller value than the first, which can
253                          ;; lead to *GC-RUN-TIME* to going negative, which in
254                          ;; turn is a type-error.
255                          (when (plusp run-time)
256                            (incf *gc-run-time* run-time))))
257                      (setf *gc-pending* nil
258                            new-usage (dynamic-usage))
259                      #!+sb-thread
260                      (assert (not *stop-for-gc-pending*))
261                      (gc-start-the-world)
262                      ;; In a multithreaded environment the other threads
263                      ;; will see *n-b-f-o-p* change a little late, but
264                      ;; that's OK.
265                      (let ((freed (- old-usage new-usage)))
266                        ;; GENCGC occasionally reports negative here, but
267                        ;; the current belief is that it is part of the
268                        ;; normal order of things and not a bug.
269                        (when (plusp freed)
270                          (incf *n-bytes-freed-or-purified* freed))))))))
271            ;; While holding the mutex we were protected from
272            ;; SIG_STOP_FOR_GC and recursive GCs. Now, in order to
273            ;; preserve the invariant (*GC-PENDING* ->
274            ;; pseudo-atomic-interrupted or *GC-INHIBIT*), let's check
275            ;; explicitly for a pending gc before interrupts are
276            ;; enabled again.
277            (maybe-handle-pending-gc))
278          t)))
279
280 (defun post-gc ()
281   ;; Outside the mutex, interrupts may be enabled: these may cause
282   ;; another GC. FIXME: it can potentially exceed maximum interrupt
283   ;; nesting by triggering GCs.
284   ;;
285   ;; Can that be avoided by having the finalizers and hooks run only
286   ;; from the outermost SUB-GC? If the nested GCs happen in interrupt
287   ;; handlers that's not enough.
288   ;;
289   ;; KLUDGE: Don't run the hooks in GC's if:
290   ;;
291   ;; A) this thread is dying, so that user-code never runs with
292   ;;    (thread-alive-p *current-thread*) => nil
293   ;;
294   ;; B) interrupts are disabled somewhere up the call chain since we
295   ;;    don't want to run user code in such a case.
296   ;;
297   ;; The long-term solution will be to keep a separate thread for
298   ;; finalizers and after-gc hooks.
299   (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
300     (when *allow-with-interrupts*
301       (sb!thread::without-thread-waiting-for ()
302         (with-interrupts
303           (run-pending-finalizers)
304           (call-hooks "after-GC" *after-gc-hooks* :on-error :warn))))))
305
306 ;;; This is the user-advertised garbage collection function.
307 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
308   #!+(and sb-doc gencgc)
309   "Initiate a garbage collection. GEN controls the number of generations
310   to garbage collect."
311   #!+(and sb-doc (not gencgc))
312   "Initiate a garbage collection. GEN may be provided for compatibility with
313   generational garbage collectors, but is ignored in this implementation."
314   (when (sub-gc :gen (if full 6 gen))
315     (post-gc)))
316
317 (define-alien-routine scrub-control-stack sb!alien:void)
318
319 (defun unsafe-clear-roots (gen)
320   #!-gencgc (declare (ignore gen))
321   ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
322   ;; as having these cons more then we have space left leads to huge
323   ;; badness.
324   (scrub-control-stack)
325   ;; Power cache of the bignum printer: drops overly large bignums and
326   ;; removes duplicate entries.
327   (scrub-power-cache)
328   ;; Clear caches depending on the generation being collected.
329   #!+gencgc
330   (cond ((eql 0 gen))
331         ((eql 1 gen)
332          (ctype-of-cache-clear))
333         (t
334          (drop-all-hash-caches)))
335   #!-gencgc
336   (drop-all-hash-caches))
337 \f
338 ;;;; auxiliary functions
339
340 (defun bytes-consed-between-gcs ()
341   #!+sb-doc
342   "The amount of memory that will be allocated before the next garbage
343 collection is initiated. This can be set with SETF.
344
345 On GENCGC platforms this is the nursery size, and defaults to 5% of dynamic
346 space size.
347
348 Note: currently changes to this value are lost when saving core."
349   (sb!alien:extern-alien "bytes_consed_between_gcs" os-vm-size-t))
350
351 (defun (setf bytes-consed-between-gcs) (val)
352   (declare (type index val))
353   (setf (sb!alien:extern-alien "bytes_consed_between_gcs" os-vm-size-t)
354         val))
355
356 (declaim (inline maybe-handle-pending-gc))
357 (defun maybe-handle-pending-gc ()
358   (when (and (not *gc-inhibit*)
359              (or #!+sb-thread *stop-for-gc-pending*
360                  *gc-pending*))
361     (sb!unix::receive-pending-interrupt)))
362
363 ;;;; GENCGC specifics
364 ;;;;
365 ;;;; For documentation convenience, these have stubs on non-GENCGC platforms
366 ;;;; as well.
367 #!+gencgc
368 (deftype generation-index ()
369   '(integer 0 #.sb!vm:+pseudo-static-generation+))
370
371 ;;; FIXME: GENERATION (and PAGE, as seen in room.lisp) should probably be
372 ;;; defined in Lisp, and written to header files by genesis, instead of this
373 ;;; OAOOMiness -- this duplicates the struct definition in gencgc.c.
374 #!+gencgc
375 (define-alien-type generation
376     (struct generation
377             (alloc-start-page page-index-t)
378             (alloc-unboxed-start-page page-index-t)
379             (alloc-large-start-page page-index-t)
380             (alloc-large-unboxed-start-page page-index-t)
381             (bytes-allocated os-vm-size-t)
382             (gc-trigger os-vm-size-t)
383             (bytes-consed-between-gcs os-vm-size-t)
384             (number-of-gcs int)
385             (number-of-gcs-before-promotion int)
386             (cum-sum-bytes-allocated os-vm-size-t)
387             (minimum-age-before-gc double)))
388
389 #!+gencgc
390 (define-alien-variable generations
391     (array generation #.(1+ sb!vm:+pseudo-static-generation+)))
392
393 (macrolet ((def (slot doc &optional setfp)
394              (declare (ignorable doc))
395              `(progn
396                 (defun ,(symbolicate "GENERATION-" slot) (generation)
397                   #!+sb-doc
398                   ,doc
399                   #!+gencgc
400                   (declare (generation-index generation))
401                   #!-gencgc
402                   (declare (ignore generation))
403                   #!-gencgc
404                   (error "~S is a GENCGC only function and unavailable in this build"
405                          ',slot)
406                   #!+gencgc
407                   (slot (deref generations generation) ',slot))
408                 ,@(when setfp
409                         `((defun (setf ,(symbolicate "GENERATION-" slot)) (value generation)
410                             #!+gencgc
411                             (declare (generation-index generation))
412                             #!-gencgc
413                             (declare (ignore value generation))
414                             #!-gencgc
415                             (error "(SETF ~S) is a GENCGC only function and unavailable in this build"
416                                    ',slot)
417                             #!+gencgc
418                             (setf (slot (deref generations generation) ',slot) value)))))))
419   (def bytes-consed-between-gcs
420       "Number of bytes that can be allocated to GENERATION before that
421 generation is considered for garbage collection. This value is meaningless for
422 generation 0 (the nursery): see BYTES-CONSED-BETWEEN-GCS instead. Default is
423 5% of the dynamic space size. Can be assigned to using SETF. Available on
424 GENCGC platforms only.
425
426 Experimental: interface subject to change."
427     t)
428   (def minimum-age-before-gc
429       "Minimum average age of objects allocated to GENERATION before that
430 generation is may be garbage collected. Default is 0.75. See also
431 GENERATION-AVERAGE-AGE. Can be assigned to using SETF. Available on GENCGC
432 platforms only.
433
434 Experimental: interface subject to change."
435     t)
436   (def number-of-gcs-before-promotion
437       "Number of times garbage collection is done on GENERATION before
438 automatic promotion to the next generation is triggered. Default is 1. Can be
439 assigned to using SETF. Available on GENCGC platforms only.
440
441 Experimental: interface subject to change."
442     t)
443   (def bytes-allocated
444       "Number of bytes allocated to GENERATION currently. Available on GENCGC
445 platforms only.
446
447 Experimental: interface subject to change.")
448   (def number-of-gcs
449       "Number of times garbage collection has been done on GENERATION without
450 promotion. Available on GENCGC platforms only.
451
452 Experimental: interface subject to change."))
453   (defun generation-average-age (generation)
454     "Average age of memory allocated to GENERATION: average number of times
455 objects allocated to the generation have seen younger objects promoted to it.
456 Available on GENCGC platforms only.
457
458 Experimental: interface subject to change."
459     #!+gencgc
460     (declare (generation-index generation))
461     #!-gencgc (declare (ignore generation))
462     #!-gencgc
463     (error "~S is a GENCGC only function and unavailable in this build."
464            'generation-average-age)
465     #!+gencgc
466     (alien-funcall (extern-alien "generation_average_age"
467                                  (function double generation-index-t))
468                    generation))