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