0.8.20.30:
[sbcl.git] / src / code / target-thread.lisp
1 ;;;; support for threads in the target machine
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
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.
11
12 (in-package "SB!THREAD")
13
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
17
18 (define-alien-routine ("create_thread" %create-thread)
19     unsigned-long
20   (lisp-fun-address unsigned-long))
21
22 (define-alien-routine "signal_thread_to_dequeue"
23     unsigned-int
24   (thread-id unsigned-long))
25
26 (define-alien-routine reap-dead-threads void)
27
28 (defvar *session* nil)
29
30 ;;;; queues, locks 
31
32 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
33 (declaim (inline get-spinlock release-spinlock))
34
35 (defun get-spinlock (lock offset new-value)
36   (declare (optimize (speed 3) (safety 0)))
37   (loop until
38         (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
39
40 ;; this should do nothing if we didn't own the lock, so safe to use in
41 ;; unwind-protect cleanups when lock acquisition failed for some reason
42 (defun release-spinlock (lock offset our-value)
43   (declare (optimize (speed 3) (safety 0)))
44   (sb!vm::%instance-set-conditional lock offset our-value 0))
45
46 (defmacro with-spinlock ((queue) &body body)
47   (with-unique-names (pid)
48     `(let ((,pid (current-thread-id)))
49        (unwind-protect
50             (progn
51               (get-spinlock ,queue 2 ,pid)
52               ,@body)
53          (release-spinlock ,queue 2 ,pid)))))
54
55
56 ;;;; the higher-level locking operations are based on waitqueues
57
58 (declaim (inline waitqueue-data-address mutex-value-address))
59
60 (defstruct waitqueue
61   (name nil :type (or null simple-string))
62   (lock 0)
63   (data nil))
64
65 ;;; The bare 4 here and 5 below are offsets of the slots in the struct.
66 ;;; There ought to be some better way to get these numbers
67 (defun waitqueue-data-address (lock)
68   (declare (optimize (speed 3)))
69   (sb!ext:truly-the
70    (unsigned-byte 32)
71    (+ (sb!kernel:get-lisp-obj-address lock)
72       (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
73
74 (defstruct (mutex (:include waitqueue))
75   (value nil))
76
77 (defun mutex-value-address (lock)
78   (declare (optimize (speed 3)))
79   (sb!ext:truly-the
80    (unsigned-byte 32)
81    (+ (sb!kernel:get-lisp-obj-address lock)
82       (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
83
84 (sb!alien:define-alien-routine "block_sigcont"  void)
85 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep"  void)
86
87 (declaim (inline futex-wait futex-wake))
88 (sb!alien:define-alien-routine
89     "futex_wait" int (word unsigned-long) (old-value unsigned-long))
90 (sb!alien:define-alien-routine
91     "futex_wake" int (word unsigned-long) (n unsigned-long))
92
93
94 ;;;; mutex
95
96 (defun get-mutex (lock &optional new-value (wait-p t))
97   "Acquire LOCK, setting it to NEW-VALUE or some suitable default value 
98 if NIL.  If WAIT-P is non-NIL and the lock is in use, sleep until it
99 is available"
100   (declare (type mutex lock)  (optimize (speed 3)))
101   (let ((pid (current-thread-id))
102         old)
103     (unless new-value (setf new-value pid))
104     (when (eql new-value (mutex-value lock))
105       (warn "recursive lock attempt ~S~%" lock))
106     (loop
107      (unless
108          (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
109        (return t))
110      (unless wait-p (return nil))
111      (futex-wait (mutex-value-address lock)
112                  (sb!kernel:get-lisp-obj-address old)))))
113
114 (defun release-mutex (lock)
115   (declare (type mutex lock))
116   (setf (mutex-value lock) nil)
117   (futex-wake (mutex-value-address lock) 1))
118
119 ;;;; condition variables
120
121 (defun condition-wait (queue lock)
122   "Atomically release LOCK and enqueue ourselves on QUEUE.  Another
123 thread may subsequently notify us using CONDITION-NOTIFY, at which
124 time we reacquire LOCK and return to the caller."
125   (assert lock)
126   (let ((value (mutex-value lock)))
127     (unwind-protect
128          (let ((me (current-thread-id)))
129            ;; XXX we should do something to ensure that the result of this setf
130            ;; is visible to all CPUs
131            (setf (waitqueue-data queue) me)
132            (release-mutex lock)
133            ;; Now we go to sleep using futex-wait.  If anyone else
134            ;; manages to grab LOCK and call CONDITION-NOTIFY during
135            ;; this comment, it will change queue->data, and so
136            ;; futex-wait returns immediately instead of sleeping.
137            ;; Ergo, no lost wakeup
138            (futex-wait (waitqueue-data-address queue)
139                        (sb!kernel:get-lisp-obj-address me)))
140       ;; If we are interrupted while waiting, we should do these things
141       ;; before returning.  Ideally, in the case of an unhandled signal,
142       ;; we should do them before entering the debugger, but this is
143       ;; better than nothing.
144       (get-mutex lock value))))
145
146
147 (defun condition-notify (queue)
148   "Notify one of the processes waiting on QUEUE"
149   (let ((me (current-thread-id)))
150     ;; no problem if >1 thread notifies during the comment in
151     ;; condition-wait: as long as the value in queue-data isn't the
152     ;; waiting thread's id, it matters not what it is
153     ;; XXX we should do something to ensure that the result of this setf
154     ;; is visible to all CPUs
155     (setf (waitqueue-data queue) me)
156     (futex-wake (waitqueue-data-address queue) 1)))
157
158 (defun condition-broadcast (queue)
159   (let ((me (current-thread-id)))
160     (setf (waitqueue-data queue) me)
161     (futex-wake (waitqueue-data-address queue) (ash 1 30))))
162
163 (defun make-thread (function)
164   (let* ((real-function (coerce function 'function))
165          (tid
166           (%create-thread
167            (sb!kernel:get-lisp-obj-address
168             (lambda ()
169               ;; in time we'll move some of the binding presently done in C
170               ;; here too
171               (let ((sb!kernel::*restart-clusters* nil)
172                     (sb!kernel::*handler-clusters* nil)
173                     (sb!kernel::*condition-restarts* nil)
174                     (sb!impl::*descriptor-handlers* nil) ; serve-event
175                     (sb!impl::*available-buffers* nil)) ;for fd-stream
176                 ;; can't use handling-end-of-the-world, because that flushes
177                 ;; output streams, and we don't necessarily have any (or we
178                 ;; could be sharing them)
179                 (sb!sys:enable-interrupt sb!unix:sigint :ignore)
180                 (catch 'sb!impl::%end-of-the-world 
181                   (with-simple-restart 
182                       (destroy-thread
183                        (format nil "~~@<Destroy this thread (~A)~~@:>"
184                                (current-thread-id)))
185                     (funcall real-function))
186                   0))
187               (values))))))
188     (when (zerop tid) (error "Can't create a new thread"))
189     (with-mutex ((session-lock *session*))
190       (pushnew tid (session-threads *session*)))
191     tid))
192
193 ;;; Really, you don't want to use these: they'll get into trouble with
194 ;;; garbage collection.  Use a lock or a waitqueue instead
195 (defun suspend-thread (thread-id)
196   (sb!unix:unix-kill thread-id sb!unix:sigstop))
197 (defun resume-thread (thread-id)
198   (sb!unix:unix-kill thread-id sb!unix:sigcont))
199 ;;; Note warning about cleanup forms
200 (defun destroy-thread (thread-id)
201   "Destroy the thread identified by THREAD-ID abruptly, without running cleanup forms"
202   (sb!unix:unix-kill thread-id sb!unix:sigterm)
203   ;; may have been stopped for some reason, so now wake it up to
204   ;; deliver the TERM
205   (sb!unix:unix-kill thread-id sb!unix:sigcont))
206
207      
208      
209
210 ;;; a moderate degree of care is expected for use of interrupt-thread,
211 ;;; due to its nature: if you interrupt a thread that was holding
212 ;;; important locks then do something that turns out to need those
213 ;;; locks, you probably won't like the effect.  Used with thought
214 ;;; though, it's a good deal gentler than the last-resort functions above
215
216 (define-condition interrupt-thread-error (error)
217   ((thread :reader interrupt-thread-error-thread :initarg :thread)
218    (errno :reader interrupt-thread-error-errno :initarg :errno))
219   (:report (lambda (c s)
220              (format s "interrupt thread ~A failed (~A: ~A)"
221                      (interrupt-thread-error-thread c)
222                      (interrupt-thread-error-errno c)
223                      (strerror (interrupt-thread-error-errno c))))))
224
225 (defun interrupt-thread (thread function)
226   "Interrupt THREAD and make it run FUNCTION."
227   (let ((function (coerce function 'function)))
228     (sb!sys:with-pinned-objects 
229      (function)
230      (multiple-value-bind (res err)
231          (sb!unix::syscall ("interrupt_thread"
232                             sb!alien:unsigned-long  sb!alien:unsigned-long)
233                            thread
234                            thread 
235                            (sb!kernel:get-lisp-obj-address function))
236        (unless res
237          (error 'interrupt-thread-error :thread thread :errno err))))))
238
239
240 (defun terminate-thread (thread-id)
241   "Terminate the thread identified by THREAD-ID, by causing it to run
242 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
243   (interrupt-thread thread-id 'sb!ext:quit))
244
245 (declaim (inline current-thread-id))
246 (defun current-thread-id ()
247   (logand 
248    (sb!sys:sap-int
249     (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
250    ;; KLUDGE pids are 16 bit really.  Avoid boxing the return value
251    (1- (ash 1 16))))
252
253 ;;;; iterate over the in-memory threads
254
255 (defun mapcar-threads (function)
256   "Call FUNCTION once for each known thread, giving it the thread structure as argument"
257   (let ((function (coerce function 'function)))
258     (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
259           then  (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
260                                               sb!vm::thread-next-slot))
261           until (sb!sys:sap= thread (sb!sys:int-sap 0))
262           collect (funcall function thread))))
263
264 (defun thread-sap-from-id (id)
265   (let ((thread (alien-sap (extern-alien "all_threads" (* t)))))
266     (loop 
267      (when (sb!sys:sap= thread (sb!sys:int-sap 0)) (return nil))
268      (let ((pid (sb!sys:sap-ref-32 thread (* sb!vm:n-word-bytes
269                                              sb!vm::thread-pid-slot))))
270        (when (= pid id) (return thread))
271        (setf thread (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
272                                                   sb!vm::thread-next-slot)))))))
273
274 ;;; internal use only.  If you think you need to use this, either you
275 ;;; are an SBCL developer, are doing something that you should discuss
276 ;;; with an SBCL developer first, or are doing something that you
277 ;;; should probably discuss with a professional psychiatrist first
278 (defun symbol-value-in-thread (symbol thread-id)
279   (let ((thread (thread-sap-from-id thread-id)))
280     (when thread
281       (let* ((index (sb!vm::symbol-tls-index symbol))
282              (tl-val (sb!sys:sap-ref-word thread
283                                           (* sb!vm:n-word-bytes index))))
284         (if (eql tl-val sb!vm::unbound-marker-widetag)
285             (sb!vm::symbol-global-value symbol)
286             (sb!kernel:make-lisp-obj tl-val))))))
287
288 ;;;; job control, independent listeners
289
290 (defstruct session 
291   (lock (make-mutex))
292   (threads nil)
293   (interactive-threads nil)
294   (interactive-threads-queue (make-waitqueue)))
295
296 (defun new-session ()
297   (let ((tid (current-thread-id)))
298     (make-session :threads (list tid)
299                   :interactive-threads (list tid))))
300
301 (defun init-job-control ()
302   (setf *session* (new-session)))
303
304 (defun %delete-thread-from-session (tid session)
305   (with-mutex ((session-lock session))
306     (setf (session-threads session)
307           (delete tid (session-threads session))
308           (session-interactive-threads session)
309           (delete tid (session-interactive-threads session)))))
310
311 (defun call-with-new-session (fn)
312   (%delete-thread-from-session (current-thread-id) *session*)
313   (let ((*session* (new-session)))  (funcall fn)))
314
315 (defmacro with-new-session (args &body forms)
316   (declare (ignore args))               ;for extensibility
317   (sb!int:with-unique-names (fb-name)
318     `(labels ((,fb-name () ,@forms))
319       (call-with-new-session (function ,fb-name)))))
320
321 ;;; Remove thread id TID from its session, if it has one.  This is
322 ;;; called from C reap_dead_threads() so is run in the context of
323 ;;; whichever thread called that (usually after a GC), which may not have 
324 ;;; any meaningful parent/child/sibling relationship with the dead thread
325 (defun handle-thread-exit (tid)
326   (let ((session (symbol-value-in-thread '*session* tid)))
327     (and session (%delete-thread-from-session tid session))))
328   
329 (defun terminate-session ()
330   "Kill all threads in session except for this one.  Does nothing if current
331 thread is not the foreground thread"
332   (reap-dead-threads)
333   (let* ((tid (current-thread-id))
334          (to-kill
335           (with-mutex ((session-lock *session*))
336             (and (eql tid (car (session-interactive-threads *session*)))
337                  (session-threads *session*)))))
338     ;; do the kill after dropping the mutex; unwind forms in dying
339     ;; threads may want to do session things
340     (dolist (p to-kill)
341       (unless (eql p tid) (terminate-thread p)))))
342
343 ;;; called from top of invoke-debugger
344 (defun debugger-wait-until-foreground-thread (stream)
345   "Returns T if thread had been running in background, NIL if it was
346 interactive."
347   (declare (ignore stream))
348   (prog1
349       (with-mutex ((session-lock *session*))
350         (not (member (current-thread-id) 
351                      (session-interactive-threads *session*))))
352     (get-foreground)))
353
354
355 (defun get-foreground ()
356   (let ((was-foreground t))
357     (loop
358      (with-mutex ((session-lock *session*))
359        (let ((tid (current-thread-id))
360              (int-t (session-interactive-threads *session*)))
361          (when (eql (car int-t) tid)
362            (unless was-foreground
363              (format *query-io* "Resuming thread ~A~%" tid))
364            (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
365            (return-from get-foreground t))
366          (setf was-foreground nil)
367          (unless (member tid int-t)
368            (setf (cdr (last int-t))
369                  (list tid)))
370          (condition-wait
371           (session-interactive-threads-queue *session*)
372           (session-lock *session*)))))))
373
374 (defun release-foreground (&optional next)
375   "Background this thread.  If NEXT is supplied, arrange for it to have the foreground next"
376   (with-mutex ((session-lock *session*))
377     (let ((tid (current-thread-id)))
378       (setf (session-interactive-threads *session*)
379             (delete tid (session-interactive-threads *session*)))
380       (sb!sys:enable-interrupt sb!unix:sigint :ignore)
381       (when next 
382         (setf (session-interactive-threads *session*)
383               (list* next 
384                      (delete next (session-interactive-threads *session*)))))
385       (condition-broadcast (session-interactive-threads-queue *session*)))))
386
387 (defun make-listener-thread (tty-name)  
388   (assert (probe-file tty-name))
389   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
390          (out (sb!unix:unix-dup in))
391          (err (sb!unix:unix-dup in)))
392     (labels ((thread-repl () 
393                (sb!unix::unix-setsid)
394                (let* ((sb!impl::*stdin* 
395                        (sb!sys:make-fd-stream in :input t :buffering :line))
396                       (sb!impl::*stdout* 
397                        (sb!sys:make-fd-stream out :output t :buffering :line))
398                       (sb!impl::*stderr* 
399                        (sb!sys:make-fd-stream err :output t :buffering :line))
400                       (sb!impl::*tty* 
401                        (sb!sys:make-fd-stream err :input t :output t :buffering :line))
402                       (sb!impl::*descriptor-handlers* nil))
403                  (with-new-session ()
404                    (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
405                    (unwind-protect
406                         (sb!impl::toplevel-repl nil)
407                      (sb!int:flush-standard-output-streams))))))
408       (make-thread #'thread-repl))))