1 ;;;; support for threads in the target machine
3 ;;;; This software is part of the SBCL system. See the README file for
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!THREAD")
14 ;;; FIXME it would be good to define what a thread id is or isn't (our
15 ;;; current assumption is that it's a fixnum). It so happens that on
16 ;;; Linux it's a pid, but it might not be on posix thread implementations
18 (define-alien-routine ("create_thread" %create-thread)
20 (lisp-fun-address unsigned-long))
22 (define-alien-routine "signal_thread_to_dequeue"
24 (thread-id unsigned-long))
26 (defvar *session* nil)
30 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
31 (declaim (inline get-spinlock release-spinlock))
33 (defun get-spinlock (lock offset new-value)
34 (declare (optimize (speed 3) (safety 0)))
36 (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
38 ;; this should do nothing if we didn't own the lock, so safe to use in
39 ;; unwind-protect cleanups when lock acquisition failed for some reason
40 (defun release-spinlock (lock offset our-value)
41 (declare (optimize (speed 3) (safety 0)))
42 (sb!vm::%instance-set-conditional lock offset our-value 0))
44 (defmacro with-spinlock ((queue) &body body)
45 (with-unique-names (pid)
46 `(let ((,pid (current-thread-id)))
49 (get-spinlock ,queue 2 ,pid)
51 (release-spinlock ,queue 2 ,pid)))))
54 ;;;; the higher-level locking operations are based on waitqueues
56 (declaim (inline waitqueue-data-address mutex-value-address))
59 (name nil :type (or null simple-base-string))
63 ;;; The bare 4 here and 5 below are offsets of the slots in the struct.
64 ;;; There ought to be some better way to get these numbers
65 (defun waitqueue-data-address (lock)
66 (declare (optimize (speed 3)))
69 (+ (sb!kernel:get-lisp-obj-address lock)
70 (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
72 (defstruct (mutex (:include waitqueue))
75 (defun mutex-value-address (lock)
76 (declare (optimize (speed 3)))
79 (+ (sb!kernel:get-lisp-obj-address lock)
80 (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
82 (sb!alien:define-alien-routine "block_sigcont" void)
83 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep" void)
86 (declaim (inline futex-wait futex-wake))
88 (sb!alien:define-alien-routine
89 "futex_wait" int (word unsigned-long) (old-value unsigned-long))
91 (sb!alien:define-alien-routine
92 "futex_wake" int (word unsigned-long) (n unsigned-long))
95 ;;; this should only be called while holding the queue spinlock.
96 ;;; it releases the spinlock before sleeping
97 (defun wait-on-queue (queue &optional lock)
98 (let ((pid (current-thread-id)))
100 (when lock (release-mutex lock))
101 (sb!sys:without-interrupts
102 (pushnew pid (waitqueue-data queue)))
103 (setf (waitqueue-lock queue) 0)
104 (unblock-sigcont-and-sleep)))
106 ;;; this should only be called while holding the queue spinlock. It doesn't
108 (defun dequeue (queue)
109 (let ((pid (current-thread-id)))
110 (sb!sys:without-interrupts
111 (setf (waitqueue-data queue)
112 (delete pid (waitqueue-data queue))))))
114 ;;; this should only be called while holding the queue spinlock.
115 (defun signal-queue-head (queue)
116 (let ((p (car (waitqueue-data queue))))
117 (when p (signal-thread-to-dequeue p))))
121 ;;; i suspect there may be a race still in this: the futex version requires
122 ;;; the old mutex value before sleeping, so how do we get away without it
123 (defun get-mutex (lock &optional new-value (wait-p t))
124 (declare (type mutex lock) (optimize (speed 3)))
125 (let ((pid (current-thread-id)))
126 (unless new-value (setf new-value pid))
127 (assert (not (eql new-value (mutex-value lock))))
128 (get-spinlock lock 2 pid)
131 ;; args are object slot-num old-value new-value
132 (sb!vm::%instance-set-conditional lock 4 nil new-value)
134 (setf (waitqueue-lock lock) 0)
137 (setf (waitqueue-lock lock) 0)
139 (wait-on-queue lock nil))))
142 (defun get-mutex/futex (lock &optional new-value (wait-p t))
143 (declare (type mutex lock) (optimize (speed 3)))
144 (let ((pid (current-thread-id))
146 (unless new-value (setf new-value pid))
147 (assert (not (eql new-value (mutex-value lock))))
150 (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
152 (unless wait-p (return nil))
153 (futex-wait (mutex-value-address lock)
154 (sb!kernel:get-lisp-obj-address old)))))
156 (defun release-mutex (lock &optional (new-value nil))
157 (declare (type mutex lock))
158 ;; we assume the lock is ours to release
159 (with-spinlock (lock)
160 (setf (mutex-value lock) new-value)
161 (signal-queue-head lock)))
164 (defun release-mutex/futex (lock)
165 (declare (type mutex lock))
166 (setf (mutex-value lock) nil)
167 (futex-wake (mutex-value-address lock) 1))
169 ;;;; condition variables
171 (defun condition-wait (queue lock)
172 "Atomically release LOCK and enqueue ourselves on QUEUE. Another
173 thread may subsequently notify us using CONDITION-NOTIFY, at which
174 time we reacquire LOCK and return to the caller."
176 (let ((value (mutex-value lock)))
179 (get-spinlock queue 2 (current-thread-id))
180 (wait-on-queue queue lock))
181 ;; If we are interrupted while waiting, we should do these things
182 ;; before returning. Ideally, in the case of an unhandled signal,
183 ;; we should do them before entering the debugger, but this is
184 ;; better than nothing.
185 (with-spinlock (queue)
187 (get-mutex lock value))))
190 (defun condition-wait/futex (queue lock)
192 (let ((value (mutex-value lock)))
194 (let ((me (current-thread-id)))
195 ;; XXX we should do something to ensure that the result of this setf
196 ;; is visible to all CPUs
197 (setf (waitqueue-data queue) me)
199 ;; Now we go to sleep using futex-wait. If anyone else
200 ;; manages to grab LOCK and call CONDITION-NOTIFY during
201 ;; this comment, it will change queue->data, and so
202 ;; futex-wait returns immediately instead of sleeping.
203 ;; Ergo, no lost wakeup
204 (futex-wait (waitqueue-data-address queue)
205 (sb!kernel:get-lisp-obj-address me)))
206 ;; If we are interrupted while waiting, we should do these things
207 ;; before returning. Ideally, in the case of an unhandled signal,
208 ;; we should do them before entering the debugger, but this is
209 ;; better than nothing.
210 (get-mutex lock value))))
213 (defun condition-notify (queue)
214 "Notify one of the processes waiting on QUEUE"
215 (with-spinlock (queue) (signal-queue-head queue)))
218 (defun condition-notify/futex (queue)
219 "Notify one of the processes waiting on QUEUE."
220 (let ((me (current-thread-id)))
221 ;; no problem if >1 thread notifies during the comment in
222 ;; condition-wait: as long as the value in queue-data isn't the
223 ;; waiting thread's id, it matters not what it is
224 ;; XXX we should do something to ensure that the result of this setf
225 ;; is visible to all CPUs
226 (setf (waitqueue-data queue) me)
227 (futex-wake (waitqueue-data-address queue) 1)))
230 (defun condition-broadcast/futex (queue)
231 (let ((me (current-thread-id)))
232 (setf (waitqueue-data queue) me)
233 (futex-wake (waitqueue-data-address queue) (ash 1 30))))
235 (defun condition-broadcast (queue)
236 "Notify all of the processes waiting on QUEUE."
237 (with-spinlock (queue)
238 (map nil #'signal-thread-to-dequeue (waitqueue-data queue))))
240 ;;; Futexes may be available at compile time but not runtime, so we
241 ;;; default to not using them unless os_init says they're available
242 (defun maybe-install-futex-functions ()
244 (unless (zerop (extern-alien "linux_supports_futex" int))
245 (setf (fdefinition 'get-mutex) #'get-mutex/futex
246 (fdefinition 'release-mutex) #'release-mutex/futex
247 (fdefinition 'condition-wait) #'condition-wait/futex
248 (fdefinition 'condition-broadcast) #'condition-broadcast/futex
249 (fdefinition 'condition-notify) #'condition-notify/futex)
252 (defun make-thread (function)
253 (let* ((real-function (coerce function 'function))
256 (sb!kernel:get-lisp-obj-address
258 ;; in time we'll move some of the binding presently done in C
260 (let ((sb!kernel::*restart-clusters* nil)
261 (sb!impl::*descriptor-handlers* nil) ; serve-event
262 (sb!impl::*available-buffers* nil)) ;for fd-stream
263 ;; can't use handling-end-of-the-world, because that flushes
264 ;; output streams, and we don't necessarily have any (or we
265 ;; could be sharing them)
266 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
268 (catch 'sb!impl::%end-of-the-world
271 (format nil "~~@<Destroy this thread (~A)~~@:>"
272 (current-thread-id)))
273 (funcall real-function))
275 (with-mutex ((session-lock *session*))
276 (pushnew tid (session-threads *session*)))
279 ;;; Really, you don't want to use these: they'll get into trouble with
280 ;;; garbage collection. Use a lock or a waitqueue instead
281 (defun suspend-thread (thread-id)
282 (sb!unix:unix-kill thread-id sb!unix:sigstop))
283 (defun resume-thread (thread-id)
284 (sb!unix:unix-kill thread-id sb!unix:sigcont))
285 ;;; Note warning about cleanup forms
286 (defun destroy-thread (thread-id)
287 "Destroy the thread identified by THREAD-ID abruptly, without running cleanup forms"
288 (sb!unix:unix-kill thread-id sb!unix:sigterm)
289 ;; may have been stopped for some reason, so now wake it up to
291 (sb!unix:unix-kill thread-id sb!unix:sigcont))
296 ;;; a moderate degree of care is expected for use of interrupt-thread,
297 ;;; due to its nature: if you interrupt a thread that was holding
298 ;;; important locks then do something that turns out to need those
299 ;;; locks, you probably won't like the effect. Used with thought
300 ;;; though, it's a good deal gentler than the last-resort functions above
302 (defun interrupt-thread (thread function)
303 "Interrupt THREAD and make it run FUNCTION."
304 (let ((function (coerce function 'function)))
305 (sb!sys:with-pinned-objects (function)
306 (sb!unix::syscall* ("interrupt_thread"
307 sb!alien:unsigned-long sb!alien:unsigned-long)
310 (sb!kernel:get-lisp-obj-address function)))))
312 (defun terminate-thread (thread-id)
313 "Terminate the thread identified by THREAD-ID, by causing it to run
314 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
315 (interrupt-thread thread-id 'sb!ext:quit))
317 (declaim (inline current-thread-id))
318 (defun current-thread-id ()
321 (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
322 ;; KLUDGE pids are 16 bit really. Avoid boxing the return value
325 ;;;; iterate over the in-memory threads
327 (defun mapcar-threads (function)
328 "Call FUNCTION once for each known thread, giving it the thread structure as argument"
329 (let ((function (coerce function 'function)))
330 (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
331 then (sb!sys:sap-ref-sap thread (* 4 sb!vm::thread-next-slot))
332 until (sb!sys:sap= thread (sb!sys:int-sap 0))
333 collect (funcall function thread))))
335 ;;;; job control, independent listeners
340 (interactive-threads nil)
341 (interactive-threads-queue (make-waitqueue)))
343 (defun new-session ()
344 (let ((tid (current-thread-id)))
345 (make-session :threads (list tid)
346 :interactive-threads (list tid))))
348 (defun init-job-control ()
349 (setf *session* (new-session)))
351 (defun %delete-thread-from-session (tid)
352 (with-mutex ((session-lock *session*))
353 (setf (session-threads *session*)
354 (delete tid (session-threads *session*))
355 (session-interactive-threads *session*)
356 (delete tid (session-interactive-threads *session*)))))
358 (defun call-with-new-session (fn)
359 (%delete-thread-from-session (current-thread-id))
360 (let ((*session* (new-session))) (funcall fn)))
362 (defmacro with-new-session (args &body forms)
363 (declare (ignore args)) ;for extensibility
364 (sb!int:with-unique-names (fb-name)
365 `(labels ((,fb-name () ,@forms))
366 (call-with-new-session (function ,fb-name)))))
368 ;;; this is called from a C signal handler: some signals may be masked
369 (defun handle-thread-exit (tid)
370 "Remove thread id TID from the session, if it's there"
371 (%delete-thread-from-session tid))
373 (defun terminate-session ()
374 "Kill all threads in session exept for this one. Does nothing if current
375 thread is not the foreground thread"
376 (let* ((tid (current-thread-id))
378 (with-mutex ((session-lock *session*))
379 (and (eql tid (car (session-interactive-threads *session*)))
380 (session-threads *session*)))))
381 ;; do the kill after dropping the mutex; unwind forms in dying
382 ;; threads may want to do session things
384 (unless (eql p tid) (terminate-thread p)))))
386 ;;; called from top of invoke-debugger
387 (defun debugger-wait-until-foreground-thread (stream)
388 "Returns T if thread had been running in background, NIL if it was
390 (declare (ignore stream))
392 (with-mutex ((session-lock *session*))
393 (not (member (current-thread-id)
394 (session-interactive-threads *session*))))
398 (defun get-foreground ()
399 (let ((was-foreground t))
401 (with-mutex ((session-lock *session*))
402 (let ((tid (current-thread-id))
403 (int-t (session-interactive-threads *session*)))
404 (when (eql (car int-t) tid)
405 (unless was-foreground
406 (format *query-io* "Resuming thread ~A~%" tid))
407 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
408 (return-from get-foreground t))
409 (setf was-foreground nil)
410 (unless (member tid int-t)
411 (setf (cdr (last int-t))
414 (session-interactive-threads-queue *session*)
415 (session-lock *session*)))))))
417 (defun release-foreground (&optional next)
418 "Background this thread. If NEXT is supplied, arrange for it to have the foreground next"
419 (with-mutex ((session-lock *session*))
420 (let ((tid (current-thread-id)))
421 (setf (session-interactive-threads *session*)
422 (delete tid (session-interactive-threads *session*)))
423 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
425 (setf (session-interactive-threads *session*)
427 (delete next (session-interactive-threads *session*)))))
428 (condition-broadcast (session-interactive-threads-queue *session*)))))
430 (defun make-listener-thread (tty-name)
431 (assert (probe-file tty-name))
432 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
433 (out (sb!unix:unix-dup in))
434 (err (sb!unix:unix-dup in)))
435 (labels ((thread-repl ()
436 (sb!unix::unix-setsid)
437 (let* ((sb!impl::*stdin*
438 (sb!sys:make-fd-stream in :input t :buffering :line))
440 (sb!sys:make-fd-stream out :output t :buffering :line))
442 (sb!sys:make-fd-stream err :output t :buffering :line))
444 (sb!sys:make-fd-stream err :input t :output t :buffering :line))
445 (sb!impl::*descriptor-handlers* nil))
447 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
449 (sb!impl::toplevel-repl nil)
450 (sb!int:flush-standard-output-streams))))))
451 (make-thread #'thread-repl))))