timeouts for WITH-MUTEX and WITH-RECURSIVE-LOCK
[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 (define-deprecated-function :early "1.0.37.33" get-mutex (grab-mutex)
619     (mutex &optional new-owner (waitp t) (timeout nil))
620   (declare (ignorable waitp timeout))
621   (let ((new-owner (or new-owner *current-thread*)))
622     (or (%try-mutex mutex new-owner)
623         #!+sb-thread
624         (when waitp
625           (multiple-value-call #'%wait-for-mutex
626             mutex new-owner timeout (decode-timeout timeout))))))
627
628 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
629   #!+sb-doc
630   "Acquire MUTEX for the current thread. If WAITP is true (the default) and
631 the mutex is not immediately available, sleep until it is available.
632
633 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
634 GRAB-MUTEX should try to acquire the lock in the contested case.
635
636 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
637 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
638 that GRAB-MUTEX did -not- acquire the lock.
639
640 Notes:
641
642   - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
643
644       (WITHOUT-INTERRUPTS
645         ...
646         (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
647         ...)
648
649     WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
650     while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
651     allows the call to be interrupted from sleep.
652
653   - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
654     (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
655     DEADLINE-TIMEOUT if the global deadline was due already on entering
656     GRAB-MUTEX.
657
658     The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
659     future versions.
660
661   - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
662     directly.
663 "
664   (declare (ignorable waitp timeout))
665   (let ((self *current-thread*))
666     (or (%try-mutex mutex self)
667         #!+sb-thread
668         (when waitp
669           (multiple-value-call #'%wait-for-mutex
670             mutex self timeout (decode-timeout timeout))))))
671
672 (defun release-mutex (mutex &key (if-not-owner :punt))
673   #!+sb-doc
674   "Release MUTEX by setting it to NIL. Wake up threads waiting for
675 this mutex.
676
677 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
678 around calls to it.
679
680 If the current thread is not the owner of the mutex then it silently
681 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
682 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
683 IF-NOT-OWNER is :FORCE)."
684   (declare (type mutex mutex))
685   ;; Order matters: set owner to NIL before releasing state.
686   (let* ((self *current-thread*)
687          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
688     (unless (eq self old-owner)
689       (ecase if-not-owner
690         ((:punt) (return-from release-mutex nil))
691         ((:warn)
692          (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
693         ((:force)))
694       (setf (mutex-%owner mutex) nil)
695       ;; FIXME: Is a :memory barrier too strong here?  Can we use a :write
696       ;; barrier instead?
697       (barrier (:memory)))
698     #!+(and sb-thread sb-futex)
699     (when old-owner
700       ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
701       ;; unsigned-byte type this can be used:
702       ;;
703       ;;     (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
704       ;;       (unless (eql old +lock-free+)
705       ;;         (setf (mutex-state mutex) +lock-free+)
706       ;;         (with-pinned-objects (mutex)
707       ;;           (futex-wake (mutex-state-address mutex) 1))))
708       (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
709                                           +lock-taken+ +lock-free+)))
710         (when (eql old +lock-contested+)
711           (sb!ext:compare-and-swap (mutex-state mutex)
712                                    +lock-contested+ +lock-free+)
713           (with-pinned-objects (mutex)
714             (futex-wake (mutex-state-address mutex) 1))))
715       nil)))
716 \f
717
718 ;;;; Waitqueues/condition variables
719
720 #!+(or (not sb-thread) sb-futex)
721 (defstruct (waitqueue (:constructor %make-waitqueue))
722   #!+sb-doc
723   "Waitqueue type."
724   (name nil :type (or null thread-name))
725   #!+(and sb-thread sb-futex)
726   (token nil))
727
728 #!+(and sb-thread (not sb-futex))
729 (progn
730   (defstruct (waitqueue (:constructor %make-waitqueue))
731     #!+sb-doc
732     "Waitqueue type."
733     (name nil :type (or null thread-name))
734     ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
735     ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
736     ;; lock. In most cases this should be uncontested thanks to the mutex --
737     ;; the only case where that might not be true is when CONDITION-WAIT
738     ;; unwinds and %WAITQUEUE-DROP is called.
739     %owner
740     %head
741     %tail)
742
743   (defun %waitqueue-enqueue (thread queue)
744     (setf (thread-waiting-for thread) queue)
745     (let ((head (waitqueue-%head queue))
746           (tail (waitqueue-%tail queue))
747           (new (list thread)))
748       (unless head
749         (setf (waitqueue-%head queue) new))
750       (when tail
751         (setf (cdr tail) new))
752       (setf (waitqueue-%tail queue) new)
753       nil))
754   (defun %waitqueue-drop (thread queue)
755     (setf (thread-waiting-for thread) nil)
756     (let ((head (waitqueue-%head queue)))
757       (do ((list head (cdr list))
758            (prev nil list))
759           ((or (null list)
760                (eq (car list) thread))
761            (when list
762              (let ((rest (cdr list)))
763                (cond (prev
764                       (setf (cdr prev) rest))
765                      (t
766                       (setf (waitqueue-%head queue) rest
767                             prev rest)))
768                (unless rest
769                  (setf (waitqueue-%tail queue) prev)))))))
770     nil)
771   (defun %waitqueue-wakeup (queue n)
772     (declare (fixnum n))
773     (loop while (plusp n)
774           for next = (let ((head (waitqueue-%head queue))
775                            (tail (waitqueue-%tail queue)))
776                        (when head
777                          (if (eq head tail)
778                              (setf (waitqueue-%head queue) nil
779                                    (waitqueue-%tail queue) nil)
780                              (setf (waitqueue-%head queue) (cdr head)))
781                          (car head)))
782           while next
783           do (when (eq queue (sb!ext:compare-and-swap
784                               (thread-waiting-for next) queue nil))
785                (decf n)))
786     nil))
787
788 (def!method print-object ((waitqueue waitqueue) stream)
789   (print-unreadable-object (waitqueue stream :type t :identity t)
790     (format stream "~@[~A~]" (waitqueue-name waitqueue))))
791
792 (defun make-waitqueue (&key name)
793   #!+sb-doc
794   "Create a waitqueue."
795   (%make-waitqueue :name name))
796
797 #!+sb-doc
798 (setf (fdocumentation 'waitqueue-name 'function)
799       "The name of the waitqueue. Setfable.")
800
801 #!+(and sb-thread sb-futex)
802 (define-structure-slot-addressor waitqueue-token-address
803     :structure waitqueue
804     :slot token)
805
806 (defun condition-wait (queue mutex &key timeout)
807   #!+sb-doc
808   "Atomically release MUTEX and start waiting on QUEUE for till another thread
809 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
810 queue, at which point we re-acquire MUTEX and return T.
811
812 Spurious wakeups are possible.
813
814 If TIMEOUT is given, it is the maximum number of seconds to wait, including
815 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
816 wakeup and re-acquisition do not occur within the given time, returns NIL
817 without re-acquiring the mutex.
818
819 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
820
821 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
822 occurred the correct way to write code that uses CONDITION-WAIT is to loop
823 around the call, checking the the associated data:
824
825   (defvar *data* nil)
826   (defvar *queue* (make-waitqueue))
827   (defvar *lock* (make-mutex))
828
829   ;; Consumer
830   (defun pop-data (&optional timeout)
831     (with-mutex (*lock*)
832       (loop until *data*
833             do (or (condition-wait *queue* *lock* :timeout timeout)
834                    ;; Lock not held, must unwind without touching *data*.
835                    (return-from pop-data nil)))
836       (pop *data*)))
837
838   ;; Producer
839   (defun push-data (data)
840     (with-mutex (*lock*)
841       (push data *data*)
842       (condition-notify *queue*)))
843 "
844   #!-sb-thread
845   (declare (ignore queue))
846   (assert mutex)
847   #!-sb-thread
848   (sb!ext:wait-for nil :timeout timeout) ; Yeah...
849   #!+sb-thread
850   (let ((me *current-thread*))
851     (barrier (:read))
852     (assert (eq me (mutex-%owner mutex)))
853     (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
854         (decode-timeout timeout)
855       (let ((status :interrupted))
856         ;; Need to disable interrupts so that we don't miss grabbing the
857         ;; mutex on our way out.
858         (without-interrupts
859           (unwind-protect
860                (progn
861                  #!-sb-futex
862                  (progn
863                    (%with-cas-lock ((waitqueue-%owner queue))
864                      (%waitqueue-enqueue me queue))
865                    (release-mutex mutex)
866                    (setf status
867                          (or (flet ((wakeup ()
868                                       (barrier (:read))
869                                       (unless (eq queue (thread-waiting-for me))
870                                         :ok)))
871                                (declare (dynamic-extent #'wakeup))
872                                (allow-with-interrupts
873                                  (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
874                              :timeout)))
875                  #!+sb-futex
876                  (with-pinned-objects (queue me)
877                    (setf (waitqueue-token queue) me)
878                    (release-mutex mutex)
879                    ;; Now we go to sleep using futex-wait. If anyone else
880                    ;; manages to grab MUTEX and call CONDITION-NOTIFY during
881                    ;; this comment, it will change the token, and so futex-wait
882                    ;; returns immediately instead of sleeping. Ergo, no lost
883                    ;; wakeup. We may get spurious wakeups, but that's ok.
884                    (setf status
885                          (case (allow-with-interrupts
886                                  (futex-wait (waitqueue-token-address queue)
887                                              (get-lisp-obj-address me)
888                                              ;; our way of saying "no
889                                              ;; timeout":
890                                              (or to-sec -1)
891                                              (or to-usec 0)))
892                            ((1)
893                             ;;  1 = ETIMEDOUT
894                             :timeout)
895                            (t
896                             ;; -1 = EWOULDBLOCK, possibly spurious wakeup
897                             ;;  0 = normal wakeup
898                             ;;  2 = EINTR, a spurious wakeup
899                             :ok)))))
900             #!-sb-futex
901             (%with-cas-lock ((waitqueue-%owner queue))
902               (if (eq queue (thread-waiting-for me))
903                   (%waitqueue-drop me queue)
904                   (unless (eq :ok status)
905                     ;; CONDITION-NOTIFY thinks we've been woken up, but really
906                     ;; we're unwinding. Wake someone else up.
907                     (%waitqueue-wakeup queue 1))))
908             ;; Update timeout for mutex re-aquisition.
909             (when (and (eq :ok status) to-sec)
910               (setf (values to-sec to-usec)
911                     (sb!impl::relative-decoded-times stop-sec stop-usec)))
912             ;; If we ran into deadline, try to get the mutex before
913             ;; signaling. If we don't unwind it will look like a normal
914             ;; return from user perspective.
915             (when (and (eq :timeout status) deadlinep)
916               (let ((got-it (%try-mutex mutex me)))
917                 (allow-with-interrupts
918                   (signal-deadline)
919                   (cond (got-it
920                          (return-from condition-wait t))
921                         (t
922                          ;; The deadline may have changed.
923                          (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
924                                (decode-timeout timeout))
925                          (setf status :ok))))))
926             ;; Re-acquire the mutex for normal return.
927             (when (eq :ok status)
928               (unless (or (%try-mutex mutex me)
929                           (allow-with-interrupts
930                             (%wait-for-mutex mutex me timeout
931                                              to-sec to-usec
932                                              stop-sec stop-usec deadlinep)))
933                 (setf status :timeout)))))
934         (or (eq :ok status)
935             (unless (eq :timeout status)
936               ;; The only case we return normally without re-acquiring the
937               ;; mutex is when there is a :TIMEOUT that runs out.
938               (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
939
940 (defun condition-notify (queue &optional (n 1))
941   #!+sb-doc
942   "Notify N threads waiting on QUEUE.
943
944 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
945 must be held by this thread during this call."
946   #!-sb-thread
947   (declare (ignore queue n))
948   #!-sb-thread
949   (error "Not supported in unithread builds.")
950   #!+sb-thread
951   (declare (type (and fixnum (integer 1)) n))
952   (/show0 "Entering CONDITION-NOTIFY")
953   #!+sb-thread
954   (progn
955     #!-sb-futex
956     (with-cas-lock ((waitqueue-%owner queue))
957       (%waitqueue-wakeup queue n))
958     #!+sb-futex
959     (progn
960     ;; No problem if >1 thread notifies during the comment in condition-wait:
961     ;; as long as the value in queue-data isn't the waiting thread's id, it
962     ;; matters not what it is -- using the queue object itself is handy.
963     ;;
964     ;; XXX we should do something to ensure that the result of this setf
965     ;; is visible to all CPUs.
966     ;;
967     ;; ^-- surely futex_wake() involves a memory barrier?
968       (setf (waitqueue-token queue) queue)
969       (with-pinned-objects (queue)
970         (futex-wake (waitqueue-token-address queue) n)))))
971
972 (defun condition-broadcast (queue)
973   #!+sb-doc
974   "Notify all threads waiting on QUEUE.
975
976 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
977 must be held by this thread during this call."
978   (condition-notify queue
979                     ;; On a 64-bit platform truncating M-P-F to an int
980                     ;; results in -1, which wakes up only one thread.
981                     (ldb (byte 29 0)
982                          most-positive-fixnum)))
983 \f
984
985 ;;;; Semaphores
986
987 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
988   #!+sb-doc
989   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
990 should be considered an implementation detail, and may change in the
991 future."
992   (name    nil :type (or null thread-name))
993   (%count    0 :type (integer 0))
994   (waitcount 0 :type sb!vm:word)
995   (mutex (make-mutex))
996   (queue (make-waitqueue)))
997
998 (setf (fdocumentation 'semaphore-name 'function)
999       "The name of the semaphore INSTANCE. Setfable.")
1000
1001 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
1002                                    (:copier nil))
1003   #!+sb-doc
1004   "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1005 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1006 multiple threads are using the same notification object in parallel."
1007   (%status nil :type boolean))
1008
1009 (setf (fdocumentation 'make-semaphore-notification 'function)
1010       "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1011 is initially NIL.")
1012
1013 (declaim (inline semaphore-notification-status))
1014 (defun semaphore-notification-status (semaphore-notification)
1015   #!+sb-doc
1016   "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1017 SEMAPHORE-NOTICATION has succeeded since the notification object was created
1018 or cleared."
1019   (barrier (:read))
1020   (semaphore-notification-%status semaphore-notification))
1021
1022 (declaim (inline clear-semaphore-notification))
1023 (defun clear-semaphore-notification (semaphore-notification)
1024   #!+sb-doc
1025   "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1026 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1027   (barrier (:write)
1028     (setf (semaphore-notification-%status semaphore-notification) nil)))
1029
1030 (declaim (inline semaphore-count))
1031 (defun semaphore-count (instance)
1032   #!+sb-doc
1033   "Returns the current count of the semaphore INSTANCE."
1034   (barrier (:read))
1035   (semaphore-%count instance))
1036
1037 (defun make-semaphore (&key name (count 0))
1038   #!+sb-doc
1039   "Create a semaphore with the supplied COUNT and NAME."
1040   (%make-semaphore name count))
1041
1042 (defun wait-on-semaphore (semaphore &key timeout notification)
1043   #!+sb-doc
1044   "Decrement the count of SEMAPHORE if the count would not be negative. Else
1045 blocks until the semaphore can be decremented. Returns T on success.
1046
1047 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1048 cannot be decremented in that time, returns NIL without decrementing the
1049 count.
1050
1051 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1052 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1053 decrements the count, the status is set to T."
1054   (when (and notification (semaphore-notification-status notification))
1055     (with-simple-restart (continue "Clear notification status and continue.")
1056       (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1057              'wait-on-semaphore semaphore))
1058     (clear-semaphore-notification notification))
1059   ;; A more direct implementation based directly on futexes should be
1060   ;; possible.
1061   ;;
1062   ;; We need to disable interrupts so that we don't forget to
1063   ;; decrement the waitcount (which would happen if an asynch
1064   ;; interrupt should catch us on our way out from the loop.)
1065   ;;
1066   ;; FIXME: No timeout on initial mutex acquisition.
1067   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1068     ;; Quick check: is it positive? If not, enter the wait loop.
1069     (let ((count (semaphore-%count semaphore)))
1070       (cond ((plusp count)
1071              (setf (semaphore-%count semaphore) (1- count))
1072              (when notification
1073                (setf (semaphore-notification-%status notification) t)))
1074             (t
1075              (unwind-protect
1076                   (progn
1077                     ;; Need to use ATOMIC-INCF despite the lock, because on our
1078                     ;; way out from here we might not be locked anymore -- so
1079                     ;; another thread might be tweaking this in parallel using
1080                     ;; ATOMIC-DECF. No danger over overflow, since there it
1081                     ;; at most one increment per thread waiting on the semaphore.
1082                     (sb!ext:atomic-incf (semaphore-waitcount semaphore))
1083                     (loop until (plusp (setf count (semaphore-%count semaphore)))
1084                           do (or (condition-wait (semaphore-queue semaphore)
1085                                                  (semaphore-mutex semaphore)
1086                                                  :timeout timeout)
1087                                  (return-from wait-on-semaphore nil)))
1088                     (setf (semaphore-%count semaphore) (1- count))
1089                     (when notification
1090                       (setf (semaphore-notification-%status notification) t)))
1091                ;; Need to use ATOMIC-DECF as we may unwind without the lock
1092                ;; being held!
1093                (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
1094   t)
1095
1096 (defun try-semaphore (semaphore &optional (n 1) notification)
1097   #!+sb-doc
1098   "Try to decrement the count of SEMAPHORE by N. If the count were to
1099 become negative, punt and return NIL, otherwise return true.
1100
1101 If NOTIFICATION is given it must be a semaphore notification object
1102 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1103 the status is set to T."
1104   (declare (type (integer 1) n))
1105   (when (and notification (semaphore-notification-status notification))
1106     (with-simple-restart (continue "Clear notification status and continue.")
1107       (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1108              'try-semaphore semaphore))
1109     (clear-semaphore-notification notification))
1110   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1111     (let ((new-count (- (semaphore-%count semaphore) n)))
1112       (when (not (minusp new-count))
1113         (setf (semaphore-%count semaphore) new-count)
1114         (when notification
1115           (setf (semaphore-notification-%status notification) t))
1116         ;; FIXME: We don't actually document this -- should we just
1117         ;; return T, or document new count as the return?
1118         new-count))))
1119
1120 (defun signal-semaphore (semaphore &optional (n 1))
1121   #!+sb-doc
1122   "Increment the count of SEMAPHORE by N. If there are threads waiting
1123 on this semaphore, then N of them is woken up."
1124   (declare (type (integer 1) n))
1125   ;; Need to disable interrupts so that we don't lose a wakeup after
1126   ;; we have incremented the count.
1127   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1128     (let ((waitcount (semaphore-waitcount semaphore))
1129           (count (incf (semaphore-%count semaphore) n)))
1130       (when (plusp waitcount)
1131         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1132 \f
1133
1134 ;;;; Job control, independent listeners
1135
1136 (defstruct session
1137   (lock (make-mutex :name "session lock"))
1138   (threads nil)
1139   (interactive-threads nil)
1140   (interactive-threads-queue (make-waitqueue)))
1141
1142 (defvar *session* nil)
1143
1144 ;;; The debugger itself tries to acquire the session lock, don't let
1145 ;;; funny situations (like getting a sigint while holding the session
1146 ;;; lock) occur. At the same time we need to allow interrupts while
1147 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1148 ;;; be interruptible.
1149 ;;;
1150 ;;; Take care: we sometimes need to obtain the session lock while
1151 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1152 ;;; _after_ getting a session lock! (Deadlock risk.)
1153 ;;;
1154 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1155 ;;; like the above.
1156 (defmacro with-session-lock ((session) &body body)
1157   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1158      ,@body))
1159
1160 (defun new-session ()
1161   (make-session :threads (list *current-thread*)
1162                 :interactive-threads (list *current-thread*)))
1163
1164 (defun init-job-control ()
1165   (/show0 "Entering INIT-JOB-CONTROL")
1166   (setf *session* (new-session))
1167   (/show0 "Exiting INIT-JOB-CONTROL"))
1168
1169 (defun %delete-thread-from-session (thread session)
1170   (with-session-lock (session)
1171     (setf (session-threads session)
1172           (delete thread (session-threads session))
1173           (session-interactive-threads session)
1174           (delete thread (session-interactive-threads session)))))
1175
1176 (defun call-with-new-session (fn)
1177   (%delete-thread-from-session *current-thread* *session*)
1178   (let ((*session* (new-session)))
1179     (funcall fn)))
1180
1181 (defmacro with-new-session (args &body forms)
1182   (declare (ignore args))               ;for extensibility
1183   (sb!int:with-unique-names (fb-name)
1184     `(labels ((,fb-name () ,@forms))
1185       (call-with-new-session (function ,fb-name)))))
1186
1187 ;;; Remove thread from its session, if it has one.
1188 #!+sb-thread
1189 (defun handle-thread-exit (thread)
1190   (/show0 "HANDLING THREAD EXIT")
1191   (when *exit-in-process*
1192     (%exit))
1193   ;; Lisp-side cleanup
1194   (with-all-threads-lock
1195     (setf (thread-%alive-p thread) nil)
1196     (setf (thread-os-thread thread) nil)
1197     (setq *all-threads* (delete thread *all-threads*))
1198     (when *session*
1199       (%delete-thread-from-session thread *session*))))
1200
1201 (defun %exit-other-threads ()
1202   ;; Grabbing this lock prevents new threads from
1203   ;; being spawned, and guarantees that *ALL-THREADS*
1204   ;; is up to date.
1205   (with-deadline (:seconds nil :override t)
1206     (grab-mutex *make-thread-lock*)
1207     (let ((timeout sb!ext:*exit-timeout*)
1208           (code *exit-in-process*)
1209           (current *current-thread*)
1210           (joinees nil)
1211           (main nil))
1212       (dolist (thread (list-all-threads))
1213         (cond ((eq thread current))
1214               ((main-thread-p thread)
1215                (setf main thread))
1216               (t
1217                (handler-case
1218                    (progn
1219                      (terminate-thread thread)
1220                      (push thread joinees))
1221                  (interrupt-thread-error ())))))
1222       (with-progressive-timeout (time-left :seconds timeout)
1223         (dolist (thread joinees)
1224           (join-thread thread :default t :timeout (time-left)))
1225         ;; Need to defer till others have joined, because when main
1226         ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1227         ;; get the exit code wrong.
1228         (when main
1229           (handler-case
1230               (interrupt-thread
1231                main
1232                (lambda ()
1233                  (setf *exit-in-process* (list code))
1234                  (throw 'sb!impl::%end-of-the-world t)))
1235             (interrupt-thread-error ()))
1236           ;; Normally this never finishes, as once the main-thread unwinds we
1237           ;; exit with the right code, but if times out before that happens,
1238           ;; we will exit after returning -- or rathe racing the main thread
1239           ;; to calling OS-EXIT.
1240           (join-thread main :default t :timeout (time-left)))))))
1241
1242 (defun terminate-session ()
1243   #!+sb-doc
1244   "Kill all threads in session except for this one.  Does nothing if current
1245 thread is not the foreground thread."
1246   ;; FIXME: threads created in other threads may escape termination
1247   (let ((to-kill
1248          (with-session-lock (*session*)
1249            (and (eq *current-thread*
1250                     (car (session-interactive-threads *session*)))
1251                 (session-threads *session*)))))
1252     ;; do the kill after dropping the mutex; unwind forms in dying
1253     ;; threads may want to do session things
1254     (dolist (thread to-kill)
1255       (unless (eq thread *current-thread*)
1256         ;; terminate the thread but don't be surprised if it has
1257         ;; exited in the meantime
1258         (handler-case (terminate-thread thread)
1259           (interrupt-thread-error ()))))))
1260
1261 ;;; called from top of invoke-debugger
1262 (defun debugger-wait-until-foreground-thread (stream)
1263   "Returns T if thread had been running in background, NIL if it was
1264 interactive."
1265   (declare (ignore stream))
1266   #!-sb-thread nil
1267   #!+sb-thread
1268   (prog1
1269       (with-session-lock (*session*)
1270         (not (member *current-thread*
1271                      (session-interactive-threads *session*))))
1272     (get-foreground)))
1273
1274 (defun get-foreground ()
1275   #!-sb-thread t
1276   #!+sb-thread
1277   (let ((was-foreground t))
1278     (loop
1279      (/show0 "Looping in GET-FOREGROUND")
1280      (with-session-lock (*session*)
1281        (let ((int-t (session-interactive-threads *session*)))
1282          (when (eq (car int-t) *current-thread*)
1283            (unless was-foreground
1284              (format *query-io* "Resuming thread ~A~%" *current-thread*))
1285            (return-from get-foreground t))
1286          (setf was-foreground nil)
1287          (unless (member *current-thread* int-t)
1288            (setf (cdr (last int-t))
1289                  (list *current-thread*)))
1290          (condition-wait
1291           (session-interactive-threads-queue *session*)
1292           (session-lock *session*)))))))
1293
1294 (defun release-foreground (&optional next)
1295   #!+sb-doc
1296   "Background this thread.  If NEXT is supplied, arrange for it to
1297 have the foreground next."
1298   #!-sb-thread (declare (ignore next))
1299   #!-sb-thread nil
1300   #!+sb-thread
1301   (with-session-lock (*session*)
1302     (when (rest (session-interactive-threads *session*))
1303       (setf (session-interactive-threads *session*)
1304             (delete *current-thread* (session-interactive-threads *session*))))
1305     (when next
1306       (setf (session-interactive-threads *session*)
1307             (list* next
1308                    (delete next (session-interactive-threads *session*)))))
1309     (condition-broadcast (session-interactive-threads-queue *session*))))
1310
1311 (defun foreground-thread ()
1312   (car (session-interactive-threads *session*)))
1313
1314 (defun make-listener-thread (tty-name)
1315   (assert (probe-file tty-name))
1316   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1317          (out (sb!unix:unix-dup in))
1318          (err (sb!unix:unix-dup in)))
1319     (labels ((thread-repl ()
1320                (sb!unix::unix-setsid)
1321                (let* ((sb!impl::*stdin*
1322                        (make-fd-stream in :input t :buffering :line
1323                                        :dual-channel-p t))
1324                       (sb!impl::*stdout*
1325                        (make-fd-stream out :output t :buffering :line
1326                                               :dual-channel-p t))
1327                       (sb!impl::*stderr*
1328                        (make-fd-stream err :output t :buffering :line
1329                                               :dual-channel-p t))
1330                       (sb!impl::*tty*
1331                        (make-fd-stream err :input t :output t
1332                                               :buffering :line
1333                                               :dual-channel-p t))
1334                       (sb!impl::*descriptor-handlers* nil))
1335                  (with-new-session ()
1336                    (unwind-protect
1337                         (sb!impl::toplevel-repl nil)
1338                      (sb!int:flush-standard-output-streams))))))
1339       (make-thread #'thread-repl))))
1340 \f
1341
1342 ;;;; The beef
1343
1344 (defun make-thread (function &key name arguments)
1345   #!+sb-doc
1346   "Create a new thread of NAME that runs FUNCTION with the argument
1347 list designator provided (defaults to no argument). Thread exits when
1348 the function returns. The return values of FUNCTION are kept around
1349 and can be retrieved by JOIN-THREAD.
1350
1351 Invoking the initial ABORT restart estabilished by MAKE-THREAD
1352 terminates the thread.
1353
1354 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1355   #!-sb-thread (declare (ignore function name arguments))
1356   #!-sb-thread (error "Not supported in unithread builds.")
1357   #!+sb-thread (assert (or (atom arguments)
1358                            (null (cdr (last arguments))))
1359                        (arguments)
1360                        "Argument passed to ~S, ~S, is an improper list."
1361                        'make-thread arguments)
1362   #!+sb-thread
1363   (tagbody
1364      (with-mutex (*make-thread-lock*)
1365        (let* ((thread (%make-thread :name name))
1366               (setup-sem (make-semaphore :name "Thread setup semaphore"))
1367               (real-function (coerce function 'function))
1368               (arguments     (if (listp arguments)
1369                                  arguments
1370                                  (list arguments)))
1371               (initial-function
1372                 (named-lambda initial-thread-function ()
1373                   ;; In time we'll move some of the binding presently done in C
1374                   ;; here too.
1375                   ;;
1376                   ;; KLUDGE: Here we have a magic list of variables that are
1377                   ;; not thread-safe for one reason or another.  As people
1378                   ;; report problems with the thread safety of certain
1379                   ;; variables, (e.g. "*print-case* in multiple threads
1380                   ;; broken", sbcl-devel 2006-07-14), we add a few more
1381                   ;; bindings here.  The Right Thing is probably some variant
1382                   ;; of Allegro's *cl-default-special-bindings*, as that is at
1383                   ;; least accessible to users to secure their own libraries.
1384                   ;;   --njf, 2006-07-15
1385                   ;;
1386                   ;; As it is, this lambda must not cons until we are ready
1387                   ;; to run GC. Be very careful.
1388                   (let* ((*current-thread* thread)
1389                          (*restart-clusters* nil)
1390                          (*handler-clusters* (sb!kernel::initial-handler-clusters))
1391                          (*condition-restarts* nil)
1392                          (*exit-in-process* nil)
1393                          (sb!impl::*deadline* nil)
1394                          (sb!impl::*deadline-seconds* nil)
1395                          (sb!impl::*step-out* nil)
1396                          ;; internal printer variables
1397                          (sb!impl::*previous-case* nil)
1398                          (sb!impl::*previous-readtable-case* nil)
1399                          (sb!impl::*internal-symbol-output-fun* nil)
1400                          (sb!impl::*descriptor-handlers* nil)) ; serve-event
1401                     ;; Binding from C
1402                     (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1403                     (setf (thread-os-thread thread) (current-thread-os-thread))
1404                     (with-mutex ((thread-result-lock thread))
1405                       (with-all-threads-lock
1406                         (push thread *all-threads*))
1407                       (with-session-lock (*session*)
1408                         (push thread (session-threads *session*)))
1409                       (setf (thread-%alive-p thread) t)
1410                       (signal-semaphore setup-sem)
1411                       ;; Using handling-end-of-the-world would be a bit tricky
1412                       ;; due to other catches and interrupts, so we essentially
1413                       ;; re-implement it here. Once and only once more.
1414                       (catch 'sb!impl::toplevel-catcher
1415                         (catch 'sb!impl::%end-of-the-world
1416                           (catch '%abort-thread
1417                             (with-simple-restart
1418                                 (abort "~@<Abort thread (~A)~@:>" *current-thread*)
1419                               (without-interrupts
1420                                 (unwind-protect
1421                                      (with-local-interrupts
1422                                        (sb!unix::unblock-deferrable-signals)
1423                                        (setf (thread-result thread)
1424                                              (prog1
1425                                                  (cons t
1426                                                        (multiple-value-list
1427                                                         (unwind-protect
1428                                                              (catch '%return-from-thread
1429                                                                (apply real-function arguments))
1430                                                           (when *exit-in-process*
1431                                                             (sb!impl::call-exit-hooks)))))
1432                                                #!+sb-safepoint
1433                                                (sb!kernel::gc-safepoint))))
1434                                   ;; We're going down, can't handle interrupts
1435                                   ;; sanely anymore. GC remains enabled.
1436                                   (block-deferrable-signals)
1437                                   ;; We don't want to run interrupts in a dead
1438                                   ;; thread when we leave WITHOUT-INTERRUPTS.
1439                                   ;; This potentially causes important
1440                                   ;; interupts to be lost: SIGINT comes to
1441                                   ;; mind.
1442                                   (setq *interrupt-pending* nil)
1443                                   #!+sb-thruption
1444                                   (setq *thruption-pending* nil)
1445                                   (handle-thread-exit thread)))))))))
1446                   (values))))
1447          ;; If the starting thread is stopped for gc before it signals the
1448          ;; semaphore then we'd be stuck.
1449          (assert (not *gc-inhibit*))
1450          ;; Keep INITIAL-FUNCTION pinned until the child thread is
1451          ;; initialized properly. Wrap the whole thing in
1452          ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1453          ;; thread.
1454          (without-interrupts
1455            (with-pinned-objects (initial-function)
1456              (let ((os-thread
1457                      (%create-thread
1458                       (get-lisp-obj-address initial-function))))
1459                (when (zerop os-thread)
1460                  (go :cant-spawn))
1461                (wait-on-semaphore setup-sem)
1462                (return-from make-thread thread))))))
1463    :cant-spawn
1464      (error "Could not create a new thread.")))
1465
1466 (defun join-thread (thread &key (default nil defaultp) timeout)
1467   #!+sb-doc
1468   "Suspend current thread until THREAD exits. Return the result values
1469 of the thread function.
1470
1471 If the thread does not exit normally within TIMEOUT seconds return
1472 DEFAULT if given, or else signal JOIN-THREAD-ERROR.
1473
1474 Trying to join the main thread will cause JOIN-THREAD to block until
1475 TIMEOUT occurs or the process exits: when main thread exits, the
1476 entire process exits.
1477
1478 NOTE: Return convention in case of a timeout is exprimental and
1479 subject to change."
1480   (let ((lock (thread-result-lock thread))
1481         (got-it nil)
1482         (problem :timeout))
1483     (without-interrupts
1484       (unwind-protect
1485            (if (setf got-it
1486                      (allow-with-interrupts
1487                        ;; Don't use the timeout if the thread is not alive anymore.
1488                        (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1489                (cond ((car (thread-result thread))
1490                       (return-from join-thread
1491                         (values-list (cdr (thread-result thread)))))
1492                      (defaultp
1493                       (return-from join-thread default))
1494                      (t
1495                       (setf problem :abort)))
1496                (when defaultp
1497                  (return-from join-thread default)))
1498         (when got-it
1499           (release-mutex lock))))
1500     (error 'join-thread-error :thread thread :problem problem)))
1501
1502 (defun destroy-thread (thread)
1503   #!+sb-doc
1504   "Deprecated. Same as TERMINATE-THREAD."
1505   (terminate-thread thread))
1506
1507 (defmacro with-interruptions-lock ((thread) &body body)
1508   `(with-system-mutex ((thread-interruptions-lock ,thread))
1509      ,@body))
1510
1511 ;;; Called from the signal handler.
1512 #!-(or sb-thruption win32)
1513 (defun run-interruption ()
1514   (let ((interruption (with-interruptions-lock (*current-thread*)
1515                         (pop (thread-interruptions *current-thread*)))))
1516     ;; If there is more to do, then resignal and let the normal
1517     ;; interrupt deferral mechanism take care of the rest. From the
1518     ;; OS's point of view the signal we are in the handler for is no
1519     ;; longer pending, so the signal will not be lost.
1520     (when (thread-interruptions *current-thread*)
1521       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1522     (when interruption
1523       (funcall interruption))))
1524
1525 #!+sb-thruption
1526 (defun run-interruption ()
1527   (in-interruption () ;the non-thruption code does this in the signal handler
1528     (let ((interruption (with-interruptions-lock (*current-thread*)
1529                           (pop (thread-interruptions *current-thread*)))))
1530       (when interruption
1531         (funcall interruption)
1532         ;; I tried implementing this function as an explicit LOOP, because
1533         ;; if we are currently processing the thruption queue, why not do
1534         ;; all of them in one go instead of one-by-one?
1535         ;;
1536         ;; I still think LOOPing would be basically the right thing
1537         ;; here.  But suppose some interruption unblocked deferrables.
1538         ;; Will the next one be happy with that?  The answer is "no", at
1539         ;; least in the sense that there are tests which check that
1540         ;; deferrables are blocked at the beginning of a thruption, and
1541         ;; races that make those tests fail.  Whether the tests are
1542         ;; misguided or not, it seems easier/cleaner to loop implicitly
1543         ;; -- and it's also what AK had implemented in the first place.
1544         ;;
1545         ;; The implicit loop is achieved by returning to C, but having C
1546         ;; call back to us immediately.  The runtime will reset the sigmask
1547         ;; in the mean time.
1548         ;; -- DFL
1549         (setf *thruption-pending* t)))))
1550
1551 (defun interrupt-thread (thread function)
1552   #!+sb-doc
1553   "Interrupt THREAD and make it run FUNCTION.
1554
1555 The interrupt is asynchronous, and can occur anywhere with the exception of
1556 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1557
1558 FUNCTION is called with interrupts disabled, under
1559 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1560 enable interrupts internally, in most cases FUNCTION should either enter
1561 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1562 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1563
1564 When a thread receives multiple interrupts, they are executed in the order
1565 they were sent -- first in, first out.
1566
1567 This means that a great degree of care is required to use INTERRUPT-THREAD
1568 safely and sanely in a production environment. The general recommendation is
1569 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1570 entirely from production environments -- it is simply exceedingly hard to use
1571 correctly.
1572
1573 With those caveats in mind, what you need to know when using it:
1574
1575  * If calling FUNCTION causes a non-local transfer of control (ie. an
1576    unwind), all normal cleanup forms will be executed.
1577
1578    However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1579    it is just as if that had happened due to a regular GO, THROW, or
1580    RETURN-FROM: the interrupted cleanup form and those following it in the
1581    same UNWIND-PROTECT do not get executed.
1582
1583    SBCL tries to keep its own internals asynch-unwind-safe, but this is
1584    frankly an unreasonable expectation for third party libraries, especially
1585    given that asynch-unwind-safety does not compose: a function calling
1586    only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1587
1588    This means that in order for an asych unwind to be safe, the entire
1589    callstack at the point of interruption needs to be asynch-unwind-safe.
1590
1591  * In addition to asynch-unwind-safety you must consider the issue of
1592    re-entrancy. INTERRUPT-THREAD can cause function that are never normally
1593    called recursively to be re-entered during their dynamic contour,
1594    which may cause them to misbehave. (Consider binding of special variables,
1595    values of global variables, etc.)
1596
1597 Take togather, these two restrict the \"safe\" things to do using
1598 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1599 interactive development use is using it to force entry to debugger to inspect
1600 the state of a thread:
1601
1602   (interrupt-thread thread #'break)
1603
1604 Short version: be careful out there."
1605  #!+win32
1606   (declare (ignore thread))
1607   #!+win32
1608   (with-interrupt-bindings
1609     (with-interrupts (funcall function)))
1610   #!-win32
1611   (let ((os-thread (thread-os-thread thread)))
1612     (cond ((not os-thread)
1613            (error 'interrupt-thread-error :thread thread))
1614           (t
1615            (with-interruptions-lock (thread)
1616              ;; Append to the end of the interruptions queue. It's
1617              ;; O(N), but it does not hurt to slow interruptors down a
1618              ;; bit when the queue gets long.
1619              (setf (thread-interruptions thread)
1620                    (append (thread-interruptions thread)
1621                            (list (lambda ()
1622                                    (without-interrupts
1623                                      (allow-with-interrupts
1624                                        (funcall function))))))))
1625            (when (minusp (wake-thread os-thread))
1626              (error 'interrupt-thread-error :thread thread))))))
1627
1628 (defun terminate-thread (thread)
1629   #!+sb-doc
1630   "Terminate the thread identified by THREAD, by interrupting it and
1631 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1632
1633 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1634 eg. thread executing
1635
1636   (let (foo)
1637      (unwind-protect
1638          (progn
1639             (setf foo (get-foo))
1640             (work-on-foo foo))
1641        (when foo
1642          ;; An interrupt occurring inside the cleanup clause
1643          ;; will cause cleanups from the current UNWIND-PROTECT
1644          ;; to be dropped.
1645          (release-foo foo))))
1646
1647 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1648 the interrupt occurs inside the cleanup clause, eg. during execution
1649 of RELEASE-FOO.
1650
1651 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1652 to use WITHOUT-INTERRUPTS:
1653
1654   (let (foo)
1655     (sb-sys:without-interrupts
1656       (unwind-protect
1657           (progn
1658             (setf foo (sb-sys:allow-with-interrupts
1659                         (get-foo)))
1660             (sb-sys:with-local-interrupts
1661               (work-on-foo foo)))
1662        (when foo
1663          (release-foo foo)))))
1664
1665 Since most libraries using UNWIND-PROTECT do not do this, you should never
1666 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1667   (interrupt-thread thread (lambda () (abort-thread :allow-exit t))))
1668
1669 (define-alien-routine "thread_yield" int)
1670
1671 #!+sb-doc
1672 (setf (fdocumentation 'thread-yield 'function)
1673       "Yield the processor to other threads.")
1674
1675 ;;; internal use only.  If you think you need to use these, either you
1676 ;;; are an SBCL developer, are doing something that you should discuss
1677 ;;; with an SBCL developer first, or are doing something that you
1678 ;;; should probably discuss with a professional psychiatrist first
1679 #!+sb-thread
1680 (progn
1681   (defun %thread-sap (thread)
1682     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1683           (target (thread-os-thread thread)))
1684       (loop
1685         (when (sap= thread-sap (int-sap 0)) (return nil))
1686         (let ((os-thread (sap-ref-word thread-sap
1687                                        (* sb!vm:n-word-bytes
1688                                           sb!vm::thread-os-thread-slot))))
1689           (when (= os-thread target) (return thread-sap))
1690           (setf thread-sap
1691                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1692                                            sb!vm::thread-next-slot)))))))
1693
1694   (defun %symbol-value-in-thread (symbol thread)
1695     ;; Prevent the thread from dying completely while we look for the TLS
1696     ;; area...
1697     (with-all-threads-lock
1698       (if (thread-alive-p thread)
1699           (let* ((offset (sb!kernel:get-lisp-obj-address
1700                           (sb!vm::symbol-tls-index symbol)))
1701                  (obj (sap-ref-lispobj (%thread-sap thread) offset))
1702                  (tl-val (sb!kernel:get-lisp-obj-address obj)))
1703             (cond ((zerop offset)
1704                    (values nil :no-tls-value))
1705                   ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1706                        (eql tl-val sb!vm:unbound-marker-widetag))
1707                    (values nil :unbound-in-thread))
1708                   (t
1709                    (values obj :ok))))
1710           (values nil :thread-dead))))
1711
1712   (defun %set-symbol-value-in-thread (symbol thread value)
1713     (with-pinned-objects (value)
1714       ;; Prevent the thread from dying completely while we look for the TLS
1715       ;; area...
1716       (with-all-threads-lock
1717         (if (thread-alive-p thread)
1718             (let ((offset (sb!kernel:get-lisp-obj-address
1719                            (sb!vm::symbol-tls-index symbol))))
1720               (cond ((zerop offset)
1721                      (values nil :no-tls-value))
1722                     (t
1723                      (setf (sap-ref-lispobj (%thread-sap thread) offset)
1724                            value)
1725                      (values value :ok))))
1726             (values nil :thread-dead)))))
1727
1728   (define-alien-variable tls-index-start unsigned-int)
1729
1730   ;; Get values from the TLS area of the current thread.
1731   (defun %thread-local-references ()
1732     (without-gcing
1733       (let ((sap (%thread-sap *current-thread*)))
1734         (loop for index from tls-index-start
1735                 below (symbol-value 'sb!vm::*free-tls-index*)
1736               for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1737               for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1738               unless (or (not ok)
1739                          (typep obj '(or fixnum character))
1740                          (member value
1741                                  '(#.sb!vm:no-tls-value-marker-widetag
1742                                    #.sb!vm:unbound-marker-widetag))
1743                          (member obj seen :test #'eq))
1744                 collect obj into seen
1745               finally (return seen))))))
1746
1747 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1748   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1749 on success.
1750
1751 If the value cannot be retrieved (because the thread has exited or because it
1752 has no local binding for NAME) and ERRORP is true signals an error of type
1753 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1754 NIL, and a secondary value of NIL.
1755
1756 Can also be used with SETF to change the thread-local value of SYMBOL.
1757
1758 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1759 mechanism for inter-thread communication."
1760   (declare (symbol symbol) (thread thread))
1761   #!+sb-thread
1762   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1763     (if (eq :ok status)
1764         (values res t)
1765         (if errorp
1766             (error 'symbol-value-in-thread-error
1767                    :name symbol
1768                    :thread thread
1769                    :info (list :read status))
1770             (values nil nil))))
1771   #!-sb-thread
1772   (if (boundp symbol)
1773       (values (symbol-value symbol) t)
1774       (if errorp
1775           (error 'symbol-value-in-thread-error
1776                  :name symbol
1777                  :thread thread
1778                  :info (list :read :unbound-in-thread))
1779           (values nil nil))))
1780
1781 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1782   (declare (symbol symbol) (thread thread))
1783   #!+sb-thread
1784   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1785     (if (eq :ok status)
1786         (values res t)
1787         (if errorp
1788             (error 'symbol-value-in-thread-error
1789                    :name symbol
1790                    :thread thread
1791                    :info (list :write status))
1792             (values nil nil))))
1793   #!-sb-thread
1794   (if (boundp symbol)
1795       (values (setf (symbol-value symbol) value) t)
1796       (if errorp
1797           (error 'symbol-value-in-thread-error
1798                  :name symbol
1799                  :thread thread
1800                  :info (list :write :unbound-in-thread))
1801           (values nil nil))))
1802
1803 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1804   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1805 \f
1806
1807 ;;;; Stepping
1808
1809 (defun thread-stepping ()
1810   (make-lisp-obj
1811    (sap-ref-word (current-thread-sap)
1812                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1813
1814 (defun (setf thread-stepping) (value)
1815   (setf (sap-ref-word (current-thread-sap)
1816                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1817         (get-lisp-obj-address value)))