0.8.6.5
[sbcl.git] / src / code / target-thread.lisp
1 (in-package "SB!THREAD")
2
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
6
7 (sb!alien::define-alien-routine ("create_thread" %create-thread)
8      sb!alien:unsigned-long
9   (lisp-fun-address sb!alien:unsigned-long))
10
11 (sb!alien::define-alien-routine "signal_thread_to_dequeue"
12     sb!alien:unsigned-int
13   (thread-pid sb!alien:unsigned-long))
14
15
16 (defun make-thread (function)
17   (let ((real-function (coerce function 'function)))
18     (%create-thread
19      (sb!kernel:get-lisp-obj-address
20       (lambda ()
21         ;; in time we'll move some of the binding presently done in C
22         ;; here too
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)
30           (sb!unix:unix-exit
31            (catch 'sb!impl::%end-of-the-world 
32              (with-simple-restart 
33                  (destroy-thread
34                   (format nil "~~@<Destroy this thread (~A)~~@:>"
35                           (current-thread-id)))
36                (funcall real-function))
37              0))))))))
38
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
50   ;; deliver the TERM
51   (sb!unix:unix-kill thread-id sb!unix:sigcont))
52
53
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
59
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)
64                      thread
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))
71
72 (declaim (inline current-thread-id))
73 (defun current-thread-id ()
74   (logand 
75    (sb!sys:sap-int
76     (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
77    ;; KLUDGE pids are 16 bit really.  Avoid boxing the return value
78    (1- (ash 1 16))))
79
80 ;;;; iterate over the in-memory threads
81
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))))
89
90 ;;;; queues, locks 
91
92 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
93 (declaim (inline get-spinlock release-spinlock))
94
95 (defun get-spinlock (lock offset new-value)
96   (declare (optimize (speed 3) (safety 0)))
97   (loop until
98         (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
99
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))
105
106 (defmacro with-spinlock ((queue) &body body)
107   (with-unique-names (pid)
108     `(let ((,pid (current-thread-id)))
109        (unwind-protect
110             (progn
111               (get-spinlock ,queue 2 ,pid)
112               ,@body)
113          (release-spinlock ,queue 2 ,pid)))))
114
115
116 ;;;; the higher-level locking operations are based on waitqueues
117
118 (declaim (inline waitqueue-data-address mutex-value-address))
119
120 (defstruct waitqueue
121   (name nil :type (or null simple-base-string))
122   (lock 0)
123   (data nil))
124
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)))
129   (sb!ext:truly-the
130    (unsigned-byte 32)
131    (+ (sb!kernel:get-lisp-obj-address lock)
132       (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
133
134 (defstruct (mutex (:include waitqueue))
135   (value nil))
136
137 (defun mutex-value-address (lock)
138   (declare (optimize (speed 3)))
139   (sb!ext:truly-the
140    (unsigned-byte 32)
141    (+ (sb!kernel:get-lisp-obj-address lock)
142       (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
143
144 (sb!alien:define-alien-routine "block_sigcont"  void)
145 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep"  void)
146
147 #!+sb-futex
148 (declaim (inline futex-wait futex-wake))
149 #!+sb-futex
150 (sb!alien:define-alien-routine
151     "futex_wait" int (word unsigned-long) (old-value unsigned-long))
152 #!+sb-futex
153 (sb!alien:define-alien-routine
154     "futex_wake" int (word unsigned-long) (n unsigned-long))
155
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)))
160     (block-sigcont)
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)))
166
167 ;;; this should only be called while holding the queue spinlock.  It doesn't
168 ;;; release it
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))))))
174
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))))
179
180 ;;;; mutex
181
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)
190     (loop
191      (unless
192          ;; args are object slot-num old-value new-value
193          (sb!vm::%instance-set-conditional lock 4 nil new-value)
194        (dequeue lock)
195        (setf (waitqueue-lock lock) 0)
196        (return t))
197      (unless wait-p
198        (setf (waitqueue-lock lock) 0)
199        (return nil))
200      (wait-on-queue lock nil))))
201
202 #!+sb-futex
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))
206         old)
207     (unless new-value (setf new-value pid))
208     (assert (not (eql new-value (mutex-value lock))))
209     (loop
210      (unless
211          (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
212        (return t))
213      (unless wait-p (return nil))
214      (futex-wait (mutex-value-address lock)
215                  (sb!kernel:get-lisp-obj-address old)))))
216
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)))
223
224 #!+sb-futex
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))
229
230
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)))
234       (when ,got
235         (unwind-protect
236              (progn ,@body)
237           (release-mutex ,mutex))))))
238
239
240 ;;;; condition variables
241
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."
246   (assert lock)
247   (let ((value (mutex-value lock)))
248     (unwind-protect
249          (progn
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)
257         (dequeue queue))
258       (get-mutex lock value))))
259
260 #!+sb-futex
261 (defun condition-wait/futex (queue lock)
262   (assert lock)
263   (let ((value (mutex-value lock)))
264     (unwind-protect
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)
269            (release-mutex lock)
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))))
282
283
284 (defun condition-notify (queue)
285   "Notify one of the processes waiting on QUEUE"
286   (with-spinlock (queue) (signal-queue-head queue)))
287
288 #!+sb-futex
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)))
299
300 #!+sb-futex
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))))
305
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))))
310
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 ()
314   #!+sb-futex
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)
321     t))
322
323 ;;;; multiple independent listeners
324
325 (defvar *session-lock* nil)
326
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.
331   ;; FIXME 
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)))
339                       (sb!impl::*stdin* 
340                        (sb!sys:make-fd-stream in :input t :buffering :line))
341                       (sb!impl::*stdout* 
342                        (sb!sys:make-fd-stream out :output t :buffering :line))
343                       (sb!impl::*stderr* 
344                        (sb!sys:make-fd-stream err :output t :buffering :line))
345                       (sb!impl::*tty* 
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)
350                  (unwind-protect
351                       (sb!impl::toplevel-repl nil)
352                    (sb!int:flush-standard-output-streams)))))
353       (make-thread #'thread-repl))))
354   
355 ;;;; job control
356
357
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"))
363
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)))
368
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
372 interactive."
373   (prog1
374       (with-mutex (*interactive-threads-lock*)
375         (not (member (current-thread-id) *interactive-threads*)))
376     (get-foreground)))
377
378 (defun thread-repl-prompt-fun (out-stream)
379   (get-foreground)
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)))
384
385 (defun get-foreground ()
386   (loop
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)))
394        (condition-wait
395         *interactive-threads-queue* *interactive-threads-lock* )))))
396
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*))))