1 (in-package "SB!THREAD")
3 ;;; FIXME it would be good to define what a thread id is or isn't (our
4 ;;; current assumption is that it's a fixnum). It so happens that on
5 ;;; Linux it's a pid, but it might not be on posix thread implementations
7 (sb!alien::define-alien-routine ("create_thread" %create-thread)
9 (lisp-fun-address sb!alien:unsigned-long))
11 (sb!alien::define-alien-routine "signal_thread_to_dequeue"
13 (thread-pid sb!alien:unsigned-long))
16 (defun make-thread (function)
17 (let ((real-function (coerce function 'function)))
19 (sb!kernel:get-lisp-obj-address
21 ;; in time we'll move some of the binding presently done in C
23 (let ((sb!kernel::*restart-clusters* nil)
24 (sb!impl::*descriptor-handlers* nil); serve-event
25 (sb!impl::*available-buffers* nil)) ;for fd-stream
26 ;; can't use handling-end-of-the-world, because that flushes
27 ;; output streams, and we don't necessarily have any (or we
28 ;; could be sharing them)
29 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
31 (catch 'sb!impl::%end-of-the-world
34 (format nil "~~@<Destroy this thread (~A)~~@:>"
36 (funcall real-function))
39 ;;; Really, you don't want to use these: they'll get into trouble with
40 ;;; garbage collection. Use a lock or a waitqueue instead
41 (defun suspend-thread (thread-id)
42 (sb!unix:unix-kill thread-id sb!unix:sigstop))
43 (defun resume-thread (thread-id)
44 (sb!unix:unix-kill thread-id sb!unix:sigcont))
45 ;;; Note warning about cleanup forms
46 (defun destroy-thread (thread-id)
47 "Destroy the thread identified by THREAD-ID abruptly, without running cleanup forms"
48 (sb!unix:unix-kill thread-id sb!unix:sigterm)
49 ;; may have been stopped for some reason, so now wake it up to
51 (sb!unix:unix-kill thread-id sb!unix:sigcont))
54 ;;; a moderate degree of care is expected for use of interrupt-thread,
55 ;;; due to its nature: if you interrupt a thread that was holding
56 ;;; important locks then do something that turns out to need those
57 ;;; locks, you probably won't like the effect. Used with thought
58 ;;; though, it's a good deal gentler than the last-resort functions above
60 (defun interrupt-thread (thread function)
61 "Interrupt THREAD and make it run FUNCTION. "
62 (sb!unix::syscall* ("interrupt_thread"
63 sb!alien:unsigned-long sb!alien:unsigned-long)
65 thread (sb!kernel:get-lisp-obj-address
66 (coerce function 'function))))
67 (defun terminate-thread (thread-id)
68 "Terminate the thread identified by THREAD-ID, by causing it to run
69 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
70 (interrupt-thread thread-id 'sb!ext:quit))
72 (declaim (inline current-thread-id))
73 (defun current-thread-id ()
76 (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
77 ;; KLUDGE pids are 16 bit really. Avoid boxing the return value
80 ;;;; iterate over the in-memory threads
82 (defun mapcar-threads (function)
83 "Call FUNCTION once for each known thread, giving it the thread structure as argument"
84 (let ((function (coerce function 'function)))
85 (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
86 then (sb!sys:sap-ref-sap thread (* 4 sb!vm::thread-next-slot))
87 until (sb!sys:sap= thread (sb!sys:int-sap 0))
88 collect (funcall function thread))))
92 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
93 (declaim (inline get-spinlock release-spinlock))
95 (defun get-spinlock (lock offset new-value)
96 (declare (optimize (speed 3) (safety 0)))
98 (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
100 ;; this should do nothing if we didn't own the lock, so safe to use in
101 ;; unwind-protect cleanups when lock acquisition failed for some reason
102 (defun release-spinlock (lock offset our-value)
103 (declare (optimize (speed 3) (safety 0)))
104 (sb!vm::%instance-set-conditional lock offset our-value 0))
106 (defmacro with-spinlock ((queue) &body body)
107 (with-unique-names (pid)
108 `(let ((,pid (current-thread-id)))
111 (get-spinlock ,queue 2 ,pid)
113 (release-spinlock ,queue 2 ,pid)))))
116 ;;;; the higher-level locking operations are based on waitqueues
118 (declaim (inline waitqueue-data-address mutex-value-address))
121 (name nil :type (or null simple-base-string))
125 ;;; The bare 4 here and 5 below are offsets of the slots in the struct.
126 ;;; There ought to be some better way to get these numbers
127 (defun waitqueue-data-address (lock)
128 (declare (optimize (speed 3)))
131 (+ (sb!kernel:get-lisp-obj-address lock)
132 (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
134 (defstruct (mutex (:include waitqueue))
137 (defun mutex-value-address (lock)
138 (declare (optimize (speed 3)))
141 (+ (sb!kernel:get-lisp-obj-address lock)
142 (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
144 (sb!alien:define-alien-routine "block_sigcont" void)
145 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep" void)
148 (declaim (inline futex-wait futex-wake))
150 (sb!alien:define-alien-routine
151 "futex_wait" int (word unsigned-long) (old-value unsigned-long))
153 (sb!alien:define-alien-routine
154 "futex_wake" int (word unsigned-long) (n unsigned-long))
156 ;;; this should only be called while holding the queue spinlock.
157 ;;; it releases the spinlock before sleeping
158 (defun wait-on-queue (queue &optional lock)
159 (let ((pid (current-thread-id)))
161 (when lock (release-mutex lock))
162 (sb!sys:without-interrupts
163 (pushnew pid (waitqueue-data queue)))
164 (setf (waitqueue-lock queue) 0)
165 (unblock-sigcont-and-sleep)))
167 ;;; this should only be called while holding the queue spinlock. It doesn't
169 (defun dequeue (queue)
170 (let ((pid (current-thread-id)))
171 (sb!sys:without-interrupts
172 (setf (waitqueue-data queue)
173 (delete pid (waitqueue-data queue))))))
175 ;;; this should only be called while holding the queue spinlock.
176 (defun signal-queue-head (queue)
177 (let ((p (car (waitqueue-data queue))))
178 (when p (signal-thread-to-dequeue p))))
182 ;;; i suspect there may be a race still in this: the futex version requires
183 ;;; the old mutex value before sleeping, so how do we get away without it
184 (defun get-mutex (lock &optional new-value (wait-p t))
185 (declare (type mutex lock) (optimize (speed 3)))
186 (let ((pid (current-thread-id)))
187 (unless new-value (setf new-value pid))
188 (assert (not (eql new-value (mutex-value lock))))
189 (get-spinlock lock 2 pid)
192 ;; args are object slot-num old-value new-value
193 (sb!vm::%instance-set-conditional lock 4 nil new-value)
195 (setf (waitqueue-lock lock) 0)
198 (setf (waitqueue-lock lock) 0)
200 (wait-on-queue lock nil))))
203 (defun get-mutex/futex (lock &optional new-value (wait-p t))
204 (declare (type mutex lock) (optimize (speed 3)))
205 (let ((pid (current-thread-id))
207 (unless new-value (setf new-value pid))
208 (assert (not (eql new-value (mutex-value lock))))
211 (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
213 (unless wait-p (return nil))
214 (futex-wait (mutex-value-address lock)
215 (sb!kernel:get-lisp-obj-address old)))))
217 (defun release-mutex (lock &optional (new-value nil))
218 (declare (type mutex lock))
219 ;; we assume the lock is ours to release
220 (with-spinlock (lock)
221 (setf (mutex-value lock) new-value)
222 (signal-queue-head lock)))
225 (defun release-mutex/futex (lock)
226 (declare (type mutex lock))
227 (setf (mutex-value lock) nil)
228 (futex-wake (mutex-value-address lock) 1))
231 (defmacro with-mutex ((mutex &key value (wait-p t)) &body body)
232 (with-unique-names (got)
233 `(let ((,got (get-mutex ,mutex ,value ,wait-p)))
237 (release-mutex ,mutex))))))
240 ;;;; condition variables
242 (defun condition-wait (queue lock)
243 "Atomically release LOCK and enqueue ourselves on QUEUE. Another
244 thread may subsequently notify us using CONDITION-NOTIFY, at which
245 time we reacquire LOCK and return to the caller."
247 (let ((value (mutex-value lock)))
250 (get-spinlock queue 2 (current-thread-id))
251 (wait-on-queue queue lock))
252 ;; If we are interrupted while waiting, we should do these things
253 ;; before returning. Ideally, in the case of an unhandled signal,
254 ;; we should do them before entering the debugger, but this is
255 ;; better than nothing.
256 (with-spinlock (queue)
258 (get-mutex lock value))))
261 (defun condition-wait/futex (queue lock)
263 (let ((value (mutex-value lock)))
265 (let ((me (current-thread-id)))
266 ;; XXX we should do something to ensure that the result of this setf
267 ;; is visible to all CPUs
268 (setf (waitqueue-data queue) me)
270 ;; Now we go to sleep using futex-wait. If anyone else
271 ;; manages to grab LOCK and call CONDITION-NOTIFY during
272 ;; this comment, it will change queue->data, and so
273 ;; futex-wait returns immediately instead of sleeping.
274 ;; Ergo, no lost wakeup
275 (futex-wait (waitqueue-data-address queue)
276 (sb!kernel:get-lisp-obj-address me)))
277 ;; If we are interrupted while waiting, we should do these things
278 ;; before returning. Ideally, in the case of an unhandled signal,
279 ;; we should do them before entering the debugger, but this is
280 ;; better than nothing.
281 (get-mutex lock value))))
284 (defun condition-notify (queue)
285 "Notify one of the processes waiting on QUEUE"
286 (with-spinlock (queue) (signal-queue-head queue)))
289 (defun condition-notify/futex (queue)
290 "Notify one of the processes waiting on QUEUE."
291 (let ((me (current-thread-id)))
292 ;; no problem if >1 thread notifies during the comment in
293 ;; condition-wait: as long as the value in queue-data isn't the
294 ;; waiting thread's id, it matters not what it is
295 ;; XXX we should do something to ensure that the result of this setf
296 ;; is visible to all CPUs
297 (setf (waitqueue-data queue) me)
298 (futex-wake (waitqueue-data-address queue) 1)))
301 (defun condition-broadcast/futex (queue)
302 (let ((me (current-thread-id)))
303 (setf (waitqueue-data queue) me)
304 (futex-wake (waitqueue-data-address queue) (ash 1 30))))
306 (defun condition-broadcast (queue)
307 "Notify all of the processes waiting on QUEUE."
308 (with-spinlock (queue)
309 (map nil #'signal-thread-to-dequeue (waitqueue-data queue))))
311 ;;; Futexes may be available at compile time but not runtime, so we
312 ;;; default to not using them unless os_init says they're available
313 (defun maybe-install-futex-functions ()
315 (unless (zerop (extern-alien "linux_supports_futex" int))
316 (setf (fdefinition 'get-mutex) #'get-mutex/futex
317 (fdefinition 'release-mutex) #'release-mutex/futex
318 (fdefinition 'condition-wait) #'condition-wait/futex
319 (fdefinition 'condition-broadcast) #'condition-broadcast/futex
320 (fdefinition 'condition-notify) #'condition-notify/futex)
323 ;;;; multiple independent listeners
325 (defvar *session-lock* nil)
327 (defun make-listener-thread (tty-name)
328 (assert (probe-file tty-name))
329 ;; FIXME probably still need to do some tty stuff to get signals
330 ;; delivered correctly.
332 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
333 (out (sb!unix:unix-dup in))
334 (err (sb!unix:unix-dup in)))
335 (labels ((thread-repl ()
336 (sb!unix::unix-setsid)
337 (let* ((*session-lock*
338 (make-mutex :name (format nil "lock for ~A" tty-name)))
340 (sb!sys:make-fd-stream in :input t :buffering :line))
342 (sb!sys:make-fd-stream out :output t :buffering :line))
344 (sb!sys:make-fd-stream err :output t :buffering :line))
346 (sb!sys:make-fd-stream err :input t :output t :buffering :line))
347 (sb!impl::*descriptor-handlers* nil))
348 (get-mutex *session-lock*)
349 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
351 (sb!impl::toplevel-repl nil)
352 (sb!int:flush-standard-output-streams)))))
353 (make-thread #'thread-repl))))
358 (defvar *interactive-threads-lock*
359 (make-mutex :name "*interactive-threads* lock"))
360 (defvar *interactive-threads* nil)
361 (defvar *interactive-threads-queue*
362 (make-waitqueue :name "All threads that need the terminal. First ID on this list is running, the others are waiting"))
364 (defun init-job-control ()
365 (with-mutex (*interactive-threads-lock*)
366 (setf *interactive-threads* (list (current-thread-id)))
367 (return-from init-job-control t)))
369 ;;; called from top of invoke-debugger
370 (defun debugger-wait-until-foreground-thread (stream)
371 "Returns T if thread had been running in background, NIL if it was
374 (with-mutex (*interactive-threads-lock*)
375 (not (member (current-thread-id) *interactive-threads*)))
378 (defun thread-repl-prompt-fun (out-stream)
380 (let ((stopped-threads (cdr *interactive-threads*)))
381 (when stopped-threads
382 (format out-stream "~{~&Thread ~A suspended~}~%" stopped-threads))
383 (sb!impl::repl-prompt-fun out-stream)))
385 (defun get-foreground ()
387 (with-mutex (*interactive-threads-lock*)
388 (let ((tid (current-thread-id)))
389 (when (eql (car *interactive-threads*) tid)
390 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
391 (return-from get-foreground t))
392 (unless (member tid *interactive-threads*)
393 (setf (cdr (last *interactive-threads*)) (list tid)))
395 *interactive-threads-queue* *interactive-threads-lock* )))))
397 (defun release-foreground (&optional next)
398 "Background this thread. If NEXT is supplied, arrange for it to have the foreground next"
399 (with-mutex (*interactive-threads-lock*)
400 (let ((tid (current-thread-id)))
401 (setf *interactive-threads* (delete tid *interactive-threads*))
402 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
403 (when next (setf *interactive-threads*
404 (list* next (delete next *interactive-threads*))))
405 (condition-broadcast *interactive-threads-queue*))))