0.9.17.2: fix two potential GC deadlocks
[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-start () 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!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))))
56
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*))))
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*))
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         ;; See comment in interr.lisp
125         *heap-exhausted-error-condition* (make-condition 'heap-exhausted-error)))
126
127 (declaim (ftype (function () unsigned-byte) get-bytes-consed))
128 (defun get-bytes-consed ()
129   #!+sb-doc
130   "Return the number of bytes consed since the program began. Typically
131 this result will be a consed bignum, so if you have an application (e.g.
132 profiling) which can't tolerate the overhead of consing bignums, you'll
133 probably want either to hack in at a lower level (as the code in the
134 SB-PROFILE package does), or to design a more microefficient interface
135 and submit it as a patch."
136   (+ (dynamic-usage)
137      *n-bytes-freed-or-purified*))
138 \f
139 ;;;; GC hooks
140
141 (defvar *after-gc-hooks* nil
142   "Called after each garbage collection, except for garbage collections
143 triggered during thread exits. In a multithreaded environment these hooks may
144 run in any thread.")
145
146 \f
147 ;;;; internal GC
148
149 (sb!alien:define-alien-routine collect-garbage sb!alien:int
150   (#!+gencgc last-gen #!-gencgc ignore sb!alien:int))
151
152 #!+sb-thread
153 (progn
154   (sb!alien:define-alien-routine gc-stop-the-world sb!alien:void)
155   (sb!alien:define-alien-routine gc-start-the-world sb!alien:void))
156 #!-sb-thread
157 (progn
158   (defun gc-stop-the-world ())
159   (defun gc-start-the-world ()))
160
161 \f
162 ;;;; SUB-GC
163
164 ;;; SUB-GC does a garbage collection.  This is called from three places:
165 ;;; (1) The C runtime will call here when it detects that we've consed
166 ;;;     enough to exceed the gc trigger threshold.  This is done in
167 ;;;     alloc() for gencgc or interrupt_maybe_gc() for cheneygc
168 ;;; (2) The user may request a collection using GC, below
169 ;;; (3) At the end of a WITHOUT-GCING section, we are called if
170 ;;;     *NEED-TO-COLLECT-GARBAGE* is true
171 ;;;
172 ;;; This is different from the behaviour in 0.7 and earlier: it no
173 ;;; longer decides whether to GC based on thresholds.  If you call
174 ;;; SUB-GC you will definitely get a GC either now or when the
175 ;;; WITHOUT-GCING is over
176
177 ;;; For GENCGC all generations < GEN will be GC'ed.
178
179 (defvar *already-in-gc*
180   (sb!thread:make-mutex :name "GC lock") "ID of thread running SUB-GC")
181
182 (defun sub-gc (&key (gen 0))
183   (unless (eq sb!thread:*current-thread* 
184               (sb!thread::mutex-value *already-in-gc*))
185     ;; With gencgc, unless *GC-PENDING* every allocation in this
186     ;; function triggers another gc, potentially exceeding maximum
187     ;; interrupt nesting.
188     (setq *gc-pending* t)
189     (unless *gc-inhibit*
190       (sb!thread:with-mutex (*already-in-gc*)
191         (let ((old-usage (dynamic-usage))
192               (new-usage 0))
193           (unsafe-clear-roots)
194           ;; We need to disable interrupts for GC, but we also want
195           ;; to run as little as possible without them.
196           (without-interrupts
197             (gc-stop-the-world)
198             (let ((start-time (get-internal-run-time)))
199               (collect-garbage gen)
200               (incf *gc-run-time*
201                     (- (get-internal-run-time) start-time)))
202             (setf *gc-pending* nil
203                   new-usage (dynamic-usage))
204             (gc-start-the-world))
205           ;; Interrupts re-enabled, but still inside the mutex.
206           ;; In a multithreaded environment the other threads will
207           ;; see *n-b-f-o-p* change a little late, but that's OK.
208           (let ((freed (- old-usage new-usage)))
209             ;; GENCGC occasionally reports negative here, but the
210             ;; current belief is that it is part of the normal order
211             ;; of things and not a bug.
212             (when (plusp freed)
213               (incf *n-bytes-freed-or-purified* freed)))))
214       ;; Outside the mutex, these may cause another GC. FIXME: it can
215       ;; potentially exceed maximum interrupt nesting by triggering
216       ;; GCs.
217       ;;
218       ;; Can that be avoided by having the finalizers and hooks run only
219       ;; from the outermost SUB-GC?
220       ;;
221       ;; KLUDGE: Don't run the hooks in GC's triggered by dying threads,
222       ;; so that user-code never runs with 
223       ;;   (thread-alive-p *current-thread*) => nil
224       ;; The long-term solution will be to keep a separate thread for
225       ;; finalizers and after-gc hooks.
226       (when (sb!thread:thread-alive-p sb!thread:*current-thread*)
227         (run-pending-finalizers)
228         (dolist (hook *after-gc-hooks*)
229           (handler-case
230               (funcall hook)
231             (error (c)
232               (warn "Error calling after-GC hook ~S:~% ~A" hook c))))))))
233
234 ;;; This is the user-advertised garbage collection function.
235 (defun gc (&key (gen 0) (full nil) &allow-other-keys)
236   #!+(and sb-doc gencgc)
237   "Initiate a garbage collection. GEN controls the number of generations
238   to garbage collect."
239   #!+(and sb-doc (not gencgc))
240   "Initiate a garbage collection. GEN may be provided for compatibility with
241   generational garbage collectors, but is ignored in this implementation."
242   (sub-gc :gen (if full 6 gen)))
243
244 (defun unsafe-clear-roots ()
245   ;; KLUDGE: Do things in an attempt to get rid of extra roots. Unsafe
246   ;; as having these cons more then we have space left leads to huge
247   ;; badness.
248   (scrub-control-stack)
249   ;; FIXME: CTYPE-OF-CACHE-CLEAR isn't thread-safe.
250   #!-sb-thread
251   (ctype-of-cache-clear))
252
253 \f
254 ;;;; auxiliary functions
255
256 (defun bytes-consed-between-gcs ()
257   #!+sb-doc
258   "Return the amount of memory that will be allocated before the next garbage
259    collection is initiated. This can be set with SETF."
260   (sb!alien:extern-alien "bytes_consed_between_gcs"
261                          (sb!alien:unsigned 32)))
262
263 (defun (setf bytes-consed-between-gcs) (val)
264   (declare (type index val))
265   (setf (sb!alien:extern-alien "bytes_consed_between_gcs"
266                                (sb!alien:unsigned 32))
267         val))
268
269 (declaim (inline maybe-handle-pending-gc))
270 (defun maybe-handle-pending-gc ()
271   (when (and (not *gc-inhibit*)
272              (or #!+sb-thread *stop-for-gc-pending*
273                  *gc-pending*))
274     (sb!unix::receive-pending-interrupt)))
275
276 ;;; These work both regardless of whether we're inside WITHOUT-GCING
277 ;;; or not.
278 (defun gc-on ()
279   #!+sb-doc
280   "Enable the garbage collector."
281   (setq *gc-inhibit* nil)
282   (maybe-handle-pending-gc)
283   nil)
284
285 (defun gc-off ()
286   #!+sb-doc
287   "Disable the garbage collector."
288   (setq *gc-inhibit* t)
289   nil)