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-id sb!alien:unsigned-long))
15 (defvar *session* nil)
19 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
20 (declaim (inline get-spinlock release-spinlock))
22 (defun get-spinlock (lock offset new-value)
23 (declare (optimize (speed 3) (safety 0)))
25 (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
27 ;; this should do nothing if we didn't own the lock, so safe to use in
28 ;; unwind-protect cleanups when lock acquisition failed for some reason
29 (defun release-spinlock (lock offset our-value)
30 (declare (optimize (speed 3) (safety 0)))
31 (sb!vm::%instance-set-conditional lock offset our-value 0))
33 (defmacro with-spinlock ((queue) &body body)
34 (with-unique-names (pid)
35 `(let ((,pid (current-thread-id)))
38 (get-spinlock ,queue 2 ,pid)
40 (release-spinlock ,queue 2 ,pid)))))
43 ;;;; the higher-level locking operations are based on waitqueues
45 (declaim (inline waitqueue-data-address mutex-value-address))
48 (name nil :type (or null simple-base-string))
52 ;;; The bare 4 here and 5 below are offsets of the slots in the struct.
53 ;;; There ought to be some better way to get these numbers
54 (defun waitqueue-data-address (lock)
55 (declare (optimize (speed 3)))
58 (+ (sb!kernel:get-lisp-obj-address lock)
59 (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
61 (defstruct (mutex (:include waitqueue))
64 (defun mutex-value-address (lock)
65 (declare (optimize (speed 3)))
68 (+ (sb!kernel:get-lisp-obj-address lock)
69 (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
71 (sb!alien:define-alien-routine "block_sigcont" void)
72 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep" void)
75 (declaim (inline futex-wait futex-wake))
77 (sb!alien:define-alien-routine
78 "futex_wait" int (word unsigned-long) (old-value unsigned-long))
80 (sb!alien:define-alien-routine
81 "futex_wake" int (word unsigned-long) (n unsigned-long))
84 ;;; this should only be called while holding the queue spinlock.
85 ;;; it releases the spinlock before sleeping
86 (defun wait-on-queue (queue &optional lock)
87 (let ((pid (current-thread-id)))
89 (when lock (release-mutex lock))
90 (sb!sys:without-interrupts
91 (pushnew pid (waitqueue-data queue)))
92 (setf (waitqueue-lock queue) 0)
93 (unblock-sigcont-and-sleep)))
95 ;;; this should only be called while holding the queue spinlock. It doesn't
97 (defun dequeue (queue)
98 (let ((pid (current-thread-id)))
99 (sb!sys:without-interrupts
100 (setf (waitqueue-data queue)
101 (delete pid (waitqueue-data queue))))))
103 ;;; this should only be called while holding the queue spinlock.
104 (defun signal-queue-head (queue)
105 (let ((p (car (waitqueue-data queue))))
106 (when p (signal-thread-to-dequeue p))))
110 ;;; i suspect there may be a race still in this: the futex version requires
111 ;;; the old mutex value before sleeping, so how do we get away without it
112 (defun get-mutex (lock &optional new-value (wait-p t))
113 (declare (type mutex lock) (optimize (speed 3)))
114 (let ((pid (current-thread-id)))
115 (unless new-value (setf new-value pid))
116 (assert (not (eql new-value (mutex-value lock))))
117 (get-spinlock lock 2 pid)
120 ;; args are object slot-num old-value new-value
121 (sb!vm::%instance-set-conditional lock 4 nil new-value)
123 (setf (waitqueue-lock lock) 0)
126 (setf (waitqueue-lock lock) 0)
128 (wait-on-queue lock nil))))
131 (defun get-mutex/futex (lock &optional new-value (wait-p t))
132 (declare (type mutex lock) (optimize (speed 3)))
133 (let ((pid (current-thread-id))
135 (unless new-value (setf new-value pid))
136 (assert (not (eql new-value (mutex-value lock))))
139 (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
141 (unless wait-p (return nil))
142 (futex-wait (mutex-value-address lock)
143 (sb!kernel:get-lisp-obj-address old)))))
145 (defun release-mutex (lock &optional (new-value nil))
146 (declare (type mutex lock))
147 ;; we assume the lock is ours to release
148 (with-spinlock (lock)
149 (setf (mutex-value lock) new-value)
150 (signal-queue-head lock)))
153 (defun release-mutex/futex (lock)
154 (declare (type mutex lock))
155 (setf (mutex-value lock) nil)
156 (futex-wake (mutex-value-address lock) 1))
159 (defmacro with-mutex ((mutex &key value (wait-p t)) &body body)
160 (with-unique-names (got)
161 `(let ((,got (get-mutex ,mutex ,value ,wait-p)))
165 (release-mutex ,mutex))))))
168 ;;;; condition variables
170 (defun condition-wait (queue lock)
171 "Atomically release LOCK and enqueue ourselves on QUEUE. Another
172 thread may subsequently notify us using CONDITION-NOTIFY, at which
173 time we reacquire LOCK and return to the caller."
175 (let ((value (mutex-value lock)))
178 (get-spinlock queue 2 (current-thread-id))
179 (wait-on-queue queue lock))
180 ;; If we are interrupted while waiting, we should do these things
181 ;; before returning. Ideally, in the case of an unhandled signal,
182 ;; we should do them before entering the debugger, but this is
183 ;; better than nothing.
184 (with-spinlock (queue)
186 (get-mutex lock value))))
189 (defun condition-wait/futex (queue lock)
191 (let ((value (mutex-value lock)))
193 (let ((me (current-thread-id)))
194 ;; XXX we should do something to ensure that the result of this setf
195 ;; is visible to all CPUs
196 (setf (waitqueue-data queue) me)
198 ;; Now we go to sleep using futex-wait. If anyone else
199 ;; manages to grab LOCK and call CONDITION-NOTIFY during
200 ;; this comment, it will change queue->data, and so
201 ;; futex-wait returns immediately instead of sleeping.
202 ;; Ergo, no lost wakeup
203 (futex-wait (waitqueue-data-address queue)
204 (sb!kernel:get-lisp-obj-address me)))
205 ;; If we are interrupted while waiting, we should do these things
206 ;; before returning. Ideally, in the case of an unhandled signal,
207 ;; we should do them before entering the debugger, but this is
208 ;; better than nothing.
209 (get-mutex lock value))))
212 (defun condition-notify (queue)
213 "Notify one of the processes waiting on QUEUE"
214 (with-spinlock (queue) (signal-queue-head queue)))
217 (defun condition-notify/futex (queue)
218 "Notify one of the processes waiting on QUEUE."
219 (let ((me (current-thread-id)))
220 ;; no problem if >1 thread notifies during the comment in
221 ;; condition-wait: as long as the value in queue-data isn't the
222 ;; waiting thread's id, it matters not what it is
223 ;; XXX we should do something to ensure that the result of this setf
224 ;; is visible to all CPUs
225 (setf (waitqueue-data queue) me)
226 (futex-wake (waitqueue-data-address queue) 1)))
229 (defun condition-broadcast/futex (queue)
230 (let ((me (current-thread-id)))
231 (setf (waitqueue-data queue) me)
232 (futex-wake (waitqueue-data-address queue) (ash 1 30))))
234 (defun condition-broadcast (queue)
235 "Notify all of the processes waiting on QUEUE."
236 (with-spinlock (queue)
237 (map nil #'signal-thread-to-dequeue (waitqueue-data queue))))
239 ;;; Futexes may be available at compile time but not runtime, so we
240 ;;; default to not using them unless os_init says they're available
241 (defun maybe-install-futex-functions ()
243 (unless (zerop (extern-alien "linux_supports_futex" int))
244 (setf (fdefinition 'get-mutex) #'get-mutex/futex
245 (fdefinition 'release-mutex) #'release-mutex/futex
246 (fdefinition 'condition-wait) #'condition-wait/futex
247 (fdefinition 'condition-broadcast) #'condition-broadcast/futex
248 (fdefinition 'condition-notify) #'condition-notify/futex)
251 (defun make-thread (function)
252 (let* ((real-function (coerce function 'function))
255 (sb!kernel:get-lisp-obj-address
257 ;; in time we'll move some of the binding presently done in C
259 (let ((sb!kernel::*restart-clusters* nil)
260 (sb!impl::*descriptor-handlers* nil) ; serve-event
261 (sb!impl::*available-buffers* nil)) ;for fd-stream
262 ;; can't use handling-end-of-the-world, because that flushes
263 ;; output streams, and we don't necessarily have any (or we
264 ;; could be sharing them)
265 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
267 (catch 'sb!impl::%end-of-the-world
270 (format nil "~~@<Destroy this thread (~A)~~@:>"
271 (current-thread-id)))
272 (funcall real-function))
274 (with-mutex ((session-lock *session*))
275 (pushnew tid (session-threads *session*)))
278 ;;; Really, you don't want to use these: they'll get into trouble with
279 ;;; garbage collection. Use a lock or a waitqueue instead
280 (defun suspend-thread (thread-id)
281 (sb!unix:unix-kill thread-id sb!unix:sigstop))
282 (defun resume-thread (thread-id)
283 (sb!unix:unix-kill thread-id sb!unix:sigcont))
284 ;;; Note warning about cleanup forms
285 (defun destroy-thread (thread-id)
286 "Destroy the thread identified by THREAD-ID abruptly, without running cleanup forms"
287 (sb!unix:unix-kill thread-id sb!unix:sigterm)
288 ;; may have been stopped for some reason, so now wake it up to
290 (sb!unix:unix-kill thread-id sb!unix:sigcont))
295 ;;; a moderate degree of care is expected for use of interrupt-thread,
296 ;;; due to its nature: if you interrupt a thread that was holding
297 ;;; important locks then do something that turns out to need those
298 ;;; locks, you probably won't like the effect. Used with thought
299 ;;; though, it's a good deal gentler than the last-resort functions above
301 (defun interrupt-thread (thread function)
302 "Interrupt THREAD and make it run FUNCTION. "
303 (sb!unix::syscall* ("interrupt_thread"
304 sb!alien:unsigned-long sb!alien:unsigned-long)
306 thread (sb!kernel:get-lisp-obj-address
307 (coerce function 'function))))
308 (defun terminate-thread (thread-id)
309 "Terminate the thread identified by THREAD-ID, by causing it to run
310 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
311 (interrupt-thread thread-id 'sb!ext:quit))
313 (declaim (inline current-thread-id))
314 (defun current-thread-id ()
317 (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
318 ;; KLUDGE pids are 16 bit really. Avoid boxing the return value
321 ;;;; iterate over the in-memory threads
323 (defun mapcar-threads (function)
324 "Call FUNCTION once for each known thread, giving it the thread structure as argument"
325 (let ((function (coerce function 'function)))
326 (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
327 then (sb!sys:sap-ref-sap thread (* 4 sb!vm::thread-next-slot))
328 until (sb!sys:sap= thread (sb!sys:int-sap 0))
329 collect (funcall function thread))))
331 ;;;; job control, independent listeners
336 (interactive-threads nil)
337 (interactive-threads-queue (make-waitqueue)))
339 (defun new-session ()
340 (let ((tid (current-thread-id)))
341 (make-session :threads (list tid)
342 :interactive-threads (list tid))))
344 (defun init-job-control ()
345 (setf *session* (new-session)))
347 (defun %delete-thread-from-session (tid)
348 (with-mutex ((session-lock *session*))
349 (setf (session-threads *session*)
350 (delete tid (session-threads *session*))
351 (session-interactive-threads *session*)
352 (delete tid (session-interactive-threads *session*)))))
354 (defun call-with-new-session (fn)
355 (%delete-thread-from-session (current-thread-id))
356 (let ((*session* (new-session))) (funcall fn)))
358 (defmacro with-new-session (args &body forms)
359 (declare (ignore args)) ;for extensibility
360 (sb!int:with-unique-names (fb-name)
361 `(labels ((,fb-name () ,@forms))
362 (call-with-new-session (function ,fb-name)))))
364 ;;; this is called from a C signal handler: some signals may be masked
365 (defun handle-thread-exit (tid)
366 "Remove thread id TID from the session, if it's there"
367 (%delete-thread-from-session tid))
369 (defun terminate-session ()
370 "Kill all threads in session exept for this one. Does nothing if current
371 thread is not the foreground thread"
372 (let* ((tid (current-thread-id))
374 (with-mutex ((session-lock *session*))
375 (and (eql tid (car (session-interactive-threads *session*)))
376 (session-threads *session*)))))
377 ;; do the kill after dropping the mutex; unwind forms in dying
378 ;; threads may want to do session things
380 (unless (eql p tid) (terminate-thread p)))))
382 ;;; called from top of invoke-debugger
383 (defun debugger-wait-until-foreground-thread (stream)
384 "Returns T if thread had been running in background, NIL if it was
387 (with-mutex ((session-lock *session*))
388 (not (member (current-thread-id)
389 (session-interactive-threads *session*))))
393 (defun get-foreground ()
394 (let ((was-foreground t))
396 (with-mutex ((session-lock *session*))
397 (let ((tid (current-thread-id))
398 (int-t (session-interactive-threads *session*)))
399 (when (eql (car int-t) tid)
400 (unless was-foreground
401 (format *query-io* "Resuming thread ~A~%" tid))
402 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
403 (return-from get-foreground t))
404 (setf was-foreground nil)
405 (unless (member tid int-t)
406 (setf (cdr (last int-t))
409 (session-interactive-threads-queue *session*)
410 (session-lock *session*)))))))
412 (defun release-foreground (&optional next)
413 "Background this thread. If NEXT is supplied, arrange for it to have the foreground next"
414 (with-mutex ((session-lock *session*))
415 (let ((tid (current-thread-id)))
416 (setf (session-interactive-threads *session*)
417 (delete tid (session-interactive-threads *session*)))
418 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
420 (setf (session-interactive-threads *session*)
422 (delete next (session-interactive-threads *session*)))))
423 (condition-broadcast (session-interactive-threads-queue *session*)))))
425 (defun make-listener-thread (tty-name)
426 (assert (probe-file tty-name))
427 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
428 (out (sb!unix:unix-dup in))
429 (err (sb!unix:unix-dup in)))
430 (labels ((thread-repl ()
431 (sb!unix::unix-setsid)
432 (let* ((sb!impl::*stdin*
433 (sb!sys:make-fd-stream in :input t :buffering :line))
435 (sb!sys:make-fd-stream out :output t :buffering :line))
437 (sb!sys:make-fd-stream err :output t :buffering :line))
439 (sb!sys:make-fd-stream err :input t :output t :buffering :line))
440 (sb!impl::*descriptor-handlers* nil))
442 (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
444 (sb!impl::toplevel-repl nil)
445 (sb!int:flush-standard-output-streams))))))
446 (make-thread #'thread-repl))))