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