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 (sb!unix::syscall* ("interrupt_thread"
305 sb!alien:unsigned-long sb!alien:unsigned-long)
307 thread (sb!kernel:get-lisp-obj-address
308 (coerce function 'function))))
309 (defun terminate-thread (thread-id)
310 "Terminate the thread identified by THREAD-ID, by causing it to run
311 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
312 (interrupt-thread thread-id 'sb!ext:quit))
314 (declaim (inline current-thread-id))
315 (defun current-thread-id ()
318 (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
319 ;; KLUDGE pids are 16 bit really. Avoid boxing the return value
322 ;;;; iterate over the in-memory threads
324 (defun mapcar-threads (function)
325 "Call FUNCTION once for each known thread, giving it the thread structure as argument"
326 (let ((function (coerce function 'function)))
327 (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
328 then (sb!sys:sap-ref-sap thread (* 4 sb!vm::thread-next-slot))
329 until (sb!sys:sap= thread (sb!sys:int-sap 0))
330 collect (funcall function thread))))
332 ;;;; job control, independent listeners
337 (interactive-threads nil)
338 (interactive-threads-queue (make-waitqueue)))
340 (defun new-session ()
341 (let ((tid (current-thread-id)))
342 (make-session :threads (list tid)
343 :interactive-threads (list tid))))
345 (defun init-job-control ()
346 (setf *session* (new-session)))
348 (defun %delete-thread-from-session (tid)
349 (with-mutex ((session-lock *session*))
350 (setf (session-threads *session*)
351 (delete tid (session-threads *session*))
352 (session-interactive-threads *session*)
353 (delete tid (session-interactive-threads *session*)))))
355 (defun call-with-new-session (fn)
356 (%delete-thread-from-session (current-thread-id))
357 (let ((*session* (new-session))) (funcall fn)))
359 (defmacro with-new-session (args &body forms)
360 (declare (ignore args)) ;for extensibility
361 (sb!int:with-unique-names (fb-name)
362 `(labels ((,fb-name () ,@forms))
363 (call-with-new-session (function ,fb-name)))))
365 ;;; this is called from a C signal handler: some signals may be masked
366 (defun handle-thread-exit (tid)
367 "Remove thread id TID from the session, if it's there"
368 (%delete-thread-from-session tid))
370 (defun terminate-session ()
371 "Kill all threads in session exept for this one. Does nothing if current
372 thread is not the foreground thread"
373 (let* ((tid (current-thread-id))
375 (with-mutex ((session-lock *session*))
376 (and (eql tid (car (session-interactive-threads *session*)))
377 (session-threads *session*)))))
378 ;; do the kill after dropping the mutex; unwind forms in dying
379 ;; threads may want to do session things
381 (unless (eql p tid) (terminate-thread p)))))
383 ;;; called from top of invoke-debugger
384 (defun debugger-wait-until-foreground-thread (stream)
385 "Returns T if thread had been running in background, NIL if it was
387 (declare (ignore stream))
389 (with-mutex ((session-lock *session*))
390 (not (member (current-thread-id)
391 (session-interactive-threads *session*))))
395 (defun get-foreground ()
396 (let ((was-foreground t))
398 (with-mutex ((session-lock *session*))
399 (let ((tid (current-thread-id))
400 (int-t (session-interactive-threads *session*)))
401 (when (eql (car int-t) tid)
402 (unless was-foreground
403 (format *query-io* "Resuming thread ~A~%" tid))
404 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
405 (return-from get-foreground t))
406 (setf was-foreground nil)
407 (unless (member tid int-t)
408 (setf (cdr (last int-t))
411 (session-interactive-threads-queue *session*)
412 (session-lock *session*)))))))
414 (defun release-foreground (&optional next)
415 "Background this thread. If NEXT is supplied, arrange for it to have the foreground next"
416 (with-mutex ((session-lock *session*))
417 (let ((tid (current-thread-id)))
418 (setf (session-interactive-threads *session*)
419 (delete tid (session-interactive-threads *session*)))
420 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
422 (setf (session-interactive-threads *session*)
424 (delete next (session-interactive-threads *session*)))))
425 (condition-broadcast (session-interactive-threads-queue *session*)))))
427 (defun make-listener-thread (tty-name)
428 (assert (probe-file tty-name))
429 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
430 (out (sb!unix:unix-dup in))
431 (err (sb!unix:unix-dup in)))
432 (labels ((thread-repl ()
433 (sb!unix::unix-setsid)
434 (let* ((sb!impl::*stdin*
435 (sb!sys:make-fd-stream in :input t :buffering :line))
437 (sb!sys:make-fd-stream out :output t :buffering :line))
439 (sb!sys:make-fd-stream err :output t :buffering :line))
441 (sb!sys:make-fd-stream err :input t :output t :buffering :line))
442 (sb!impl::*descriptor-handlers* nil))
444 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
446 (sb!impl::toplevel-repl nil)
447 (sb!int:flush-standard-output-streams))))))
448 (make-thread #'thread-repl))))