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