fix unthreaded builds with sb-futex in target *features*
[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 ;;; CAS Lock
15 ;;;
16 ;;; Locks don't come any simpler -- or more lightweight than this. While
17 ;;; this is probably a premature optimization for most users, we still
18 ;;; need it internally for implementing condition variables outside Futex
19 ;;; builds.
20
21 (defmacro with-cas-lock ((place) &body body)
22   #!+sb-doc
23   "Runs BODY with interrupts disabled and *CURRENT-THREAD* compare-and-swapped
24 into PLACE instead of NIL. PLACE must be a place acceptable to
25 COMPARE-AND-SWAP, and must initially hold NIL.
26
27 WITH-CAS-LOCK is suitable mostly when the critical section needing protection
28 is very small, and cost of allocating a separate lock object would be
29 prohibitive. While it is the most lightweight locking constructed offered by
30 SBCL, it is also the least scalable if the section is heavily contested or
31 long.
32
33 WITH-CAS-LOCK can be entered recursively."
34   `(without-interrupts
35      (%with-cas-lock (,place) ,@body)))
36
37 (defmacro %with-cas-lock ((place) &body body &environment env)
38   (with-unique-names (owner self)
39     (multiple-value-bind (vars vals old new cas-form read-form)
40         (sb!ext:get-cas-expansion place env)
41       `(let* (,@(mapcar #'list vars vals)
42               (,owner (progn
43                         (barrier (:read))
44                         ,read-form))
45               (,self *current-thread*)
46               (,old nil)
47               (,new ,self))
48          (unwind-protect
49               (progn
50                 (unless (eq ,owner ,self)
51                   (loop until (loop repeat 100
52                                     when (and (progn
53                                                 (barrier (:read))
54                                                 (not ,read-form))
55                                               (not (setf ,owner ,cas-form)))
56                                     return t
57                                     else
58                                     do (sb!ext:spin-loop-hint))
59                         do (thread-yield)))
60                 ,@body)
61            (unless (eq ,owner ,self)
62              (let ((,old ,self)
63                    (,new nil))
64                (unless (eq ,old ,cas-form)
65                  (bug "Failed to release CAS lock!")))))))))
66
67 ;;; Conditions
68
69 (define-condition thread-error (error)
70   ((thread :reader thread-error-thread :initarg :thread))
71   #!+sb-doc
72   (:documentation
73    "Conditions of type THREAD-ERROR are signalled when thread operations fail.
74 The offending thread is initialized by the :THREAD initialization argument and
75 read by the function THREAD-ERROR-THREAD."))
76
77 (define-condition thread-deadlock (thread-error)
78   ((cycle :initarg :cycle :reader thread-deadlock-cycle))
79   (:report
80    (lambda (condition stream)
81      (let ((*print-circle* t))
82        (format stream "Deadlock cycle detected:~%~@<   ~@;~
83                      ~{~:@_~S~:@_~}~:@>"
84                (mapcar #'car (thread-deadlock-cycle condition)))))))
85
86 #!+sb-doc
87 (setf
88  (fdocumentation 'thread-error-thread 'function)
89  "Return the offending thread that the THREAD-ERROR pertains to.")
90
91 (define-condition symbol-value-in-thread-error (cell-error thread-error)
92   ((info :reader symbol-value-in-thread-error-info :initarg :info))
93   (:report
94    (lambda (condition stream)
95      (destructuring-bind (op problem)
96          (symbol-value-in-thread-error-info condition)
97        (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
98                op
99                (cell-error-name condition)
100                (thread-error-thread condition)
101                (ecase problem
102                  (:unbound-in-thread "the symbol is unbound in thread.")
103                  (:no-tls-value "the symbol has no thread-local value.")
104                  (:thread-dead "the thread has exited.")
105                  (:invalid-tls-value "the thread-local value is not valid."))))))
106   #!+sb-doc
107   (:documentation
108    "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
109 the symbol not having a thread-local value, or the target thread having
110 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
111 offending thread using THREAD-ERROR-THREAD."))
112
113 (define-condition join-thread-error (thread-error)
114   ((problem :initarg :problem :reader join-thread-problem))
115   (:report (lambda (c s)
116              (ecase (join-thread-problem c)
117                (:abort
118                 (format s "Joining thread failed: thread ~A ~
119                            did not return normally."
120                         (thread-error-thread c)))
121                (:timeout
122                 (format s "Joining thread timed out: thread ~A ~
123                            did not exit in time."
124                         (thread-error-thread c))))))
125   #!+sb-doc
126   (:documentation
127    "Signalled when joining a thread fails due to abnormal exit of the thread
128 to be joined. The offending thread can be accessed using
129 THREAD-ERROR-THREAD."))
130
131 (define-deprecated-function :late "1.0.29.17" join-thread-error-thread thread-error-thread
132     (condition)
133   (thread-error-thread condition))
134
135 (define-condition interrupt-thread-error (thread-error) ()
136   (:report (lambda (c s)
137              (format s "Interrupt thread failed: thread ~A has exited."
138                      (thread-error-thread c))))
139   #!+sb-doc
140   (:documentation
141    "Signalled when interrupting a thread fails because the thread has already
142 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
143
144 (define-deprecated-function :late "1.0.29.17" interrupt-thread-error-thread thread-error-thread
145     (condition)
146   (thread-error-thread condition))
147
148 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
149 ;;; necessary because threads are only supported with the conservative
150 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
151 ;;; are treated as references.
152
153 ;;; set the doc here because in early-thread FDOCUMENTATION is not
154 ;;; available, yet
155 #!+sb-doc
156 (setf (fdocumentation '*current-thread* 'variable)
157       "Bound in each thread to the thread itself.")
158
159 #!+sb-doc
160 (setf
161  (fdocumentation 'thread-name 'function)
162  "Name of the thread. Can be assigned to using SETF. Thread names can be
163 arbitrary printable objects, and need not be unique.")
164
165 (def!method print-object ((thread thread) stream)
166   (print-unreadable-object (thread stream :type t :identity t)
167     (let* ((cookie (list thread))
168            (info (if (thread-alive-p thread)
169                      :running
170                      (multiple-value-list
171                       (join-thread thread :default cookie))))
172            (state (if (eq :running info)
173                       (let* ((thing (progn
174                                       (barrier (:read))
175                                       (thread-waiting-for thread))))
176                         (typecase thing
177                           (cons
178                            (list "waiting on:" (cdr thing)
179                                  "timeout: " (car thing)))
180                           (null
181                            (list info))
182                           (t
183                            (list "waiting on:" thing))))
184                       (if (eq cookie (car info))
185                           (list :aborted)
186                           :finished)))
187            (values (when (eq :finished state)
188                      info))
189            (*print-level* 4))
190       (format stream
191               "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
192               (thread-name thread)
193               (eq :finished state)
194               state
195               values))))
196
197 (defun print-lock (lock name owner stream)
198   (let ((*print-circle* t))
199     (print-unreadable-object (lock stream :type t :identity (not name))
200       (if owner
201           (format stream "~@[~S ~]~2I~_owner: ~S" name owner)
202           (format stream "~@[~S ~](free)" name)))))
203
204 (def!method print-object ((mutex mutex) stream)
205   (print-lock mutex (mutex-name mutex) (mutex-owner mutex) stream))
206
207 (defun thread-alive-p (thread)
208   #!+sb-doc
209   "Return T if THREAD is still alive. Note that the return value is
210 potentially stale even before the function returns, as the thread may exit at
211 any time."
212   (thread-%alive-p thread))
213
214 ;; A thread is eligible for gc iff it has finished and there are no
215 ;; more references to it. This list is supposed to keep a reference to
216 ;; all running threads.
217 (defvar *all-threads* ())
218 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
219
220 (defvar *default-alloc-signal* nil)
221
222 (defmacro with-all-threads-lock (&body body)
223   `(with-system-mutex (*all-threads-lock*)
224      ,@body))
225
226 (defun list-all-threads ()
227   #!+sb-doc
228   "Return a list of the live threads. Note that the return value is
229 potentially stale even before the function returns, as new threads may be
230 created and old ones may exit at any time."
231   (with-all-threads-lock
232     (copy-list *all-threads*)))
233
234 (declaim (inline current-thread-sap))
235 (defun current-thread-sap ()
236   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
237
238 (declaim (inline current-thread-os-thread))
239 (defun current-thread-os-thread ()
240   #!+sb-thread
241   (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
242   #!-sb-thread
243   0)
244
245 (defun init-initial-thread ()
246   (/show0 "Entering INIT-INITIAL-THREAD")
247   (let ((initial-thread (%make-thread :name "initial thread"
248                                       :%alive-p t
249                                       :os-thread (current-thread-os-thread))))
250     (setq *current-thread* initial-thread)
251     ;; Either *all-threads* is empty or it contains exactly one thread
252     ;; in case we are in reinit since saving core with multiple
253     ;; threads doesn't work.
254     (setq *all-threads* (list initial-thread))))
255 \f
256
257 ;;;; Aliens, low level stuff
258
259 (define-alien-routine "kill_safely"
260     integer
261   (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
262   (signal int))
263
264 #!+sb-thread
265 (progn
266   ;; FIXME it would be good to define what a thread id is or isn't
267   ;; (our current assumption is that it's a fixnum).  It so happens
268   ;; that on Linux it's a pid, but it might not be on posix thread
269   ;; implementations.
270   (define-alien-routine ("create_thread" %create-thread)
271       unsigned-long (lisp-fun-address unsigned-long))
272
273   (declaim (inline %block-deferrable-signals))
274   (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
275       void
276     (where sb!alien:unsigned-long)
277     (old sb!alien:unsigned-long))
278
279   (defun block-deferrable-signals ()
280     (%block-deferrable-signals 0 0))
281
282   #!+sb-futex
283   (progn
284     (declaim (inline futex-wait %futex-wait futex-wake))
285
286     (define-alien-routine ("futex_wait" %futex-wait)
287         int (word unsigned-long) (old-value unsigned-long)
288         (to-sec long) (to-usec unsigned-long))
289
290     (defun futex-wait (word old to-sec to-usec)
291       (with-interrupts
292         (%futex-wait word old to-sec to-usec)))
293
294     (define-alien-routine "futex_wake"
295         int (word unsigned-long) (n unsigned-long))))
296
297 ;;; used by debug-int.lisp to access interrupt contexts
298 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
299 #!-sb-thread
300 (defun sb!vm::current-thread-offset-sap (n)
301   (declare (type (unsigned-byte 27) n))
302   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
303                (* n sb!vm:n-word-bytes)))
304
305 #!+sb-thread
306 (defun sb!vm::current-thread-offset-sap (n)
307   (declare (type (unsigned-byte 27) n))
308   (sb!vm::current-thread-offset-sap n))
309 \f
310
311 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
312   (with-unique-names (n-thread n-lock new n-timeout)
313     `(let* ((,n-thread ,thread)
314             (,n-lock ,lock)
315             (,n-timeout ,(when timeoutp
316                            `(or ,timeout
317                                 (when sb!impl::*deadline*
318                                   sb!impl::*deadline-seconds*))))
319             (,new (if ,n-timeout
320                       ;; Using CONS tells the rest of the system there's a
321                       ;; timeout in place, so it isn't considered a deadlock.
322                       (cons ,n-timeout ,n-lock)
323                       ,n-lock)))
324        (declare (dynamic-extent ,new))
325        ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
326        ;; in places where interrupts should already be disabled.
327        (unwind-protect
328             (progn
329               (setf (thread-waiting-for ,n-thread) ,new)
330               (barrier (:write))
331               ,@forms)
332          ;; Interrupt handlers and GC save and restore any
333          ;; previous wait marks using WITHOUT-DEADLOCKS below.
334          (setf (thread-waiting-for ,n-thread) nil)
335          (barrier (:write))))))
336 \f
337 ;;;; Mutexes
338
339 #!+sb-doc
340 (setf (fdocumentation 'make-mutex 'function)
341       "Create a mutex."
342       (fdocumentation 'mutex-name 'function)
343       "The name of the mutex. Setfable.")
344
345 #!+(and sb-thread sb-futex)
346 (progn
347   (define-structure-slot-addressor mutex-state-address
348       :structure mutex
349       :slot state)
350   ;; Important: current code assumes these are fixnums or other
351   ;; lisp objects that don't need pinning.
352   (defconstant +lock-free+ 0)
353   (defconstant +lock-taken+ 1)
354   (defconstant +lock-contested+ 2))
355
356 (defun mutex-owner (mutex)
357   "Current owner of the mutex, NIL if the mutex is free. Naturally,
358 this is racy by design (another thread may acquire the mutex after
359 this function returns), it is intended for informative purposes. For
360 testing whether the current thread is holding a mutex see
361 HOLDING-MUTEX-P."
362   ;; Make sure to get the current value.
363   (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
364
365 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
366 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
367 (defun check-deadlock ()
368   (let* ((self *current-thread*)
369          (origin (progn
370                    (barrier (:read))
371                    (thread-waiting-for self))))
372     (labels ((detect-deadlock (lock)
373                (let ((other-thread (mutex-%owner lock)))
374                  (cond ((not other-thread))
375                        ((eq self other-thread)
376                         (let* ((chain (deadlock-chain self origin))
377                                (barf
378                                 (format nil
379                                         "~%WARNING: DEADLOCK CYCLE DETECTED:~%~@<   ~@;~
380                                          ~{~:@_~S~:@_~}~:@>~
381                                          ~%END OF CYCLE~%"
382                                         (mapcar #'car chain))))
383                           ;; Barf to stderr in case the system is too tied up
384                           ;; to report the error properly -- to avoid cross-talk
385                           ;; build the whole string up first.
386                           (write-string barf sb!sys:*stderr*)
387                           (finish-output sb!sys:*stderr*)
388                           (error 'thread-deadlock
389                                  :thread *current-thread*
390                                  :cycle chain)))
391                        (t
392                         (let ((other-lock (progn
393                                             (barrier (:read))
394                                             (thread-waiting-for other-thread))))
395                           ;; If the thread is waiting with a timeout OTHER-LOCK
396                           ;; is a cons, and we don't consider it a deadlock -- since
397                           ;; it will time out on its own sooner or later.
398                           (when (mutex-p other-lock)
399                             (detect-deadlock other-lock)))))))
400              (deadlock-chain (thread lock)
401                (let* ((other-thread (mutex-owner lock))
402                       (other-lock (when other-thread
403                                     (barrier (:read))
404                                     (thread-waiting-for other-thread))))
405                  (cond ((not other-thread)
406                         ;; The deadlock is gone -- maybe someone unwound
407                         ;; from the same deadlock already?
408                         (return-from check-deadlock nil))
409                        ((consp other-lock)
410                         ;; There's a timeout -- no deadlock.
411                         (return-from check-deadlock nil))
412                        ((waitqueue-p other-lock)
413                         ;; Not a lock.
414                         (return-from check-deadlock nil))
415                        ((eq self other-thread)
416                         ;; Done
417                         (list (list thread lock)))
418                        (t
419                         (if other-lock
420                             (cons (list thread lock)
421                                   (deadlock-chain other-thread other-lock))
422                             ;; Again, the deadlock is gone?
423                             (return-from check-deadlock nil)))))))
424       ;; Timeout means there is no deadlock
425       (when (mutex-p origin)
426         (detect-deadlock origin)
427         t))))
428
429 (defun %try-mutex (mutex new-owner)
430   (declare (type mutex mutex) (optimize (speed 3)))
431   (barrier (:read))
432   (let ((old (mutex-%owner mutex)))
433     (when (eq new-owner old)
434       (error "Recursive lock attempt ~S." mutex))
435     #!-sb-thread
436     (when old
437       (error "Strange deadlock on ~S in an unithreaded build?" mutex))
438     #!-(and sb-thread sb-futex)
439     (and (not old)
440          ;; Don't even bother to try to CAS if it looks bad.
441          (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
442     #!+(and sb-thread sb-futex)
443     ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
444     (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
445                                                     +lock-free+
446                                                     +lock-taken+))
447       (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
448         (when prev
449           (bug "Old owner in free mutex: ~S" prev))
450         t))))
451
452 #!+sb-thread
453 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
454   (declare (type mutex mutex) (optimize (speed 3)))
455   #!-sb-futex
456   (declare (ignore to-sec to-usec))
457   #!-sb-futex
458   (flet ((cas ()
459            (loop repeat 100
460                  when (and (progn
461                              (barrier (:read))
462                              (not (mutex-%owner mutex)))
463                            (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
464                                                          new-owner)))
465                  do (return-from cas t)
466                  else
467                  do
468                     (sb!ext:spin-loop-hint))
469            ;; Check for pending interrupts.
470            (with-interrupts nil)))
471     (declare (dynamic-extent #'cas))
472     (sb!impl::%%wait-for #'cas stop-sec stop-usec))
473   #!+sb-futex
474   ;; This is a fairly direct translation of the Mutex 2 algorithm from
475   ;; "Futexes are Tricky" by Ulrich Drepper.
476   (flet ((maybe (old)
477            (when (eql +lock-free+ old)
478              (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
479                                                   nil new-owner)))
480                (when prev
481                  (bug "Old owner in free mutex: ~S" prev))
482                (return-from %%wait-for-mutex t)))))
483     (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
484                                          +lock-free+ +lock-taken+)))
485        ;; Got it right off the bat?
486        (maybe old)
487      :retry
488        ;; Mark it as contested, and sleep. (Exception: it was just released.)
489        (when (or (eql +lock-contested+ old)
490                  (not (eql +lock-free+
491                            (sb!ext:compare-and-swap
492                             (mutex-state mutex) +lock-taken+ +lock-contested+))))
493          (when (eql 1 (with-pinned-objects (mutex)
494                         (futex-wait (mutex-state-address mutex)
495                                     (get-lisp-obj-address +lock-contested+)
496                                     (or to-sec -1)
497                                     (or to-usec 0))))
498            ;; -1 = EWOULDBLOCK, possibly spurious wakeup
499            ;;  0 = normal wakeup
500            ;;  1 = ETIMEDOUT ***DONE***
501            ;;  2 = EINTR, a spurious wakeup
502            (return-from %%wait-for-mutex nil)))
503        ;; Try to get it, still marking it as contested.
504        (maybe
505         (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
506        ;; Update timeout if necessary.
507        (when stop-sec
508          (setf (values to-sec to-usec)
509                (sb!impl::relative-decoded-times stop-sec stop-usec)))
510        ;; Spin.
511        (go :retry))))
512
513 #!+sb-thread
514 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
515   (with-deadlocks (self mutex timeout)
516     (with-interrupts (check-deadlock))
517     (tagbody
518      :again
519        (return-from %wait-for-mutex
520          (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
521              (when deadlinep
522                (signal-deadline)
523                ;; FIXME: substract elapsed time from timeout...
524                (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
525                      (decode-timeout timeout))
526                (go :again)))))))
527
528 (defun get-mutex (mutex &optional new-owner (waitp t) (timeout nil))
529   #!+sb-doc
530   "Deprecated in favor of GRAB-MUTEX."
531   (declare (ignorable waitp timeout))
532   (let ((new-owner (or new-owner *current-thread*)))
533     (or (%try-mutex mutex new-owner)
534         #!+sb-thread
535         (when waitp
536           (multiple-value-call #'%wait-for-mutex
537             mutex new-owner timeout (decode-timeout timeout))))))
538
539 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
540   #!+sb-doc
541   "Acquire MUTEX for the current thread. If WAITP is true (the default) and
542 the mutex is not immediately available, sleep until it is available.
543
544 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
545 GRAB-MUTEX should try to acquire the lock in the contested case.
546
547 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
548 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
549 that GRAB-MUTEX did -not- acquire the lock.
550
551 Notes:
552
553   - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
554
555       (WITHOUT-INTERRUPTS
556         ...
557         (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
558         ...)
559
560     WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
561     while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
562     allows the call to be interrupted from sleep.
563
564   - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
565     (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
566     DEADLINE-TIMEOUT if the global deadline was due already on entering
567     GRAB-MUTEX.
568
569     The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
570     future versions.
571
572   - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
573     directly.
574 "
575   (declare (ignorable waitp timeout))
576   (let ((self *current-thread*))
577     (or (%try-mutex mutex self)
578         #!+sb-thread
579         (when waitp
580           (multiple-value-call #'%wait-for-mutex
581             mutex self timeout (decode-timeout timeout))))))
582
583 (defun release-mutex (mutex &key (if-not-owner :punt))
584   #!+sb-doc
585   "Release MUTEX by setting it to NIL. Wake up threads waiting for
586 this mutex.
587
588 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
589 around calls to it.
590
591 If the current thread is not the owner of the mutex then it silently
592 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
593 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
594 IF-NOT-OWNER is :FORCE)."
595   (declare (type mutex mutex))
596   ;; Order matters: set owner to NIL before releasing state.
597   (let* ((self *current-thread*)
598          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
599     (unless (eq self old-owner)
600       (ecase if-not-owner
601         ((:punt) (return-from release-mutex nil))
602         ((:warn)
603          (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
604         ((:force)))
605       (setf (mutex-%owner mutex) nil)
606       ;; FIXME: Is a :memory barrier too strong here?  Can we use a :write
607       ;; barrier instead?
608       (barrier (:memory)))
609     #!+(and sb-thread sb-futex)
610     (when old-owner
611       ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
612       ;; unsigned-byte type this can be used:
613       ;;
614       ;;     (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
615       ;;       (unless (eql old +lock-free+)
616       ;;         (setf (mutex-state mutex) +lock-free+)
617       ;;         (with-pinned-objects (mutex)
618       ;;           (futex-wake (mutex-state-address mutex) 1))))
619       (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
620                                           +lock-taken+ +lock-free+)))
621         (when (eql old +lock-contested+)
622           (sb!ext:compare-and-swap (mutex-state mutex)
623                                    +lock-contested+ +lock-free+)
624           (with-pinned-objects (mutex)
625             (futex-wake (mutex-state-address mutex) 1))))
626       nil)))
627 \f
628
629 ;;;; Waitqueues/condition variables
630
631 #!+(or (not sb-thread) sb-futex)
632 (defstruct (waitqueue (:constructor %make-waitqueue))
633   #!+sb-doc
634   "Waitqueue type."
635   (name nil :type (or null thread-name))
636   #!+(and sb-thread sb-futex)
637   (token nil))
638
639 #!+(and sb-thread (not sb-futex))
640 (progn
641   (defstruct (waitqueue (:constructor %make-waitqueue))
642     #!+sb-doc
643     "Waitqueue type."
644     (name nil :type (or null thread-name))
645     ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
646     ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
647     ;; lock. In most cases this should be uncontested thanks to the mutex --
648     ;; the only case where that might not be true is when CONDITION-WAIT
649     ;; unwinds and %WAITQUEUE-DROP is called.
650     %owner
651     %head
652     %tail)
653
654   (defun %waitqueue-enqueue (thread queue)
655     (setf (thread-waiting-for thread) queue)
656     (let ((head (waitqueue-%head queue))
657           (tail (waitqueue-%tail queue))
658           (new (list thread)))
659       (unless head
660         (setf (waitqueue-%head queue) new))
661       (when tail
662         (setf (cdr tail) new))
663       (setf (waitqueue-%tail queue) new)
664       nil))
665   (defun %waitqueue-drop (thread queue)
666     (setf (thread-waiting-for thread) nil)
667     (let ((head (waitqueue-%head queue)))
668       (do ((list head (cdr list))
669            (prev nil list))
670           ((or (null list)
671                (eq (car list) thread))
672            (when list
673              (let ((rest (cdr list)))
674                (cond (prev
675                       (setf (cdr prev) rest))
676                      (t
677                       (setf (waitqueue-%head queue) rest
678                             prev rest)))
679                (unless rest
680                  (setf (waitqueue-%tail queue) prev)))))))
681     nil)
682   (defun %waitqueue-wakeup (queue n)
683     (declare (fixnum n))
684     (loop while (plusp n)
685           for next = (let ((head (waitqueue-%head queue))
686                            (tail (waitqueue-%tail queue)))
687                        (when head
688                          (if (eq head tail)
689                              (setf (waitqueue-%head queue) nil
690                                    (waitqueue-%tail queue) nil)
691                              (setf (waitqueue-%head queue) (cdr head)))
692                          (car head)))
693           while next
694           do (when (eq queue (sb!ext:compare-and-swap
695                               (thread-waiting-for next) queue nil))
696                (decf n)))
697     nil))
698
699 (def!method print-object ((waitqueue waitqueue) stream)
700   (print-unreadable-object (waitqueue stream :type t :identity t)
701     (format stream "~@[~A~]" (waitqueue-name waitqueue))))
702
703 (defun make-waitqueue (&key name)
704   #!+sb-doc
705   "Create a waitqueue."
706   (%make-waitqueue :name name))
707
708 #!+sb-doc
709 (setf (fdocumentation 'waitqueue-name 'function)
710       "The name of the waitqueue. Setfable.")
711
712 #!+(and sb-thread sb-futex)
713 (define-structure-slot-addressor waitqueue-token-address
714     :structure waitqueue
715     :slot token)
716
717 (defun condition-wait (queue mutex &key timeout)
718   #!+sb-doc
719   "Atomically release MUTEX and start waiting on QUEUE for till another thread
720 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
721 queue, at which point we re-acquire MUTEX and return T.
722
723 Spurious wakeups are possible.
724
725 If TIMEOUT is given, it is the maximum number of seconds to wait, including
726 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
727 wakeup and re-acquisition do not occur within the given time, returns NIL
728 without re-acquiring the mutex.
729
730 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
731
732 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
733 occurred the correct way to write code that uses CONDITION-WAIT is to loop
734 around the call, checking the the associated data:
735
736   (defvar *data* nil)
737   (defvar *queue* (make-waitqueue))
738   (defvar *lock* (make-mutex))
739
740   ;; Consumer
741   (defun pop-data (&optional timeout)
742     (with-mutex (*lock*)
743       (loop until *data*
744             do (or (condition-wait *queue* *lock* :timeout timeout)
745                    ;; Lock not held, must unwind without touching *data*.
746                    (return-from pop-data nil)))
747       (pop *data*)))
748
749   ;; Producer
750   (defun push-data (data)
751     (with-mutex (*lock*)
752       (push data *data*)
753       (condition-notify *queue*)))
754 "
755   #!-sb-thread
756   (declare (ignore queue))
757   (assert mutex)
758   #!-sb-thread
759   (sb!ext:wait-for nil :timeout timeout) ; Yeah...
760   #!+sb-thread
761   (let ((me *current-thread*))
762     (barrier (:read))
763     (assert (eq me (mutex-%owner mutex)))
764     (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
765         (decode-timeout timeout)
766       (let ((status :interrupted))
767         ;; Need to disable interrupts so that we don't miss grabbing the
768         ;; mutex on our way out.
769         (without-interrupts
770           (unwind-protect
771                (progn
772                  #!-sb-futex
773                  (progn
774                    (%with-cas-lock ((waitqueue-%owner queue))
775                      (%waitqueue-enqueue me queue))
776                    (release-mutex mutex)
777                    (setf status
778                          (or (flet ((wakeup ()
779                                       (barrier (:read))
780                                       (unless (eq queue (thread-waiting-for me))
781                                         :ok)))
782                                (declare (dynamic-extent #'wakeup))
783                                (allow-with-interrupts
784                                  (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
785                              :timeout)))
786                  #!+sb-futex
787                  (with-pinned-objects (queue me)
788                    (setf (waitqueue-token queue) me)
789                    (release-mutex mutex)
790                    ;; Now we go to sleep using futex-wait. If anyone else
791                    ;; manages to grab MUTEX and call CONDITION-NOTIFY during
792                    ;; this comment, it will change the token, and so futex-wait
793                    ;; returns immediately instead of sleeping. Ergo, no lost
794                    ;; wakeup. We may get spurious wakeups, but that's ok.
795                    (setf status
796                          (case (allow-with-interrupts
797                                  (futex-wait (waitqueue-token-address queue)
798                                              (get-lisp-obj-address me)
799                                              ;; our way of saying "no
800                                              ;; timeout":
801                                              (or to-sec -1)
802                                              (or to-usec 0)))
803                            ((1)
804                             ;;  1 = ETIMEDOUT
805                             :timeout)
806                            (t
807                             ;; -1 = EWOULDBLOCK, possibly spurious wakeup
808                             ;;  0 = normal wakeup
809                             ;;  2 = EINTR, a spurious wakeup
810                             :ok)))))
811             #!-sb-futex
812             (%with-cas-lock ((waitqueue-%owner queue))
813               (if (eq queue (thread-waiting-for me))
814                   (%waitqueue-drop me queue)
815                   (unless (eq :ok status)
816                     ;; CONDITION-NOTIFY thinks we've been woken up, but really
817                     ;; we're unwinding. Wake someone else up.
818                     (%waitqueue-wakeup queue 1))))
819             ;; Update timeout for mutex re-aquisition.
820             (when (and (eq :ok status) to-sec)
821               (setf (values to-sec to-usec)
822                     (sb!impl::relative-decoded-times stop-sec stop-usec)))
823             ;; If we ran into deadline, try to get the mutex before
824             ;; signaling. If we don't unwind it will look like a normal
825             ;; return from user perspective.
826             (when (and (eq :timeout status) deadlinep)
827               (let ((got-it (%try-mutex mutex me)))
828                 (allow-with-interrupts
829                   (signal-deadline)
830                   (cond (got-it
831                          (return-from condition-wait t))
832                         (t
833                          ;; The deadline may have changed.
834                          (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
835                                (decode-timeout timeout))
836                          (setf status :ok))))))
837             ;; Re-acquire the mutex for normal return.
838             (when (eq :ok status)
839               (unless (or (%try-mutex mutex me)
840                           (allow-with-interrupts
841                             (%wait-for-mutex mutex me timeout
842                                              to-sec to-usec
843                                              stop-sec stop-usec deadlinep)))
844                 (setf status :timeout)))))
845         (or (eq :ok status)
846             (unless (eq :timeout status)
847               ;; The only case we return normally without re-acquiring the
848               ;; mutex is when there is a :TIMEOUT that runs out.
849               (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
850
851 (defun condition-notify (queue &optional (n 1))
852   #!+sb-doc
853   "Notify N threads waiting on QUEUE.
854
855 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
856 must be held by this thread during this call."
857   #!-sb-thread
858   (declare (ignore queue n))
859   #!-sb-thread
860   (error "Not supported in unithread builds.")
861   #!+sb-thread
862   (declare (type (and fixnum (integer 1)) n))
863   (/show0 "Entering CONDITION-NOTIFY")
864   #!+sb-thread
865   (progn
866     #!-sb-futex
867     (with-cas-lock ((waitqueue-%owner queue))
868       (%waitqueue-wakeup queue n))
869     #!+sb-futex
870     (progn
871     ;; No problem if >1 thread notifies during the comment in condition-wait:
872     ;; as long as the value in queue-data isn't the waiting thread's id, it
873     ;; matters not what it is -- using the queue object itself is handy.
874     ;;
875     ;; XXX we should do something to ensure that the result of this setf
876     ;; is visible to all CPUs.
877     ;;
878     ;; ^-- surely futex_wake() involves a memory barrier?
879       (setf (waitqueue-token queue) queue)
880       (with-pinned-objects (queue)
881         (futex-wake (waitqueue-token-address queue) n)))))
882
883 (defun condition-broadcast (queue)
884   #!+sb-doc
885   "Notify all threads waiting on QUEUE.
886
887 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
888 must be held by this thread during this call."
889   (condition-notify queue
890                     ;; On a 64-bit platform truncating M-P-F to an int
891                     ;; results in -1, which wakes up only one thread.
892                     (ldb (byte 29 0)
893                          most-positive-fixnum)))
894 \f
895
896 ;;;; Semaphores
897
898 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
899   #!+sb-doc
900   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
901 should be considered an implementation detail, and may change in the
902 future."
903   (name    nil :type (or null thread-name))
904   (%count    0 :type (integer 0))
905   (waitcount 0 :type sb!vm:word)
906   (mutex (make-mutex))
907   (queue (make-waitqueue)))
908
909 (setf (fdocumentation 'semaphore-name 'function)
910       "The name of the semaphore INSTANCE. Setfable.")
911
912 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
913                                    (:copier nil))
914   #!+sb-doc
915   "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
916 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
917 multiple threads are using the same notification object in parallel."
918   (%status nil :type boolean))
919
920 (setf (fdocumentation 'make-semaphore-notification 'function)
921       "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
922 is initially NIL.")
923
924 (declaim (inline semaphore-notification-status))
925 (defun semaphore-notification-status (semaphore-notification)
926   #!+sb-doc
927   "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
928 SEMAPHORE-NOTICATION has succeeded since the notification object was created
929 or cleared."
930   (barrier (:read))
931   (semaphore-notification-%status semaphore-notification))
932
933 (declaim (inline clear-semaphore-notification))
934 (defun clear-semaphore-notification (semaphore-notification)
935   #!+sb-doc
936   "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
937 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
938   (barrier (:write)
939     (setf (semaphore-notification-%status semaphore-notification) nil)))
940
941 (declaim (inline semaphore-count))
942 (defun semaphore-count (instance)
943   #!+sb-doc
944   "Returns the current count of the semaphore INSTANCE."
945   (barrier (:read))
946   (semaphore-%count instance))
947
948 (defun make-semaphore (&key name (count 0))
949   #!+sb-doc
950   "Create a semaphore with the supplied COUNT and NAME."
951   (%make-semaphore name count))
952
953 (defun wait-on-semaphore (semaphore &key timeout notification)
954   #!+sb-doc
955   "Decrement the count of SEMAPHORE if the count would not be negative. Else
956 blocks until the semaphore can be decremented. Returns T on success.
957
958 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
959 cannot be decremented in that time, returns NIL without decrementing the
960 count.
961
962 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
963 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
964 decrements the count, the status is set to T."
965   (when (and notification (semaphore-notification-status notification))
966     (with-simple-restart (continue "Clear notification status and continue.")
967       (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
968              'wait-on-semaphore semaphore))
969     (clear-semaphore-notification notification))
970   ;; A more direct implementation based directly on futexes should be
971   ;; possible.
972   ;;
973   ;; We need to disable interrupts so that we don't forget to
974   ;; decrement the waitcount (which would happen if an asynch
975   ;; interrupt should catch us on our way out from the loop.)
976   ;;
977   ;; FIXME: No timeout on initial mutex acquisition.
978   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
979     ;; Quick check: is it positive? If not, enter the wait loop.
980     (let ((count (semaphore-%count semaphore)))
981       (cond ((plusp count)
982              (setf (semaphore-%count semaphore) (1- count))
983              (when notification
984                (setf (semaphore-notification-%status notification) t)))
985             (t
986              (unwind-protect
987                   (progn
988                     ;; Need to use ATOMIC-INCF despite the lock, because on our
989                     ;; way out from here we might not be locked anymore -- so
990                     ;; another thread might be tweaking this in parallel using
991                     ;; ATOMIC-DECF. No danger over overflow, since there it
992                     ;; at most one increment per thread waiting on the semaphore.
993                     (sb!ext:atomic-incf (semaphore-waitcount semaphore))
994                     (loop until (plusp (setf count (semaphore-%count semaphore)))
995                           do (or (condition-wait (semaphore-queue semaphore)
996                                                  (semaphore-mutex semaphore)
997                                                  :timeout timeout)
998                                  (return-from wait-on-semaphore nil)))
999                     (setf (semaphore-%count semaphore) (1- count))
1000                     (when notification
1001                       (setf (semaphore-notification-%status notification) t)))
1002                ;; Need to use ATOMIC-DECF as we may unwind without the lock
1003                ;; being held!
1004                (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
1005   t)
1006
1007 (defun try-semaphore (semaphore &optional (n 1) notification)
1008   #!+sb-doc
1009   "Try to decrement the count of SEMAPHORE by N. If the count were to
1010 become negative, punt and return NIL, otherwise return true.
1011
1012 If NOTIFICATION is given it must be a semaphore notification object
1013 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1014 the status is set to T."
1015   (declare (type (integer 1) n))
1016   (when (and notification (semaphore-notification-status notification))
1017     (with-simple-restart (continue "Clear notification status and continue.")
1018       (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1019              'try-semaphore semaphore))
1020     (clear-semaphore-notification notification))
1021   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1022     (let ((new-count (- (semaphore-%count semaphore) n)))
1023       (when (not (minusp new-count))
1024         (setf (semaphore-%count semaphore) new-count)
1025         (when notification
1026           (setf (semaphore-notifiction-%status notification) t))
1027         ;; FIXME: We don't actually document this -- should we just
1028         ;; return T, or document new count as the return?
1029         new-count))))
1030
1031 (defun signal-semaphore (semaphore &optional (n 1))
1032   #!+sb-doc
1033   "Increment the count of SEMAPHORE by N. If there are threads waiting
1034 on this semaphore, then N of them is woken up."
1035   (declare (type (integer 1) n))
1036   ;; Need to disable interrupts so that we don't lose a wakeup after
1037   ;; we have incremented the count.
1038   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1039     (let ((waitcount (semaphore-waitcount semaphore))
1040           (count (incf (semaphore-%count semaphore) n)))
1041       (when (plusp waitcount)
1042         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1043 \f
1044
1045 ;;;; Job control, independent listeners
1046
1047 (defstruct session
1048   (lock (make-mutex :name "session lock"))
1049   (threads nil)
1050   (interactive-threads nil)
1051   (interactive-threads-queue (make-waitqueue)))
1052
1053 (defvar *session* nil)
1054
1055 ;;; The debugger itself tries to acquire the session lock, don't let
1056 ;;; funny situations (like getting a sigint while holding the session
1057 ;;; lock) occur. At the same time we need to allow interrupts while
1058 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1059 ;;; be interruptible.
1060 ;;;
1061 ;;; Take care: we sometimes need to obtain the session lock while
1062 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1063 ;;; _after_ getting a session lock! (Deadlock risk.)
1064 ;;;
1065 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1066 ;;; like the above.
1067 (defmacro with-session-lock ((session) &body body)
1068   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1069      ,@body))
1070
1071 (defun new-session ()
1072   (make-session :threads (list *current-thread*)
1073                 :interactive-threads (list *current-thread*)))
1074
1075 (defun init-job-control ()
1076   (/show0 "Entering INIT-JOB-CONTROL")
1077   (setf *session* (new-session))
1078   (/show0 "Exiting INIT-JOB-CONTROL"))
1079
1080 (defun %delete-thread-from-session (thread session)
1081   (with-session-lock (session)
1082     (setf (session-threads session)
1083           (delete thread (session-threads session))
1084           (session-interactive-threads session)
1085           (delete thread (session-interactive-threads session)))))
1086
1087 (defun call-with-new-session (fn)
1088   (%delete-thread-from-session *current-thread* *session*)
1089   (let ((*session* (new-session)))
1090     (funcall fn)))
1091
1092 (defmacro with-new-session (args &body forms)
1093   (declare (ignore args))               ;for extensibility
1094   (sb!int:with-unique-names (fb-name)
1095     `(labels ((,fb-name () ,@forms))
1096       (call-with-new-session (function ,fb-name)))))
1097
1098 ;;; Remove thread from its session, if it has one.
1099 #!+sb-thread
1100 (defun handle-thread-exit (thread)
1101   (/show0 "HANDLING THREAD EXIT")
1102   ;; Lisp-side cleanup
1103   (with-all-threads-lock
1104     (setf (thread-%alive-p thread) nil)
1105     (setf (thread-os-thread thread) nil)
1106     (setq *all-threads* (delete thread *all-threads*))
1107     (when *session*
1108       (%delete-thread-from-session thread *session*))))
1109
1110 (defun terminate-session ()
1111   #!+sb-doc
1112   "Kill all threads in session except for this one.  Does nothing if current
1113 thread is not the foreground thread."
1114   ;; FIXME: threads created in other threads may escape termination
1115   (let ((to-kill
1116          (with-session-lock (*session*)
1117            (and (eq *current-thread*
1118                     (car (session-interactive-threads *session*)))
1119                 (session-threads *session*)))))
1120     ;; do the kill after dropping the mutex; unwind forms in dying
1121     ;; threads may want to do session things
1122     (dolist (thread to-kill)
1123       (unless (eq thread *current-thread*)
1124         ;; terminate the thread but don't be surprised if it has
1125         ;; exited in the meantime
1126         (handler-case (terminate-thread thread)
1127           (interrupt-thread-error ()))))))
1128
1129 ;;; called from top of invoke-debugger
1130 (defun debugger-wait-until-foreground-thread (stream)
1131   "Returns T if thread had been running in background, NIL if it was
1132 interactive."
1133   (declare (ignore stream))
1134   #!-sb-thread nil
1135   #!+sb-thread
1136   (prog1
1137       (with-session-lock (*session*)
1138         (not (member *current-thread*
1139                      (session-interactive-threads *session*))))
1140     (get-foreground)))
1141
1142 (defun get-foreground ()
1143   #!-sb-thread t
1144   #!+sb-thread
1145   (let ((was-foreground t))
1146     (loop
1147      (/show0 "Looping in GET-FOREGROUND")
1148      (with-session-lock (*session*)
1149        (let ((int-t (session-interactive-threads *session*)))
1150          (when (eq (car int-t) *current-thread*)
1151            (unless was-foreground
1152              (format *query-io* "Resuming thread ~A~%" *current-thread*))
1153            (return-from get-foreground t))
1154          (setf was-foreground nil)
1155          (unless (member *current-thread* int-t)
1156            (setf (cdr (last int-t))
1157                  (list *current-thread*)))
1158          (condition-wait
1159           (session-interactive-threads-queue *session*)
1160           (session-lock *session*)))))))
1161
1162 (defun release-foreground (&optional next)
1163   #!+sb-doc
1164   "Background this thread.  If NEXT is supplied, arrange for it to
1165 have the foreground next."
1166   #!-sb-thread (declare (ignore next))
1167   #!-sb-thread nil
1168   #!+sb-thread
1169   (with-session-lock (*session*)
1170     (when (rest (session-interactive-threads *session*))
1171       (setf (session-interactive-threads *session*)
1172             (delete *current-thread* (session-interactive-threads *session*))))
1173     (when next
1174       (setf (session-interactive-threads *session*)
1175             (list* next
1176                    (delete next (session-interactive-threads *session*)))))
1177     (condition-broadcast (session-interactive-threads-queue *session*))))
1178
1179 (defun foreground-thread ()
1180   (car (session-interactive-threads *session*)))
1181
1182 (defun make-listener-thread (tty-name)
1183   (assert (probe-file tty-name))
1184   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1185          (out (sb!unix:unix-dup in))
1186          (err (sb!unix:unix-dup in)))
1187     (labels ((thread-repl ()
1188                (sb!unix::unix-setsid)
1189                (let* ((sb!impl::*stdin*
1190                        (make-fd-stream in :input t :buffering :line
1191                                        :dual-channel-p t))
1192                       (sb!impl::*stdout*
1193                        (make-fd-stream out :output t :buffering :line
1194                                               :dual-channel-p t))
1195                       (sb!impl::*stderr*
1196                        (make-fd-stream err :output t :buffering :line
1197                                               :dual-channel-p t))
1198                       (sb!impl::*tty*
1199                        (make-fd-stream err :input t :output t
1200                                               :buffering :line
1201                                               :dual-channel-p t))
1202                       (sb!impl::*descriptor-handlers* nil))
1203                  (with-new-session ()
1204                    (unwind-protect
1205                         (sb!impl::toplevel-repl nil)
1206                      (sb!int:flush-standard-output-streams))))))
1207       (make-thread #'thread-repl))))
1208 \f
1209
1210 ;;;; The beef
1211
1212 (defun make-thread (function &key name arguments)
1213   #!+sb-doc
1214   "Create a new thread of NAME that runs FUNCTION with the argument
1215 list designator provided (defaults to no argument). When the function
1216 returns the thread exits. The return values of FUNCTION are kept
1217 around and can be retrieved by JOIN-THREAD."
1218   #!-sb-thread (declare (ignore function name arguments))
1219   #!-sb-thread (error "Not supported in unithread builds.")
1220   #!+sb-thread (assert (or (atom arguments)
1221                            (null (cdr (last arguments))))
1222                        (arguments)
1223                        "Argument passed to ~S, ~S, is an improper list."
1224                        'make-thread arguments)
1225   #!+sb-thread
1226   (let* ((thread (%make-thread :name name))
1227          (setup-sem (make-semaphore :name "Thread setup semaphore"))
1228          (real-function (coerce function 'function))
1229          (arguments     (if (listp arguments)
1230                             arguments
1231                             (list arguments)))
1232          (initial-function
1233           (named-lambda initial-thread-function ()
1234             ;; In time we'll move some of the binding presently done in C
1235             ;; here too.
1236             ;;
1237             ;; KLUDGE: Here we have a magic list of variables that are
1238             ;; not thread-safe for one reason or another.  As people
1239             ;; report problems with the thread safety of certain
1240             ;; variables, (e.g. "*print-case* in multiple threads
1241             ;; broken", sbcl-devel 2006-07-14), we add a few more
1242             ;; bindings here.  The Right Thing is probably some variant
1243             ;; of Allegro's *cl-default-special-bindings*, as that is at
1244             ;; least accessible to users to secure their own libraries.
1245             ;;   --njf, 2006-07-15
1246             ;;
1247             ;; As it is, this lambda must not cons until we are ready
1248             ;; to run GC. Be very careful.
1249             (let* ((*current-thread* thread)
1250                    (*restart-clusters* nil)
1251                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
1252                    (*condition-restarts* nil)
1253                    (sb!impl::*deadline* nil)
1254                    (sb!impl::*deadline-seconds* nil)
1255                    (sb!impl::*step-out* nil)
1256                    ;; internal printer variables
1257                    (sb!impl::*previous-case* nil)
1258                    (sb!impl::*previous-readtable-case* nil)
1259                    (sb!impl::*internal-symbol-output-fun* nil)
1260                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
1261               ;; Binding from C
1262               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1263               (setf (thread-os-thread thread) (current-thread-os-thread))
1264               (with-mutex ((thread-result-lock thread))
1265                 (with-all-threads-lock
1266                   (push thread *all-threads*))
1267                 (with-session-lock (*session*)
1268                   (push thread (session-threads *session*)))
1269                 (setf (thread-%alive-p thread) t)
1270                 (signal-semaphore setup-sem)
1271                 ;; can't use handling-end-of-the-world, because that flushes
1272                 ;; output streams, and we don't necessarily have any (or we
1273                 ;; could be sharing them)
1274                 (catch 'sb!impl::toplevel-catcher
1275                   (catch 'sb!impl::%end-of-the-world
1276                     (with-simple-restart
1277                         (terminate-thread
1278                          (format nil
1279                                  "~~@<Terminate this thread (~A)~~@:>"
1280                                  *current-thread*))
1281                       (without-interrupts
1282                         (unwind-protect
1283                              (with-local-interrupts
1284                                ;; Now that most things have a chance
1285                                ;; to work properly without messing up
1286                                ;; other threads, it's time to enable
1287                                ;; signals.
1288                                (sb!unix::unblock-deferrable-signals)
1289                                (setf (thread-result thread)
1290                                      (cons t
1291                                            (multiple-value-list
1292                                             (apply real-function arguments))))
1293                                ;; Try to block deferrables. An
1294                                ;; interrupt may unwind it, but for a
1295                                ;; normal exit it prevents interrupt
1296                                ;; loss.
1297                                (block-deferrable-signals))
1298                           ;; We're going down, can't handle interrupts
1299                           ;; sanely anymore. GC remains enabled.
1300                           (block-deferrable-signals)
1301                           ;; We don't want to run interrupts in a dead
1302                           ;; thread when we leave WITHOUT-INTERRUPTS.
1303                           ;; This potentially causes important
1304                           ;; interupts to be lost: SIGINT comes to
1305                           ;; mind.
1306                           (setq *interrupt-pending* nil)
1307                           (handle-thread-exit thread))))))))
1308             (values))))
1309     ;; If the starting thread is stopped for gc before it signals the
1310     ;; semaphore then we'd be stuck.
1311     (assert (not *gc-inhibit*))
1312     ;; Keep INITIAL-FUNCTION pinned until the child thread is
1313     ;; initialized properly. Wrap the whole thing in
1314     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1315     ;; thread.
1316     (without-interrupts
1317       (with-pinned-objects (initial-function)
1318         (let ((os-thread
1319                (%create-thread
1320                 (get-lisp-obj-address initial-function))))
1321           (when (zerop os-thread)
1322             (error "Can't create a new thread"))
1323           (wait-on-semaphore setup-sem)
1324           thread)))))
1325
1326 (defun join-thread (thread &key (default nil defaultp) timeout)
1327   #!+sb-doc
1328   "Suspend current thread until THREAD exits. Return the result values of the
1329 thread function.
1330
1331 If the thread does not exit normally within TIMEOUT seconds return DEFAULT if
1332 given, or else signal JOIN-THREAD-ERROR.
1333
1334 NOTE: Return convention in case of a timeout is exprimental and subject to
1335 change."
1336   (let ((lock (thread-result-lock thread))
1337         (got-it nil)
1338         (problem :timeout))
1339     (without-interrupts
1340       (unwind-protect
1341            (if (setf got-it
1342                      (allow-with-interrupts
1343                        ;; Don't use the timeout if the thread is not alive anymore.
1344                        (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1345                (cond ((car (thread-result thread))
1346                       (return-from join-thread
1347                         (values-list (cdr (thread-result thread)))))
1348                      (defaultp
1349                       (return-from join-thread default))
1350                      (t
1351                       (setf problem :abort)))
1352                (when defaultp
1353                  (return-from join-thread default)))
1354         (when got-it
1355           (release-mutex lock))))
1356     (error 'join-thread-error :thread thread :problem problem)))
1357
1358 (defun destroy-thread (thread)
1359   #!+sb-doc
1360   "Deprecated. Same as TERMINATE-THREAD."
1361   (terminate-thread thread))
1362
1363 (defmacro with-interruptions-lock ((thread) &body body)
1364   `(with-system-mutex ((thread-interruptions-lock ,thread))
1365      ,@body))
1366
1367 ;;; Called from the signal handler.
1368 #!-win32
1369 (defun run-interruption ()
1370   (let ((interruption (with-interruptions-lock (*current-thread*)
1371                         (pop (thread-interruptions *current-thread*)))))
1372     ;; If there is more to do, then resignal and let the normal
1373     ;; interrupt deferral mechanism take care of the rest. From the
1374     ;; OS's point of view the signal we are in the handler for is no
1375     ;; longer pending, so the signal will not be lost.
1376     (when (thread-interruptions *current-thread*)
1377       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1378     (when interruption
1379       (funcall interruption))))
1380
1381 (defun interrupt-thread (thread function)
1382   #!+sb-doc
1383   "Interrupt THREAD and make it run FUNCTION.
1384
1385 The interrupt is asynchronous, and can occur anywhere with the exception of
1386 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1387
1388 FUNCTION is called with interrupts disabled, under
1389 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1390 enable interrupts internally, in most cases FUNCTION should either enter
1391 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1392 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1393
1394 When a thread receives multiple interrupts, they are executed in the order
1395 they were sent -- first in, first out.
1396
1397 This means that a great degree of care is required to use INTERRUPT-THREAD
1398 safely and sanely in a production environment. The general recommendation is
1399 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1400 entirely from production environments -- it is simply exceedingly hard to use
1401 correctly.
1402
1403 With those caveats in mind, what you need to know when using it:
1404
1405  * If calling FUNCTION causes a non-local transfer of control (ie. an
1406    unwind), all normal cleanup forms will be executed.
1407
1408    However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1409    it is just as if that had happened due to a regular GO, THROW, or
1410    RETURN-FROM: the interrupted cleanup form and those following it in the
1411    same UNWIND-PROTECT do not get executed.
1412
1413    SBCL tries to keep its own internals asynch-unwind-safe, but this is
1414    frankly an unreasonable expectation for third party libraries, especially
1415    given that asynch-unwind-safety does not compose: a function calling
1416    only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1417
1418    This means that in order for an asych unwind to be safe, the entire
1419    callstack at the point of interruption needs to be asynch-unwind-safe.
1420
1421  * In addition to asynch-unwind-safety you must consider the issue of
1422    re-entrancy. INTERRUPT-THREAD can cause function that are never normally
1423    called recursively to be re-entered during their dynamic contour,
1424    which may cause them to misbehave. (Consider binding of special variables,
1425    values of global variables, etc.)
1426
1427 Take togather, these two restrict the \"safe\" things to do using
1428 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1429 interactive development use is using it to force entry to debugger to inspect
1430 the state of a thread:
1431
1432   (interrupt-thread thread #'break)
1433
1434 Short version: be careful out there."
1435  #!+win32
1436   (declare (ignore thread))
1437   #!+win32
1438   (with-interrupt-bindings
1439     (with-interrupts (funcall function)))
1440   #!-win32
1441   (let ((os-thread (thread-os-thread thread)))
1442     (cond ((not os-thread)
1443            (error 'interrupt-thread-error :thread thread))
1444           (t
1445            (with-interruptions-lock (thread)
1446              ;; Append to the end of the interruptions queue. It's
1447              ;; O(N), but it does not hurt to slow interruptors down a
1448              ;; bit when the queue gets long.
1449              (setf (thread-interruptions thread)
1450                    (append (thread-interruptions thread)
1451                            (list (lambda ()
1452                                    (without-interrupts
1453                                      (allow-with-interrupts
1454                                        (funcall function))))))))
1455            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1456              (error 'interrupt-thread-error :thread thread))))))
1457
1458 (defun terminate-thread (thread)
1459   #!+sb-doc
1460   "Terminate the thread identified by THREAD, by interrupting it and causing
1461 it to call SB-EXT:QUIT.
1462
1463 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that eg. thread
1464 executing
1465
1466   (let (foo)
1467      (unwind-protect
1468          (progn
1469             (setf foo (get-foo))
1470             (work-on-foo foo))
1471        (when foo
1472          ;; An interrupt occurring inside the cleanup clause
1473          ;; will cause cleanups from the current UNWIND-PROTECT
1474          ;; to be dropped.
1475          (release-foo foo))))
1476
1477 might miss calling RELEASE-FOO despite GET-FOO having returned true if the
1478 interrupt occurs inside the cleanup clause, eg. during execution of
1479 RELEASE-FOO.
1480
1481 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need to use
1482 WITHOUT-INTERRUPTS:
1483
1484   (let (foo)
1485     (sb-sys:without-interrupts
1486       (unwind-protect
1487           (progn
1488             (setf foo (sb-sys:allow-with-interrupts
1489                         (get-foo)))
1490             (sb-sys:with-local-interrupts
1491               (work-on-foo foo)))
1492        (when foo
1493          (release-foo foo)))))
1494
1495 Since most libraries using UNWIND-PROTECT do not do this, you should never
1496 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1497   (interrupt-thread thread 'sb!ext:quit))
1498
1499 (define-alien-routine "thread_yield" int)
1500
1501 #!+sb-doc
1502 (setf (fdocumentation 'thread-yield 'function)
1503       "Yield the processor to other threads.")
1504
1505 ;;; internal use only.  If you think you need to use these, either you
1506 ;;; are an SBCL developer, are doing something that you should discuss
1507 ;;; with an SBCL developer first, or are doing something that you
1508 ;;; should probably discuss with a professional psychiatrist first
1509 #!+sb-thread
1510 (progn
1511   (defun %thread-sap (thread)
1512     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1513           (target (thread-os-thread thread)))
1514       (loop
1515         (when (sap= thread-sap (int-sap 0)) (return nil))
1516         (let ((os-thread (sap-ref-word thread-sap
1517                                        (* sb!vm:n-word-bytes
1518                                           sb!vm::thread-os-thread-slot))))
1519           (when (= os-thread target) (return thread-sap))
1520           (setf thread-sap
1521                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1522                                            sb!vm::thread-next-slot)))))))
1523
1524   (defun %symbol-value-in-thread (symbol thread)
1525     ;; Prevent the thread from dying completely while we look for the TLS
1526     ;; area...
1527     (with-all-threads-lock
1528       (loop
1529         (if (thread-alive-p thread)
1530             (let* ((offset (sb!kernel:get-lisp-obj-address
1531                             (sb!vm::symbol-tls-index symbol)))
1532                    (obj (sap-ref-lispobj (%thread-sap thread) offset))
1533                    (tl-val (sb!kernel:get-lisp-obj-address obj)))
1534               (cond ((zerop offset)
1535                      (return (values nil :no-tls-value)))
1536                     ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1537                          (eql tl-val sb!vm:unbound-marker-widetag))
1538                      (return (values nil :unbound-in-thread)))
1539                     (t
1540                      (return (values obj :ok)))))
1541             (return (values nil :thread-dead))))))
1542
1543   (defun %set-symbol-value-in-thread (symbol thread value)
1544     (with-pinned-objects (value)
1545       ;; Prevent the thread from dying completely while we look for the TLS
1546       ;; area...
1547       (with-all-threads-lock
1548         (if (thread-alive-p thread)
1549             (let ((offset (sb!kernel:get-lisp-obj-address
1550                            (sb!vm::symbol-tls-index symbol))))
1551               (cond ((zerop offset)
1552                      (values nil :no-tls-value))
1553                     (t
1554                      (setf (sap-ref-lispobj (%thread-sap thread) offset)
1555                            value)
1556                      (values value :ok))))
1557             (values nil :thread-dead)))))
1558
1559   (define-alien-variable tls-index-start unsigned-int)
1560
1561   ;; Get values from the TLS area of the current thread.
1562   (defun %thread-local-references ()
1563     (without-gcing
1564       (let ((sap (%thread-sap *current-thread*)))
1565         (loop for index from tls-index-start
1566                 below (symbol-value 'sb!vm::*free-tls-index*)
1567               for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1568               for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1569               unless (or (not ok)
1570                          (typep obj '(or fixnum character))
1571                          (member value
1572                                  '(#.sb!vm:no-tls-value-marker-widetag
1573                                    #.sb!vm:unbound-marker-widetag))
1574                          (member obj seen :test #'eq))
1575                 collect obj into seen
1576               finally (return seen))))))
1577
1578 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1579   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1580 on success.
1581
1582 If the value cannot be retrieved (because the thread has exited or because it
1583 has no local binding for NAME) and ERRORP is true signals an error of type
1584 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1585 NIL, and a secondary value of NIL.
1586
1587 Can also be used with SETF to change the thread-local value of SYMBOL.
1588
1589 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1590 mechanism for inter-thread communication."
1591   (declare (symbol symbol) (thread thread))
1592   #!+sb-thread
1593   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1594     (if (eq :ok status)
1595         (values res t)
1596         (if errorp
1597             (error 'symbol-value-in-thread-error
1598                    :name symbol
1599                    :thread thread
1600                    :info (list :read status))
1601             (values nil nil))))
1602   #!-sb-thread
1603   (if (boundp symbol)
1604       (values (symbol-value symbol) t)
1605       (if errorp
1606           (error 'symbol-value-in-thread-error
1607                  :name symbol
1608                  :thread thread
1609                  :info (list :read :unbound-in-thread))
1610           (values nil nil))))
1611
1612 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1613   (declare (symbol symbol) (thread thread))
1614   #!+sb-thread
1615   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1616     (if (eq :ok status)
1617         (values res t)
1618         (if errorp
1619             (error 'symbol-value-in-thread-error
1620                    :name symbol
1621                    :thread thread
1622                    :info (list :write status))
1623             (values nil nil))))
1624   #!-sb-thread
1625   (if (boundp symbol)
1626       (values (setf (symbol-value symbol) value) t)
1627       (if errorp
1628           (error 'symbol-value-in-thread-error
1629                  :name symbol
1630                  :thread thread
1631                  :info (list :write :unbound-in-thread))
1632           (values nil nil))))
1633
1634 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1635   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1636 \f
1637
1638 ;;;; Stepping
1639
1640 (defun thread-stepping ()
1641   (make-lisp-obj
1642    (sap-ref-word (current-thread-sap)
1643                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1644
1645 (defun (setf thread-stepping) (value)
1646   (setf (sap-ref-word (current-thread-sap)
1647                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1648         (get-lisp-obj-address value)))