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