307af5322005e6015e468c35f008df73b888a3a0
[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 reap-dead-threads void)
23
24 (defvar *session* nil)
25
26 ;;;; queues, locks 
27
28 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
29 (declaim (inline get-spinlock release-spinlock))
30
31 (defun get-spinlock (lock offset new-value)
32   (declare (optimize (speed 3) (safety 0)))
33   ;; %instance-set-conditional can test for 0 (which is a fixnum) and
34   ;; store any value
35   (loop until
36        (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
37
38 (defun release-spinlock (lock offset)
39   (declare (optimize (speed 3) (safety 0)))
40   ;; %instance-set-conditional cannot compare arbitrary objects
41   ;; meaningfully, so 
42   ;; (sb!vm::%instance-set-conditional lock offset our-value 0)
43   ;; does not work for bignum thread ids.
44   (sb!vm::%instance-set lock offset 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)))))
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                 (catch 'sb!impl::%end-of-the-world 
177                   (with-simple-restart 
178                       (terminate-thread
179                        (format nil "~~@<Terminate this thread (~A)~~@:>"
180                                (current-thread-id)))
181                     ;; now that most things have a chance to work
182                     ;; properly without messing up other threads, it's
183                     ;; time to enable signals
184                     (sb!unix::reset-signal-mask)
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 (defun destroy-thread (thread-id)
194   "Deprecated. Soon to be removed or reimplemented using pthread_cancel."
195   (terminate-thread thread-id))
196
197 ;;; a moderate degree of care is expected for use of interrupt-thread,
198 ;;; due to its nature: if you interrupt a thread that was holding
199 ;;; important locks then do something that turns out to need those
200 ;;; locks, you probably won't like the effect.  Used with thought
201 ;;; though, it's a good deal gentler than the last-resort functions above
202
203 (define-condition interrupt-thread-error (error)
204   ((thread :reader interrupt-thread-error-thread :initarg :thread)
205    (errno :reader interrupt-thread-error-errno :initarg :errno))
206   (:report (lambda (c s)
207              (format s "interrupt thread ~A failed (~A: ~A)"
208                      (interrupt-thread-error-thread c)
209                      (interrupt-thread-error-errno c)
210                      (strerror (interrupt-thread-error-errno c))))))
211
212 (defun interrupt-thread (thread function)
213   "Interrupt THREAD and make it run FUNCTION."
214   (let ((function (coerce function 'function)))
215     (multiple-value-bind (res err)
216         (sb!unix::syscall ("interrupt_thread"
217                            sb!alien:unsigned-long  sb!alien:unsigned-long)
218                           thread
219                           thread 
220                           (sb!kernel:get-lisp-obj-address function))
221       (unless res
222         (error 'interrupt-thread-error :thread thread :errno err)))))
223
224
225 (defun terminate-thread (thread-id)
226   "Terminate the thread identified by THREAD-ID, by causing it to run
227 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
228   (interrupt-thread thread-id 'sb!ext:quit))
229
230 (declaim (inline current-thread-id))
231 (defun current-thread-id ()
232   (sb!sys:sap-int
233    (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
234
235 ;;;; iterate over the in-memory threads
236
237 (defun mapcar-threads (function)
238   "Call FUNCTION once for each known thread, giving it the thread structure as argument"
239   (let ((function (coerce function 'function)))
240     (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
241           then  (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
242                                               sb!vm::thread-next-slot))
243           until (sb!sys:sap= thread (sb!sys:int-sap 0))
244           collect (funcall function thread))))
245
246 (defun thread-sap-from-id (id)
247   (let ((thread (alien-sap (extern-alien "all_threads" (* t)))))
248     (loop 
249      (when (sb!sys:sap= thread (sb!sys:int-sap 0)) (return nil))
250      ;; FIXME: 32/64 bit
251      (let ((pid (sb!sys:sap-ref-32 thread (* sb!vm:n-word-bytes
252                                              sb!vm::thread-os-thread-slot))))
253        (when (= pid id) (return thread))
254        (setf thread (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
255                                                   sb!vm::thread-next-slot)))))))
256
257 ;;; internal use only.  If you think you need to use this, either you
258 ;;; are an SBCL developer, are doing something that you should discuss
259 ;;; with an SBCL developer first, or are doing something that you
260 ;;; should probably discuss with a professional psychiatrist first
261 (defun symbol-value-in-thread (symbol thread-id)
262   (let ((thread (thread-sap-from-id thread-id)))
263     (when thread
264       (let* ((index (sb!vm::symbol-tls-index symbol))
265              (tl-val (sb!sys:sap-ref-word thread
266                                           (* sb!vm:n-word-bytes index))))
267         (if (eql tl-val sb!vm::unbound-marker-widetag)
268             (sb!vm::symbol-global-value symbol)
269             (sb!kernel:make-lisp-obj tl-val))))))
270
271 ;;;; job control, independent listeners
272
273 (defstruct session 
274   (lock (make-mutex :name "session lock"))
275   (threads nil)
276   (interactive-threads nil)
277   (interactive-threads-queue (make-waitqueue)))
278
279 (defun new-session ()
280   (let ((tid (current-thread-id)))
281     (make-session :threads (list tid)
282                   :interactive-threads (list tid))))
283
284 (defun init-job-control ()
285   (setf *session* (new-session)))
286
287 (defun %delete-thread-from-session (tid session)
288   (with-mutex ((session-lock session))
289     (setf (session-threads session)
290           (delete tid (session-threads session))
291           (session-interactive-threads session)
292           (delete tid (session-interactive-threads session)))))
293
294 (defun call-with-new-session (fn)
295   (%delete-thread-from-session (current-thread-id) *session*)
296   (let ((*session* (new-session)))  (funcall fn)))
297
298 (defmacro with-new-session (args &body forms)
299   (declare (ignore args))               ;for extensibility
300   (sb!int:with-unique-names (fb-name)
301     `(labels ((,fb-name () ,@forms))
302       (call-with-new-session (function ,fb-name)))))
303
304 ;;; Remove thread id TID from its session, if it has one.  This is
305 ;;; called from C mark_thread_dead().
306 (defun handle-thread-exit (tid)
307   (when *session*
308     (%delete-thread-from-session tid *session*)))
309
310 (defun terminate-session ()
311   "Kill all threads in session except for this one.  Does nothing if current
312 thread is not the foreground thread"
313   (reap-dead-threads)
314   ;; FIXME: threads created in other threads may escape termination
315   (let* ((tid (current-thread-id))
316          (to-kill
317           (with-mutex ((session-lock *session*))
318             (and (eql tid (car (session-interactive-threads *session*)))
319                  (session-threads *session*)))))
320     ;; do the kill after dropping the mutex; unwind forms in dying
321     ;; threads may want to do session things
322     (dolist (p to-kill)
323       (unless (eql p tid)
324         ;; terminate the thread but don't be surprised if it has
325         ;; exited in the meantime
326         (handler-case (terminate-thread p)
327           (interrupt-thread-error ()))))))
328
329 ;;; called from top of invoke-debugger
330 (defun debugger-wait-until-foreground-thread (stream)
331   "Returns T if thread had been running in background, NIL if it was
332 interactive."
333   (declare (ignore stream))
334   (prog1
335       (with-mutex ((session-lock *session*))
336         (not (member (current-thread-id) 
337                      (session-interactive-threads *session*))))
338     (get-foreground)))
339
340
341 (defun get-foreground ()
342   (let ((was-foreground t))
343     (loop
344      (with-mutex ((session-lock *session*))
345        (let ((tid (current-thread-id))
346              (int-t (session-interactive-threads *session*)))
347          (when (eql (car int-t) tid)
348            (unless was-foreground
349              (format *query-io* "Resuming thread ~A~%" tid))
350            (return-from get-foreground t))
351          (setf was-foreground nil)
352          (unless (member tid int-t)
353            (setf (cdr (last int-t))
354                  (list tid)))
355          (condition-wait
356           (session-interactive-threads-queue *session*)
357           (session-lock *session*)))))))
358
359 (defun release-foreground (&optional next)
360   "Background this thread.  If NEXT is supplied, arrange for it to have the foreground next"
361   (with-mutex ((session-lock *session*))
362     (let ((tid (current-thread-id)))
363       (setf (session-interactive-threads *session*)
364             (delete tid (session-interactive-threads *session*)))
365       (when next 
366         (setf (session-interactive-threads *session*)
367               (list* next 
368                      (delete next (session-interactive-threads *session*)))))
369       (condition-broadcast (session-interactive-threads-queue *session*)))))
370
371 (defun foreground-thread ()
372   (car (session-interactive-threads *session*)))
373
374 (defun make-listener-thread (tty-name)  
375   (assert (probe-file tty-name))
376   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
377          (out (sb!unix:unix-dup in))
378          (err (sb!unix:unix-dup in)))
379     (labels ((thread-repl () 
380                (sb!unix::unix-setsid)
381                (let* ((sb!impl::*stdin* 
382                        (sb!sys:make-fd-stream in :input t :buffering :line :dual-channel-p t))
383                       (sb!impl::*stdout* 
384                        (sb!sys:make-fd-stream out :output t :buffering :line :dual-channel-p t))
385                       (sb!impl::*stderr* 
386                        (sb!sys:make-fd-stream err :output t :buffering :line :dual-channel-p t))
387                       (sb!impl::*tty* 
388                        (sb!sys:make-fd-stream err :input t :output t :buffering :line :dual-channel-p t))
389                       (sb!impl::*descriptor-handlers* nil))
390                  (with-new-session ()
391                    (unwind-protect
392                         (sb!impl::toplevel-repl nil)
393                      (sb!int:flush-standard-output-streams))))))
394       (make-thread #'thread-repl))))