Debian Codegraph @

src/lsp/mp.lsp

raw
1 ;;;; -*- Mode: Lisp; Syntax: Common-Lisp; indent-tabs-mode: nil; Package: SYSTEM -*-
2 ;;;; vim: set filetype=lisp tabstop=8 shiftwidth=2 expandtab:
3
4 ;;;;
5 ;;;; MP.LSP -- Multiprocessing capabilities.
6
7 ;;;; Copyright (c) 2003, Juan Jose Garcia-Ripoll
8 ;;;;
9 ;;;; See file 'LICENSE' for the copyright details.
10
11 #-threads
12 (defpackage "MP"
13 (:use "CL" "SI")
14 (:export "WITH-LOCK"))
15
16 (in-package "MP")
17
18 ;;;
19 ;;; Interrupt disabling and enabling
20 ;;;
21 (defmacro without-interrupts (&body body)
22 #!+sb-doc
23 "Executes BODY with all deferrable interrupts disabled. Deferrable
24 interrupts arriving during execution of the BODY take effect after BODY has
25 been executed.
26
27 Deferrable interrupts include most blockable POSIX signals, and
28 MP:INTERRUPT-PROCESS. Does not interfere with garbage collection, and
29 unlike in many traditional Lisps using userspace threads, in ECL
30 WITHOUT-INTERRUPTS does not inhibit scheduling of other threads.
31
32 Binds ALLOW-WITH-INTERRUPTS, WITH-LOCAL-INTERRUPTS and WITH-RESTORED-INTERRUPTS
33 as a local macros.
34
35 WITH-RESTORED-INTERRUPTS executes the body with interrupts enabled if and only
36 if the WITHOUT-INTERRUPTS was in an environment in which interrupts were allowed.
37
38 ALLOW-WITH-INTERRUPTS allows the WITH-INTERRUPTS to take effect during the
39 dynamic scope of its body, unless there is an outer WITHOUT-INTERRUPTS without
40 a corresponding ALLOW-WITH-INTERRUPTS.
41
42 WITH-LOCAL-INTERRUPTS executes its body with interrupts enabled provided that
43 there is an ALLOW-WITH-INTERRUPTS for every WITHOUT-INTERRUPTS surrounding
44 the current one. WITH-LOCAL-INTERRUPTS is equivalent to:
45
46 (allow-with-interrupts (with-interrupts ...))
47
48 Care must be taken not to let either ALLOW-WITH-INTERRUPTS or
49 WITH-LOCAL-INTERRUPTS appear in a function that escapes from inside the
50 WITHOUT-INTERRUPTS in:
51
52 (without-interrupts
53 ;; The body of the lambda would be executed with WITH-INTERRUPTS allowed
54 ;; regardless of the interrupt policy in effect when it is called.
55 (lambda () (allow-with-interrupts ...)))
56
57 (without-interrupts
58 ;; The body of the lambda would be executed with interrupts enabled
59 ;; regardless of the interrupt policy in effect when it is called.
60 (lambda () (with-local-interrupts ...)))
61 "
62 (ext:with-unique-names (outer-allow-with-interrupts outer-interrupts-enabled)
63 `(multiple-value-prog1
64 (macrolet ((allow-with-interrupts (&body allow-forms)
65 `(let ((si:*allow-with-interrupts* ,',outer-allow-with-interrupts))
66 ,@allow-forms))
67 (with-restored-interrupts (&body with-forms)
68 `(let ((si:*interrupts-enabled* ,',outer-interrupts-enabled))
69 ,@with-forms))
70 (with-local-interrupts (&body with-forms)
71 `(let* ((si:*allow-with-interrupts* ,',outer-allow-with-interrupts)
72 (si:*interrupts-enabled* ,',outer-allow-with-interrupts))
73 (when ,',outer-allow-with-interrupts
74 (si::check-pending-interrupts))
75 (locally ,@with-forms))))
76 (let* ((,outer-interrupts-enabled si:*interrupts-enabled*)
77 (si:*interrupts-enabled* nil)
78 (,outer-allow-with-interrupts si:*allow-with-interrupts*)
79 (si:*allow-with-interrupts* nil))
80 (declare (ignorable ,outer-allow-with-interrupts
81 ,outer-interrupts-enabled))
82 ,@body))
83 (when si:*interrupts-enabled*
84 (si::check-pending-interrupts)))))
85
86 (defmacro with-interrupts (&body body)
87 "Executes BODY with deferrable interrupts conditionally enabled. If there
88 are pending interrupts they take effect prior to executing BODY.
89
90 As interrupts are normally allowed WITH-INTERRUPTS only makes sense if there
91 is an outer WITHOUT-INTERRUPTS with a corresponding ALLOW-WITH-INTERRUPTS:
92 interrupts are not enabled if any outer WITHOUT-INTERRUPTS is not accompanied
93 by ALLOW-WITH-INTERRUPTS."
94 (ext:with-unique-names (allowp enablep)
95 ;; We could manage without ENABLEP here, but that would require
96 ;; taking extra care not to ever have *ALLOW-WITH-INTERRUPTS* NIL
97 ;; and *INTERRUPTS-ENABLED* T -- instead of risking future breakage
98 ;; we take the tiny hit here.
99 `(let* ((,allowp si:*allow-with-interrupts*)
100 (,enablep si:*interrupts-enabled*)
101 (si:*interrupts-enabled* (or ,enablep ,allowp)))
102 (when (and ,allowp (not ,enablep))
103 (si::check-pending-interrupts))
104 (locally ,@body))))
105
106
107 ;;;
108 ;;; Convenience macros for locks
109 ;;;
110 (defmacro with-lock ((lock-form &key (wait-form t)) &body body)
111 #-threads
112 `(progn ,@body)
113 ;; We do our best to make sure that the lock is released if we are
114 ;; interrupted and jump up the call stack, however there is an
115 ;; unavoidable race condition if the interrupt happens after the
116 ;; mutex is locked but before we store the return value of
117 ;; mp:get-lock.
118 #+threads
119 (ext:with-unique-names (lock wait)
120 `(let ((,lock ,lock-form)
121 (,wait ,wait-form))
122 (when (mp:get-lock ,lock ,wait)
123 (without-interrupts
124 (unwind-protect
125 (with-restored-interrupts
126 (locally ,@body))
127 (mp:giveup-lock ,lock)))))))
128
129 #+ecl-read-write-lock
130 (defmacro with-rwlock ((lock op) &body body)
131 "Acquire rwlock for the dynamic scope of BODY for operation OP,
132 which is executed with the lock held by current thread, and
133 WITH-RWLOCK returns the values of body.
134
135 Valid values of argument OP are :READ or :WRITE
136 \(for reader and writer access accordingly)."
137 (assert (member op '(:read :write) :test #'eq))
138 (let ((s-lock (gensym)))
139 `(let ((,s-lock ,lock))
140 (,(if (eq :read op)
141 'mp:get-rwlock-read
142 'mp:get-rwlock-write)
143 ,s-lock t)
144 (mp:without-interrupts
145 (unwind-protect
146 (mp:with-restored-interrupts
147 ,@body)
148 (,(if (eq :read op)
149 'mp:giveup-rwlock-read
150 'mp:giveup-rwlock-write)
151 ,s-lock))))))
152
153 ;;;
154 ;;; Atomic operations
155 ;;;
156 #+threads
157 (defmacro define-cas-expander (accessor lambda-list &body body)
158 "Define a COMPARE-AND-SWAP expander similar to DEFINE-SETF-EXPANDER.
159 Syntax: (define-cas-expander accessor lambda-list {decl | doc}*
160 {form}*)
161 Defines the COMPARE-AND-SWAP-expander for generalized-variables (ACCESSOR ...).
162 When a form (compare-and-swap (ACCESSOR arg1 ... argn) old new) is evaluated, the FORMs
163 given in the DEFINE-CAS-EXPANDER are evaluated in order with the parameters in
164 LAMBDA-LIST bound to ARG1 ... ARGn. The last FORM must return six
165 values
166 (var1 ... vark)
167 (form1 ... formk)
168 old-var
169 new-var
170 compare-and-swap-form
171 volatile-access-form
172 in order (Note that old-var and new-var are single variables, unlike
173 in DEFINE-SETF-EXPANDER). The whole COMPARE-AND-SWAP form is then
174 expanded into
175 (let* ((var1 from1) ... (vark formk)
176 (old-var old-form)
177 (new-var new-form))
178 compare-and-swap-form).
179 Note that it is up to the user of this macro to ensure atomicity for
180 the resulting COMPARE-AND-SWAP expansions."
181 (let ((env (member '&environment lambda-list :test #'eq)))
182 (if env
183 (setq lambda-list (cons (second env)
184 (nconc (ldiff lambda-list env) (cddr env))))
185 (progn
186 (setq env (gensym))
187 (setq lambda-list (cons env lambda-list))
188 (push `(declare (ignore ,env)) body))))
189 `(eval-when (:compile-toplevel :load-toplevel :execute)
190 (let ((package (symbol-package ',accessor)))
191 (when (and package
192 (ext:package-locked-p package)
193 (null si:*ignore-package-locks*))
194 (si:signal-simple-error 'package-error
195 "Ignore lock and proceed."
196 "Attempt to define CAS accessor ~S in locked package."
197 '(,accessor)
198 :package package)))
199 (si:put-sysprop ',accessor 'CAS-EXPANDER
200 ,(multiple-value-bind (decls body)
201 (si::find-declarations body)
202 `#'(lambda ,lambda-list
203 ,@decls
204 (block ,accessor ,@body))))
205 ',accessor))
206
207 #+threads
208 (defmacro defcas (accessor cas-fun &optional documentation)
209 "Define a COMPARE-AND-SWAP expansion similar to the short form of DEFSETF.
210 Syntax: (defsetf accessor cas-fun)
211 Defines an expansion
212 (compare-and-swap (ACCESSOR arg1 ... argn) old new)
213 => (CAS-FUN arg1 ... argn old new)
214 Note that it is up to the user of this macro to ensure atomicity for
215 the resulting COMPARE-AND-SWAP expansions."
216 (declare (ignore documentation))
217 `(define-cas-expander ,accessor (&rest args)
218 (let ((old (gensym)) (new (gensym)))
219 (values nil nil old new
220 `(,',cas-fun ,@args ,old ,new)
221 `(,',accessor ,@args)))))
222
223 ;; XXX - Hacky way to determine at macroexpand time whether place is a
224 ;; special variable (works for both bytecodes and native compiler). To
225 ;; be replaced by a better way once the cltl2 environment access is
226 ;; implemented (see issue #63). -- mg 2019-10-31
227 (defun special-variable-p (place)
228 (declare (si::c-local))
229 (and (symbolp place)
230 (or (and (fboundp 'c::special-variable-p)
231 (c::special-variable-p place))
232 (si:specialp place))))
233
234 #+threads
235 (defun remcas (symbol)
236 "Remove a COMPARE-AND-SWAP expansion. It is a CAS operation equivalent of
237 (FMAKUNBOUND (SETF SYMBOL))"
238 (let ((package (symbol-package symbol)))
239 (when (and package
240 (ext:package-locked-p package)
241 (null si:*ignore-package-locks*))
242 (si:signal-simple-error 'package-error
243 "Ignore lock and proceed."
244 "Attempt to define CAS accessor ~S in locked package."
245 (list symbol)
246 :package package)))
247 (si:rem-sysprop symbol 'cas-expander))
248
249 #+threads
250 (defun get-cas-expansion (place &optional environment &aux f)
251 "Returns the COMPARE-AND-SWAP expansion forms and variables as defined
252 in DEFINE-CAS-EXPANDER for PLACE as six values."
253 (when (special-variable-p place)
254 (setf place `(symbol-value ',place)))
255 (cond ((and (listp place)
256 (setq f (si:get-sysprop (first place) 'CAS-EXPANDER)))
257 (apply f environment (rest place)))
258 ;; We try macro expansion with MACROEXPAND-1 as in SETF
259 ((and (setq f (macroexpand-1 place environment)) (not (equal f place)))
260 (get-cas-expansion f environment))
261 ;; Functions like (cas foo) analogous to (setf foo) are
262 ;; currently not supported, hence we throw an error here
263 (t (error "Cannot get the compare-and-swap expansion of ~S." place))))
264
265 (defmacro compare-and-swap (&environment env place old new)
266 "Atomically stores NEW in PLACE if OLD is eq to the current value of
267 PLACE. Returns the previous value of PLACE: if the returned value is
268 eq to OLD, the swap was carried out.
269
270 Currently, the following places are supported:
271
272 car, cdr, first, rest, svref, symbol-plist, symbol-value, slot-value,
273 clos:standard-instance-access, clos:funcallable-standard-instance-access,
274 a struct accessor or any other place for which a compare-and-swap
275 expansion was defined by defcas or define-cas-expander.
276
277 For slot-value, slot-unbound is called if the slot is unbound unless
278 OLD is eq to si:unbound, in which case OLD is returned and NEW is
279 assigned to the slot. Additionally, the object should have no
280 applicable methods defined for slot-value-using-class or (setf
281 slot-value-using-class)."
282 #+threads
283 (multiple-value-bind (vars vals old-var new-var cas-form)
284 (get-cas-expansion place env)
285 `(let* (,@(mapcar #'list vars vals)
286 (,old-var ,old)
287 (,new-var ,new))
288 ,cas-form))
289 #-threads
290 (let ((old-value (gensym)))
291 `(let ((,old-value ,place))
292 (when (eq ,old ,old-value)
293 (setf ,place ,new))
294 ,old-value)))
295
296 #+threads
297 (progn
298 (defcas car mp:compare-and-swap-car)
299 (defcas first mp:compare-and-swap-car)
300 (defcas cdr mp:compare-and-swap-cdr)
301 (defcas rest mp:compare-and-swap-cdr)
302 (defcas symbol-value mp:compare-and-swap-symbol-value)
303 (defcas symbol-plist mp:compare-and-swap-symbol-plist)
304 (defcas svref mp:compare-and-swap-svref)
305 (defcas slot-value mp::compare-and-swap-slot-value)
306 (defcas clos:standard-instance-access mp::compare-and-swap-standard-instance)
307 (defcas clos:funcallable-standard-instance-access mp::compare-and-swap-standard-instance))
308
309 (defmacro atomic-update (place update-fn &rest arguments)
310 "Atomically updates the CAS-able PLACE to the value returned by calling UPDATE-FN with ARGUMENTS and the old value of PLACE. UPDATE-FN must be a function accepting (1+ (length ARGUMENTS)) arguments. Returns the new value which was stored in PLACE.
311
312 PLACE may be read and UPDATE-FN may be called more than once if multiple threads are trying to write to PLACE at the same time."
313 #+threads
314 (let ((new (gensym))
315 (old (gensym)))
316 `(let ((,old ,place))
317 (loop for ,new = (funcall ,update-fn ,@arguments ,old)
318 until (eq ,old (setf ,old (compare-and-swap ,place ,old ,new)))
319 finally (return ,new))))
320 #-threads
321 `(setf ,place (funcall ,update-fn ,@arguments ,place)))
322
323 (defmacro atomic-push (obj place)
324 "Like PUSH, but atomic. PLACE must be CAS-able and may be read
325 multiple times before the update succeeds."
326 #+threads
327 (let ((new (gensym))
328 (old (gensym)))
329 `(let* ((,old ,place)
330 (,new (cons ,obj ,old)))
331 (loop until (eq ,old (setf ,old (compare-and-swap ,place ,old ,new)))
332 do (setf (cdr ,new) ,old)
333 finally (return ,new))))
334 #-threads
335 `(push ,obj ,place))
336
337 (defmacro atomic-pop (place)
338 "Like POP, but atomic. PLACE must be CAS-able and may be read
339 multiple times before the update succeeds."
340 #+threads
341 (let ((new (gensym))
342 (old (gensym)))
343 `(let* ((,old ,place))
344 (loop for ,new = (cdr ,old)
345 until (eq ,old (setf ,old (compare-and-swap ,place ,old ,new)))
346 finally (return (car (ext:truly-the list ,old))))))
347 #-threads
348 `(pop ,place))
349
350 (defmacro atomic-incf (place &optional (increment 1))
351 "Atomically increments the fixnum stored in PLACE by the given
352 INCREMENT and returns the value of PLACE before the increment.
353 Incrementing is done using modular arithmetic, so that atomic-incf of
354 a place whose value is most-positive-fixnum by 1 results in
355 most-negative-fixnum stored in place.
356
357 Currently the following places are supported:
358 car, cdr, first, rest, svref, symbol-value, slot-value,
359 clos:standard-instance-access, clos:funcallable-standard-instance-access.
360
361 For slot-value, the object should have no applicable methods defined
362 for slot-value-using-class or (setf slot-value-using-class).
363
364 The consequences are undefined if the value of PLACE is not of type
365 fixnum."
366 #+threads
367 (progn
368 (setf place (macroexpand place))
369 (when (special-variable-p place)
370 (setf place `(symbol-value ',place)))
371 (let ((fun (when (listp place)
372 (case (first place)
373 ((car first) 'mp:atomic-incf-car)
374 ((cdr rest) 'mp:atomic-incf-cdr)
375 (symbol-value 'mp:atomic-incf-symbol-value)
376 (svref 'mp:atomic-incf-svref)
377 (slot-value 'mp::atomic-incf-slot-value)
378 ((clos:standard-instance-access clos:funcallable-standard-instance-access) 'mp::atomic-incf-standard-instance)))))
379 (unless fun
380 (error "No ATOMIC-INCF expansion defined for place ~S." place))
381 `(,fun ,@(rest place) ,increment)))
382 #-threads
383 (let ((value (gensym))
384 (incr (gensym)))
385 `(let ((,value ,place)
386 (,incr ,increment))
387 (declare (fixnum ,value ,incr))
388 (setf ,place (+ (mod (+ ,value ,incr most-negative-fixnum)
389 (* -2 most-negative-fixnum))
390 most-negative-fixnum))
391 ,value)))
392
393 (defmacro atomic-decf (place &optional (decrement 1))
394 "Atomically decrements the fixnum stored in PLACE by the given
395 DECREMENT and returns the value of PLACE before the decrement.
396 Decrementing is done using modular arithmetic, so that atomic-decf of
397 a place whose value is most-negative-fixnum by 1 results in
398 most-positive-fixnum stored in place.
399
400 Currently the following places are supported:
401 car, cdr, first, rest, svref, symbol-value, slot-value,
402 clos:standard-instance-access, clos:funcallable-standard-instance-access.
403
404 For slot-value, the object should have no applicable methods defined
405 for slot-value-using-class or (setf slot-value-using-class).
406
407 The consequences are undefined if the value of PLACE is not of type
408 fixnum."
409 `(atomic-incf ,place (- ,decrement)))