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