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