0.8.9.36:
[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-id sb!alien:unsigned-long))
14
15 (defvar *session* nil)
16
17 ;;;; queues, locks 
18
19 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
20 (declaim (inline get-spinlock release-spinlock))
21
22 (defun get-spinlock (lock offset new-value)
23   (declare (optimize (speed 3) (safety 0)))
24   (loop until
25         (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
26
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))
32
33 (defmacro with-spinlock ((queue) &body body)
34   (with-unique-names (pid)
35     `(let ((,pid (current-thread-id)))
36        (unwind-protect
37             (progn
38               (get-spinlock ,queue 2 ,pid)
39               ,@body)
40          (release-spinlock ,queue 2 ,pid)))))
41
42
43 ;;;; the higher-level locking operations are based on waitqueues
44
45 (declaim (inline waitqueue-data-address mutex-value-address))
46
47 (defstruct waitqueue
48   (name nil :type (or null simple-base-string))
49   (lock 0)
50   (data nil))
51
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)))
56   (sb!ext:truly-the
57    (unsigned-byte 32)
58    (+ (sb!kernel:get-lisp-obj-address lock)
59       (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
60
61 (defstruct (mutex (:include waitqueue))
62   (value nil))
63
64 (defun mutex-value-address (lock)
65   (declare (optimize (speed 3)))
66   (sb!ext:truly-the
67    (unsigned-byte 32)
68    (+ (sb!kernel:get-lisp-obj-address lock)
69       (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
70
71 (sb!alien:define-alien-routine "block_sigcont"  void)
72 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep"  void)
73
74 #!+sb-futex
75 (declaim (inline futex-wait futex-wake))
76 #!+sb-futex
77 (sb!alien:define-alien-routine
78     "futex_wait" int (word unsigned-long) (old-value unsigned-long))
79 #!+sb-futex
80 (sb!alien:define-alien-routine
81     "futex_wake" int (word unsigned-long) (n unsigned-long))
82
83
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)))
88     (block-sigcont)
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)))
94
95 ;;; this should only be called while holding the queue spinlock.  It doesn't
96 ;;; release it
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))))))
102
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))))
107
108 ;;;; mutex
109
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)
118     (loop
119      (unless
120          ;; args are object slot-num old-value new-value
121          (sb!vm::%instance-set-conditional lock 4 nil new-value)
122        (dequeue lock)
123        (setf (waitqueue-lock lock) 0)
124        (return t))
125      (unless wait-p
126        (setf (waitqueue-lock lock) 0)
127        (return nil))
128      (wait-on-queue lock nil))))
129
130 #!+sb-futex
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))
134         old)
135     (unless new-value (setf new-value pid))
136     (assert (not (eql new-value (mutex-value lock))))
137     (loop
138      (unless
139          (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
140        (return t))
141      (unless wait-p (return nil))
142      (futex-wait (mutex-value-address lock)
143                  (sb!kernel:get-lisp-obj-address old)))))
144
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)))
151
152 #!+sb-futex
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))
157
158
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)))
162       (when ,got
163         (unwind-protect
164              (progn ,@body)
165           (release-mutex ,mutex))))))
166
167
168 ;;;; condition variables
169
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."
174   (assert lock)
175   (let ((value (mutex-value lock)))
176     (unwind-protect
177          (progn
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)
185         (dequeue queue))
186       (get-mutex lock value))))
187
188 #!+sb-futex
189 (defun condition-wait/futex (queue lock)
190   (assert lock)
191   (let ((value (mutex-value lock)))
192     (unwind-protect
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)
197            (release-mutex lock)
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))))
210
211
212 (defun condition-notify (queue)
213   "Notify one of the processes waiting on QUEUE"
214   (with-spinlock (queue) (signal-queue-head queue)))
215
216 #!+sb-futex
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)))
227
228 #!+sb-futex
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))))
233
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))))
238
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 ()
242   #!+sb-futex
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)
249     t))
250
251 (defun make-thread (function)
252   (let* ((real-function (coerce function 'function))
253          (tid
254           (%create-thread
255            (sb!kernel:get-lisp-obj-address
256             (lambda ()
257               ;; in time we'll move some of the binding presently done in C
258               ;; here too
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)
266                 (sb!unix:unix-exit
267                  (catch 'sb!impl::%end-of-the-world 
268                    (with-simple-restart 
269                        (destroy-thread
270                         (format nil "~~@<Destroy this thread (~A)~~@:>"
271                                 (current-thread-id)))
272                      (funcall real-function))
273                    0))))))))
274     (with-mutex ((session-lock *session*))
275       (pushnew tid (session-threads *session*)))
276     tid))
277
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
289   ;; deliver the TERM
290   (sb!unix:unix-kill thread-id sb!unix:sigcont))
291
292      
293      
294
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
300
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)
305                      thread
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))
312
313 (declaim (inline current-thread-id))
314 (defun current-thread-id ()
315   (logand 
316    (sb!sys:sap-int
317     (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot))
318    ;; KLUDGE pids are 16 bit really.  Avoid boxing the return value
319    (1- (ash 1 16))))
320
321 ;;;; iterate over the in-memory threads
322
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))))
330
331 ;;;; job control, independent listeners
332
333 (defstruct session 
334   (lock (make-mutex))
335   (threads nil)
336   (interactive-threads nil)
337   (interactive-threads-queue (make-waitqueue)))
338
339 (defun new-session ()
340   (let ((tid (current-thread-id)))
341     (make-session :threads (list tid)
342                   :interactive-threads (list tid))))
343
344 (defun init-job-control ()
345   (setf *session* (new-session)))
346
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*)))))
353
354 (defun call-with-new-session (fn)
355   (%delete-thread-from-session (current-thread-id))
356   (let ((*session* (new-session)))  (funcall fn)))
357
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)))))
363
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))
368   
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))
373          (to-kill
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
379     (dolist (p to-kill)
380       (unless (eql p tid) (terminate-thread p)))))
381
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
385 interactive."
386   (prog1
387       (with-mutex ((session-lock *session*))
388         (not (member (current-thread-id) 
389                      (session-interactive-threads *session*))))
390     (get-foreground)))
391
392
393 (defun get-foreground ()
394   (let ((was-foreground t))
395     (loop
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))
407                  (list tid)))
408          (condition-wait
409           (session-interactive-threads-queue *session*)
410           (session-lock *session*)))))))
411
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)
419       (when next 
420         (setf (session-interactive-threads *session*)
421               (list* next 
422                      (delete next (session-interactive-threads *session*)))))
423       (condition-broadcast (session-interactive-threads-queue *session*)))))
424
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))
434                       (sb!impl::*stdout* 
435                        (sb!sys:make-fd-stream out :output t :buffering :line))
436                       (sb!impl::*stderr* 
437                        (sb!sys:make-fd-stream err :output t :buffering :line))
438                       (sb!impl::*tty* 
439                        (sb!sys:make-fd-stream err :input t :output t :buffering :line))
440                       (sb!impl::*descriptor-handlers* nil))
441                  (with-new-session ()
442                    (sb!sys:enable-interrupt sb!unix:sigint #'sb!unix::sigint-handler)
443                    (unwind-protect
444                         (sb!impl::toplevel-repl nil)
445                      (sb!int:flush-standard-output-streams))))))
446       (make-thread #'thread-repl))))