1.0.44.3: better docstring for CONDITION-WAIT
[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 ;;; Conditions
15
16 (define-condition thread-error (error)
17   ((thread :reader thread-error-thread :initarg :thread))
18   #!+sb-doc
19   (:documentation
20    "Conditions of type THREAD-ERROR are signalled when thread operations fail.
21 The offending thread is initialized by the :THREAD initialization argument and
22 read by the function THREAD-ERROR-THREAD."))
23
24 #!+sb-doc
25 (setf
26  (fdocumentation 'thread-error-thread 'function)
27  "Return the offending thread that the THREAD-ERROR pertains to.")
28
29 (define-condition symbol-value-in-thread-error (cell-error thread-error)
30   ((info :reader symbol-value-in-thread-error-info :initarg :info))
31   (:report
32    (lambda (condition stream)
33      (destructuring-bind (op problem)
34          (symbol-value-in-thread-error-info condition)
35        (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
36                op
37                (cell-error-name condition)
38                (thread-error-thread condition)
39                (ecase problem
40                  (:unbound-in-thread "the symbol is unbound in thread.")
41                  (:no-tls-value "the symbol has no thread-local value.")
42                  (:thread-dead "the thread has exited.")
43                  (:invalid-tls-value "the thread-local value is not valid."))))))
44   #!+sb-doc
45   (:documentation
46    "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
47 the symbol not having a thread-local value, or the target thread having
48 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
49 offending thread using THREAD-ERROR-THREAD."))
50
51 (define-condition join-thread-error (thread-error) ()
52   (:report (lambda (c s)
53              (format s "Joining thread failed: thread ~A ~
54                         did not return normally."
55                      (thread-error-thread c))))
56   #!+sb-doc
57   (:documentation
58    "Signalled when joining a thread fails due to abnormal exit of the thread
59 to be joined. The offending thread can be accessed using
60 THREAD-ERROR-THREAD."))
61
62 (defun join-thread-error-thread (condition)
63   (thread-error-thread condition))
64 (define-compiler-macro join-thread-error-thread (condition)
65   (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
66   `(thread-error-thread ,condition))
67
68 #!+sb-doc
69 (setf
70  (fdocumentation 'join-thread-error-thread 'function)
71  "The thread that we failed to join. Deprecated, use THREAD-ERROR-THREAD
72 instead.")
73
74 (define-condition interrupt-thread-error (thread-error) ()
75   (:report (lambda (c s)
76              (format s "Interrupt thread failed: thread ~A has exited."
77                      (thread-error-thread c))))
78   #!+sb-doc
79   (:documentation
80    "Signalled when interrupting a thread fails because the thread has already
81 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
82
83 (defun interrupt-thread-error-thread (condition)
84   (thread-error-thread condition))
85 (define-compiler-macro interrupt-thread-error-thread (condition)
86   (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
87   `(thread-error-thread ,condition))
88
89 #!+sb-doc
90 (setf
91  (fdocumentation 'interrupt-thread-error-thread 'function)
92  "The thread that was not interrupted. Deprecated, use THREAD-ERROR-THREAD
93 instead.")
94
95 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
96 ;;; necessary because threads are only supported with the conservative
97 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
98 ;;; are treated as references.
99
100 ;;; set the doc here because in early-thread FDOCUMENTATION is not
101 ;;; available, yet
102 #!+sb-doc
103 (setf (fdocumentation '*current-thread* 'variable)
104       "Bound in each thread to the thread itself.")
105
106 #!+sb-doc
107 (setf
108  (fdocumentation 'thread-name 'function)
109  "Name of the thread. Can be assigned to using SETF. Thread names can be
110 arbitrary printable objects, and need not be unique.")
111
112 (def!method print-object ((thread thread) stream)
113   (print-unreadable-object (thread stream :type t :identity t)
114     (let* ((cookie (list thread))
115            (info (if (thread-alive-p thread)
116                      :running
117                      (multiple-value-list
118                       (join-thread thread :default cookie))))
119            (state (if (eq :running info)
120                       info
121                       (if (eq cookie (car info))
122                           :aborted
123                           :finished)))
124            (values (when (eq :finished state) info)))
125       (format stream
126               "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
127               (thread-name thread)
128               (eq :finished state)
129               state
130               values))))
131
132 (defun thread-alive-p (thread)
133   #!+sb-doc
134   "Return T if THREAD is still alive. Note that the return value is
135 potentially stale even before the function returns, as the thread may exit at
136 any time."
137   (thread-%alive-p thread))
138
139 ;; A thread is eligible for gc iff it has finished and there are no
140 ;; more references to it. This list is supposed to keep a reference to
141 ;; all running threads.
142 (defvar *all-threads* ())
143 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
144
145 (defvar *default-alloc-signal* nil)
146
147 (defmacro with-all-threads-lock (&body body)
148   `(with-system-mutex (*all-threads-lock*)
149      ,@body))
150
151 (defun list-all-threads ()
152   #!+sb-doc
153   "Return a list of the live threads. Note that the return value is
154 potentially stale even before the function returns, as new threads may be
155 created and old ones may exit at any time."
156   (with-all-threads-lock
157     (copy-list *all-threads*)))
158
159 (declaim (inline current-thread-sap))
160 (defun current-thread-sap ()
161   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
162
163 (declaim (inline current-thread-os-thread))
164 (defun current-thread-os-thread ()
165   #!+sb-thread
166   (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
167   #!-sb-thread
168   0)
169
170 (defun init-initial-thread ()
171   (/show0 "Entering INIT-INITIAL-THREAD")
172   (let ((initial-thread (%make-thread :name "initial thread"
173                                       :%alive-p t
174                                       :os-thread (current-thread-os-thread))))
175     (setq *current-thread* initial-thread)
176     ;; Either *all-threads* is empty or it contains exactly one thread
177     ;; in case we are in reinit since saving core with multiple
178     ;; threads doesn't work.
179     (setq *all-threads* (list initial-thread))))
180 \f
181
182 ;;;; Aliens, low level stuff
183
184 (define-alien-routine "kill_safely"
185     integer
186   (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
187   (signal int))
188
189 #!+sb-thread
190 (progn
191   ;; FIXME it would be good to define what a thread id is or isn't
192   ;; (our current assumption is that it's a fixnum).  It so happens
193   ;; that on Linux it's a pid, but it might not be on posix thread
194   ;; implementations.
195   (define-alien-routine ("create_thread" %create-thread)
196       unsigned-long (lisp-fun-address unsigned-long))
197
198   (declaim (inline %block-deferrable-signals))
199   (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
200       void
201     (where sb!alien:unsigned-long)
202     (old sb!alien:unsigned-long))
203
204   (defun block-deferrable-signals ()
205     (%block-deferrable-signals 0 0))
206
207   #!+sb-lutex
208   (progn
209     (declaim (inline %lutex-init %lutex-wait %lutex-wake
210                      %lutex-lock %lutex-unlock))
211
212     (define-alien-routine ("lutex_init" %lutex-init)
213         int (lutex unsigned-long))
214
215     (define-alien-routine ("lutex_wait" %lutex-wait)
216         int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
217
218     (define-alien-routine ("lutex_wake" %lutex-wake)
219         int (lutex unsigned-long) (n int))
220
221     (define-alien-routine ("lutex_lock" %lutex-lock)
222         int (lutex unsigned-long))
223
224     (define-alien-routine ("lutex_trylock" %lutex-trylock)
225         int (lutex unsigned-long))
226
227     (define-alien-routine ("lutex_unlock" %lutex-unlock)
228         int (lutex unsigned-long))
229
230     (define-alien-routine ("lutex_destroy" %lutex-destroy)
231         int (lutex unsigned-long))
232
233     ;; FIXME: Defining a whole bunch of alien-type machinery just for
234     ;; passing primitive lutex objects directly to foreign functions
235     ;; doesn't seem like fun right now. So instead we just manually
236     ;; pin the lutex, get its address, and let the callee untag it.
237     (defmacro with-lutex-address ((name lutex) &body body)
238       `(let ((,name ,lutex))
239          (with-pinned-objects (,name)
240            (let ((,name (get-lisp-obj-address ,name)))
241              ,@body))))
242
243     (defun make-lutex ()
244       (/show0 "Entering MAKE-LUTEX")
245       ;; Suppress GC until the lutex has been properly registered with
246       ;; the GC.
247       (without-gcing
248         (let ((lutex (sb!vm::%make-lutex)))
249           (/show0 "LUTEX=..")
250           (/hexstr lutex)
251           (with-lutex-address (lutex lutex)
252             (%lutex-init lutex))
253           lutex))))
254
255   #!-sb-lutex
256   (progn
257     (declaim (inline futex-wait %futex-wait futex-wake))
258
259     (define-alien-routine ("futex_wait" %futex-wait)
260         int (word unsigned-long) (old-value unsigned-long)
261         (to-sec long) (to-usec unsigned-long))
262
263     (defun futex-wait (word old to-sec to-usec)
264       (with-interrupts
265         (%futex-wait word old to-sec to-usec)))
266
267     (define-alien-routine "futex_wake"
268         int (word unsigned-long) (n unsigned-long))))
269
270 ;;; used by debug-int.lisp to access interrupt contexts
271 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
272 #!-sb-thread
273 (defun sb!vm::current-thread-offset-sap (n)
274   (declare (type (unsigned-byte 27) n))
275   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
276                (* n sb!vm:n-word-bytes)))
277
278 #!+sb-thread
279 (defun sb!vm::current-thread-offset-sap (n)
280   (declare (type (unsigned-byte 27) n))
281   (sb!vm::current-thread-offset-sap n))
282 \f
283
284 ;;;; Spinlocks
285
286 (declaim (inline get-spinlock release-spinlock))
287
288 ;;; Should always be called with interrupts disabled.
289 (defun get-spinlock (spinlock)
290   (declare (optimize (speed 3) (safety 0)))
291   (let* ((new *current-thread*)
292          (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
293     (when old
294       (when (eq old new)
295         (error "Recursive lock attempt on ~S." spinlock))
296       #!+sb-thread
297       (flet ((cas ()
298                (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
299                    (thread-yield)
300                    (return-from get-spinlock t))))
301         (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
302             ;; If interrupts are disabled, but we are allowed to
303             ;; enabled them, check for pending interrupts every once
304             ;; in a while. %CHECK-INTERRUPTS is taking shortcuts, make
305             ;; sure that deferrables are unblocked by doing an empty
306             ;; WITH-INTERRUPTS once.
307             (progn
308               (with-interrupts)
309               (loop
310                (loop repeat 128 do (cas)) ; 128 is arbitrary here
311                (sb!unix::%check-interrupts)))
312             (loop (cas)))))
313     t))
314
315 (defun release-spinlock (spinlock)
316   (declare (optimize (speed 3) (safety 0)))
317   ;; On x86 and x86-64 we can get away with no memory barriers, (see
318   ;; Linux kernel mailing list "spin_unlock optimization(i386)"
319   ;; thread, summary at
320   ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
321   ;;
322   ;; If the compiler may reorder this with other instructions, insert
323   ;; compiler barrier here.
324   ;;
325   ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
326   ;; neither on most non-x86 architectures (but we don't have threads
327   ;; on those).
328   (setf (spinlock-value spinlock) nil)
329
330   ;; FIXME: Is a :memory barrier too strong here?  Can we use a :write
331   ;; barrier instead?
332   #!+(not (or x86 x86-64))
333   (barrier (:memory)))
334 \f
335
336 ;;;; Mutexes
337
338 #!+sb-doc
339 (setf (fdocumentation 'make-mutex 'function)
340       "Create a mutex."
341       (fdocumentation 'mutex-name 'function)
342       "The name of the mutex. Setfable.")
343
344 #!+(and sb-thread (not sb-lutex))
345 (progn
346   (define-structure-slot-addressor mutex-state-address
347       :structure mutex
348       :slot state)
349   ;; Important: current code assumes these are fixnums or other
350   ;; lisp objects that don't need pinning.
351   (defconstant +lock-free+ 0)
352   (defconstant +lock-taken+ 1)
353   (defconstant +lock-contested+ 2))
354
355 (defun mutex-owner (mutex)
356   "Current owner of the mutex, NIL if the mutex is free. Naturally,
357 this is racy by design (another thread may acquire the mutex after
358 this function returns), it is intended for informative purposes. For
359 testing whether the current thread is holding a mutex see
360 HOLDING-MUTEX-P."
361   ;; Make sure to get the current value.
362   (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
363
364 (defun get-mutex (mutex &optional (new-owner *current-thread*)
365                                   (waitp t) (timeout nil))
366   #!+sb-doc
367   "Deprecated in favor of GRAB-MUTEX."
368   (declare (type mutex mutex) (optimize (speed 3))
369            #!-sb-thread (ignore waitp timeout))
370   (unless new-owner
371     (setq new-owner *current-thread*))
372   (barrier (:read))
373   (let ((old (mutex-%owner mutex)))
374     (when (eq new-owner old)
375       (error "Recursive lock attempt ~S." mutex))
376     #!-sb-thread
377     (when old
378       (error "Strange deadlock on ~S in an unithreaded build?" mutex)))
379   #!-sb-thread
380   (setf (mutex-%owner mutex) new-owner)
381   #!+sb-thread
382   (progn
383     ;; FIXME: Lutexes do not currently support deadlines, as at least
384     ;; on Darwin pthread_foo_timedbar functions are not supported:
385     ;; this means that we probably need to use the Carbon multiprocessing
386     ;; functions on Darwin.
387     ;;
388     ;; FIXME: This is definitely not interrupt safe: what happens if
389     ;; we get hit (1) during the lutex calls (ok, they may be safe,
390     ;; but has that been checked?) (2) after the lutex call, but
391     ;; before setting the mutex owner.
392     #!+sb-lutex
393     (progn
394       (when timeout
395         (error "Mutex timeouts not supported on this platform."))
396       (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
397                     (if waitp
398                         (with-interrupts (%lutex-lock lutex))
399                         (%lutex-trylock lutex))))
400        (setf (mutex-%owner mutex) new-owner)
401        (barrier (:write))
402        t))
403     #!-sb-lutex
404     ;; This is a direct translation of the Mutex 2 algorithm from
405     ;; "Futexes are Tricky" by Ulrich Drepper.
406     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
407                                         +lock-free+
408                                         +lock-taken+)))
409       (unless (or (eql +lock-free+ old) (not waitp))
410         (tagbody
411          :retry
412            (when (or (eql +lock-contested+ old)
413                      (not (eql +lock-free+
414                                (sb!ext:compare-and-swap (mutex-state mutex)
415                                                         +lock-taken+
416                                                         +lock-contested+))))
417              ;; Wait on the contested lock.
418              (loop
419               (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
420                   (decode-timeout timeout)
421                 (declare (ignore stop-sec stop-usec))
422                 (case (with-pinned-objects (mutex)
423                         (futex-wait (mutex-state-address mutex)
424                                     (get-lisp-obj-address +lock-contested+)
425                                     (or to-sec -1)
426                                     (or to-usec 0)))
427                   ((1) (if deadlinep
428                            (signal-deadline)
429                            (return-from get-mutex nil)))
430                   ((2))
431                   (otherwise (return))))))
432            (setf old (sb!ext:compare-and-swap (mutex-state mutex)
433                                               +lock-free+
434                                               +lock-contested+))
435            ;; Did we get it?
436            (unless (eql +lock-free+ old)
437              (go :retry))))
438       (cond ((eql +lock-free+ old)
439              (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
440                                                   nil new-owner)))
441                (when prev
442                  (bug "Old owner in free mutex: ~S" prev))
443                t))
444             (waitp
445              (bug "Failed to acquire lock with WAITP."))))))
446
447 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
448   #!+sb-doc
449   "Acquire MUTEX for the current thread. If WAITP is true (the default) and
450 the mutex is not immediately available, sleep until it is available.
451
452 If TIMEOUT is given, it specifies a relative timeout, in seconds, on
453 how long GRAB-MUTEX should try to acquire the lock in the contested
454 case. Unsupported on :SB-LUTEX platforms (eg. Darwin), where a non-NIL
455 TIMEOUT signals an error.
456
457 If GRAB-MUTEX returns T, the lock acquisition was successful. In case
458 of WAITP being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return
459 NIL which denotes that GRAB-MUTEX did -not- acquire the lock.
460
461 Notes:
462
463   - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
464
465       (WITHOUT-INTERRUPTS
466         ...
467         (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
468         ...)
469
470     WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding
471     the call while the mutex is in an inconsistent state while
472     ALLOW-WITH-INTERRUPTS allows the call to be interrupted from
473     sleep.
474
475   - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
476     (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
477     DEADLINE-TIMEOUT if the global deadline was due already on
478     entering GRAB-MUTEX.
479
480     The exact interplay of GRAB-MUTEX and deadlines are reserved to
481     change in future versions.
482
483   - It is recommended that you use WITH-MUTEX instead of calling
484     GRAB-MUTEX directly.
485 "
486   (get-mutex mutex nil waitp timeout))
487
488 (defun release-mutex (mutex &key (if-not-owner :punt))
489   #!+sb-doc
490   "Release MUTEX by setting it to NIL. Wake up threads waiting for
491 this mutex.
492
493 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
494 around calls to it.
495
496 If the current thread is not the owner of the mutex then it silently
497 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
498 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
499 IF-NOT-OWNER is :FORCE)."
500   (declare (type mutex mutex))
501   ;; Order matters: set owner to NIL before releasing state.
502   (let* ((self *current-thread*)
503          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
504     (unless (eql self old-owner)
505       (ecase if-not-owner
506         ((:punt) (return-from release-mutex nil))
507         ((:warn)
508          (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
509         ((:force))))
510     #!+sb-thread
511     (when old-owner
512       (setf (mutex-%owner mutex) nil)
513       #!+sb-lutex
514       (with-lutex-address (lutex (mutex-lutex mutex))
515         (%lutex-unlock lutex))
516       #!-sb-lutex
517       ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
518       ;; unsigned-byte type this can be used:
519       ;;
520       ;;     (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
521       ;;       (unless (eql old +lock-free+)
522       ;;         (setf (mutex-state mutex) +lock-free+)
523       ;;         (with-pinned-objects (mutex)
524       ;;           (futex-wake (mutex-state-address mutex) 1))))
525       (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
526                                           +lock-taken+ +lock-free+)))
527         (when (eql old +lock-contested+)
528           (sb!ext:compare-and-swap (mutex-state mutex)
529                                    +lock-contested+ +lock-free+)
530           (with-pinned-objects (mutex)
531             (futex-wake (mutex-state-address mutex) 1))))
532       nil)))
533 \f
534
535 ;;;; Waitqueues/condition variables
536
537 (defstruct (waitqueue (:constructor %make-waitqueue))
538   #!+sb-doc
539   "Waitqueue type."
540   (name nil :type (or null thread-name))
541   #!+(and sb-lutex sb-thread)
542   (lutex (make-lutex))
543   #!-sb-lutex
544   (token nil))
545
546 (defun make-waitqueue (&key name)
547   #!+sb-doc
548   "Create a waitqueue."
549   (%make-waitqueue :name name))
550
551 #!+sb-doc
552 (setf (fdocumentation 'waitqueue-name 'function)
553       "The name of the waitqueue. Setfable.")
554
555 #!+(and sb-thread (not sb-lutex))
556 (define-structure-slot-addressor waitqueue-token-address
557     :structure waitqueue
558     :slot token)
559
560 (defun condition-wait (queue mutex)
561   #!+sb-doc
562   "Atomically release MUTEX and enqueue ourselves on QUEUE. Another thread may
563 subsequently notify us using CONDITION-NOTIFY, at which time we reacquire
564 MUTEX and return to the caller.
565
566 Important: CONDITION-WAIT may return without CONDITION-NOTIFY having occurred.
567 The correct way to write code that uses CONDITION-WAIT is to loop around the
568 call, checking the the associated data:
569
570   (defvar *data* nil)
571   (defvar *queue* (make-waitqueue))
572   (defvar *lock* (make-mutex))
573
574   ;; Consumer
575   (defun pop-data ()
576     (with-mutex (*lock*)
577       (loop until *data*
578             do (condition-wait *queue* *lock*))
579       (pop *data*)))
580
581   ;; Producer
582   (defun push-data (data)
583     (with-mutex (*lock*)
584       (push data *data*)
585       (condition-notify *queue*)))
586
587 Also note that if CONDITION-WAIT unwinds (due to eg. a timeout) instead of
588 returning normally, it may do so without holding the mutex."
589   #!-sb-thread (declare (ignore queue))
590   (assert mutex)
591   #!-sb-thread (error "Not supported in unithread builds.")
592   #!+sb-thread
593   (let ((me *current-thread*))
594     (barrier (:read))
595     (assert (eq me (mutex-%owner mutex)))
596     (/show0 "CONDITION-WAITing")
597     #!+sb-lutex
598     ;; Need to disable interrupts so that we don't miss setting the
599     ;; owner on our way out. (pthread_cond_wait handles the actual
600     ;; re-acquisition.)
601     (without-interrupts
602       (unwind-protect
603            (progn
604              (setf (mutex-%owner mutex) nil)
605              (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
606                (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
607                  (with-local-interrupts
608                    (%lutex-wait queue-lutex-address mutex-lutex-address)))))
609         (barrier (:write)
610           (setf (mutex-%owner mutex) me))))
611     #!-sb-lutex
612     ;; Need to disable interrupts so that we don't miss grabbing the
613     ;; mutex on our way out.
614     (without-interrupts
615       ;; This setf becomes visible to other CPUS due to the usual
616       ;; memory barrier semantics of lock acquire/release. This must
617       ;; not be moved into the loop else wakeups may be lost upon
618       ;; continuing after a deadline or EINTR.
619       (setf (waitqueue-token queue) me)
620       (loop
621         (multiple-value-bind (to-sec to-usec)
622             (allow-with-interrupts (decode-timeout nil))
623           (case (unwind-protect
624                      (with-pinned-objects (queue me)
625                        ;; RELEASE-MUTEX is purposefully as close to
626                        ;; FUTEX-WAIT as possible to reduce the size of
627                        ;; the window where the token may be set by a
628                        ;; notifier.
629                        (release-mutex mutex)
630                        ;; Now we go to sleep using futex-wait. If
631                        ;; anyone else manages to grab MUTEX and call
632                        ;; CONDITION-NOTIFY during this comment, it
633                        ;; will change the token, and so futex-wait
634                        ;; returns immediately instead of sleeping.
635                        ;; Ergo, no lost wakeup. We may get spurious
636                        ;; wakeups, but that's ok.
637                        (allow-with-interrupts
638                          (futex-wait (waitqueue-token-address queue)
639                                      (get-lisp-obj-address me)
640                                      ;; our way of saying "no
641                                      ;; timeout":
642                                      (or to-sec -1)
643                                      (or to-usec 0))))
644                   ;; If we are interrupted while waiting, we should
645                   ;; do these things before returning. Ideally, in
646                   ;; the case of an unhandled signal, we should do
647                   ;; them before entering the debugger, but this is
648                   ;; better than nothing.
649                   (allow-with-interrupts (get-mutex mutex)))
650             ;; ETIMEDOUT; we know it was a timeout, yet we cannot
651             ;; signal a deadline unconditionally here because the
652             ;; call to GET-MUTEX may already have signaled it.
653             ((1))
654             ;; EINTR; we do not need to return to the caller because
655             ;; an interleaved wakeup would change the token causing an
656             ;; EWOULDBLOCK in the next iteration.
657             ((2))
658             ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
659             ;; case. 0 is the normal wakeup.
660             (otherwise (return))))))))
661
662 (defun condition-notify (queue &optional (n 1))
663   #!+sb-doc
664   "Notify N threads waiting on QUEUE. The same mutex that is used in
665 the corresponding CONDITION-WAIT must be held by this thread during
666 this call."
667   #!-sb-thread (declare (ignore queue n))
668   #!-sb-thread (error "Not supported in unithread builds.")
669   #!+sb-thread
670   (declare (type (and fixnum (integer 1)) n))
671   (/show0 "Entering CONDITION-NOTIFY")
672   #!+sb-thread
673   (progn
674     #!+sb-lutex
675     (with-lutex-address (lutex (waitqueue-lutex queue))
676       (%lutex-wake lutex n))
677     ;; No problem if >1 thread notifies during the comment in condition-wait:
678     ;; as long as the value in queue-data isn't the waiting thread's id, it
679     ;; matters not what it is -- using the queue object itself is handy.
680     ;;
681     ;; XXX we should do something to ensure that the result of this setf
682     ;; is visible to all CPUs.
683     ;;
684     ;; ^-- surely futex_wake() involves a memory barrier?
685     #!-sb-lutex
686     (progn
687       (setf (waitqueue-token queue) queue)
688       (with-pinned-objects (queue)
689         (futex-wake (waitqueue-token-address queue) n)))))
690
691 (defun condition-broadcast (queue)
692   #!+sb-doc
693   "Notify all threads waiting on QUEUE."
694   (condition-notify queue
695                     ;; On a 64-bit platform truncating M-P-F to an int
696                     ;; results in -1, which wakes up only one thread.
697                     (ldb (byte 29 0)
698                          most-positive-fixnum)))
699 \f
700
701 ;;;; Semaphores
702
703 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
704   #!+sb-doc
705   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
706 should be considered an implementation detail, and may change in the
707 future."
708   (name    nil :type (or null thread-name))
709   (%count    0 :type (integer 0))
710   (waitcount 0 :type sb!vm:word)
711   (mutex (make-mutex))
712   (queue (make-waitqueue)))
713
714 (setf (fdocumentation 'semaphore-name 'function)
715       "The name of the semaphore INSTANCE. Setfable.")
716
717 (declaim (inline semaphore-count))
718 (defun semaphore-count (instance)
719   "Returns the current count of the semaphore INSTANCE."
720   (semaphore-%count instance))
721
722 (defun make-semaphore (&key name (count 0))
723   #!+sb-doc
724   "Create a semaphore with the supplied COUNT and NAME."
725   (%make-semaphore name count))
726
727 (defun wait-on-semaphore (semaphore)
728   #!+sb-doc
729   "Decrement the count of SEMAPHORE if the count would not be
730 negative. Else blocks until the semaphore can be decremented."
731   ;; A more direct implementation based directly on futexes should be
732   ;; possible.
733   ;;
734   ;; We need to disable interrupts so that we don't forget to
735   ;; decrement the waitcount (which would happen if an asynch
736   ;; interrupt should catch us on our way out from the loop.)
737   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
738     ;; Quick check: is it positive? If not, enter the wait loop.
739     (let ((count (semaphore-%count semaphore)))
740       (if (plusp count)
741           (setf (semaphore-%count semaphore) (1- count))
742           (unwind-protect
743                (progn
744                  ;; Need to use ATOMIC-INCF despite the lock, because on our
745                  ;; way out from here we might not be locked anymore -- so
746                  ;; another thread might be tweaking this in parallel using
747                  ;; ATOMIC-DECF. No danger over overflow, since there it
748                  ;; at most one increment per thread waiting on the semaphore.
749                  (sb!ext:atomic-incf (semaphore-waitcount semaphore))
750                  (loop until (plusp (setf count (semaphore-%count semaphore)))
751                        do (condition-wait (semaphore-queue semaphore)
752                                           (semaphore-mutex semaphore)))
753                  (setf (semaphore-%count semaphore) (1- count)))
754             ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
755             ;; may unwind without the lock being held due to timeouts.
756             (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
757
758 (defun try-semaphore (semaphore &optional (n 1))
759   #!+sb-doc
760   "Try to decrement the count of SEMAPHORE by N. If the count were to
761 become negative, punt and return NIL, otherwise return true."
762   (declare (type (integer 1) n))
763   (with-mutex ((semaphore-mutex semaphore))
764     (let ((new-count (- (semaphore-%count semaphore) n)))
765       (when (not (minusp new-count))
766         (setf (semaphore-%count semaphore) new-count)))))
767
768 (defun signal-semaphore (semaphore &optional (n 1))
769   #!+sb-doc
770   "Increment the count of SEMAPHORE by N. If there are threads waiting
771 on this semaphore, then N of them is woken up."
772   (declare (type (integer 1) n))
773   ;; Need to disable interrupts so that we don't lose a wakeup after
774   ;; we have incremented the count.
775   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
776     (let ((waitcount (semaphore-waitcount semaphore))
777           (count (incf (semaphore-%count semaphore) n)))
778       (when (plusp waitcount)
779         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
780 \f
781
782 ;;;; Job control, independent listeners
783
784 (defstruct session
785   (lock (make-mutex :name "session lock"))
786   (threads nil)
787   (interactive-threads nil)
788   (interactive-threads-queue (make-waitqueue)))
789
790 (defvar *session* nil)
791
792 ;;; The debugger itself tries to acquire the session lock, don't let
793 ;;; funny situations (like getting a sigint while holding the session
794 ;;; lock) occur. At the same time we need to allow interrupts while
795 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
796 ;;; be interruptible.
797 ;;;
798 ;;; Take care: we sometimes need to obtain the session lock while
799 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
800 ;;; _after_ getting a session lock! (Deadlock risk.)
801 ;;;
802 ;;; FIXME: It would be good to have ordered locks to ensure invariants
803 ;;; like the above.
804 (defmacro with-session-lock ((session) &body body)
805   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
806      ,@body))
807
808 (defun new-session ()
809   (make-session :threads (list *current-thread*)
810                 :interactive-threads (list *current-thread*)))
811
812 (defun init-job-control ()
813   (/show0 "Entering INIT-JOB-CONTROL")
814   (setf *session* (new-session))
815   (/show0 "Exiting INIT-JOB-CONTROL"))
816
817 (defun %delete-thread-from-session (thread session)
818   (with-session-lock (session)
819     (setf (session-threads session)
820           (delete thread (session-threads session))
821           (session-interactive-threads session)
822           (delete thread (session-interactive-threads session)))))
823
824 (defun call-with-new-session (fn)
825   (%delete-thread-from-session *current-thread* *session*)
826   (let ((*session* (new-session)))
827     (funcall fn)))
828
829 (defmacro with-new-session (args &body forms)
830   (declare (ignore args))               ;for extensibility
831   (sb!int:with-unique-names (fb-name)
832     `(labels ((,fb-name () ,@forms))
833       (call-with-new-session (function ,fb-name)))))
834
835 ;;; Remove thread from its session, if it has one.
836 #!+sb-thread
837 (defun handle-thread-exit (thread)
838   (/show0 "HANDLING THREAD EXIT")
839   ;; Lisp-side cleanup
840   (with-all-threads-lock
841     (setf (thread-%alive-p thread) nil)
842     (setf (thread-os-thread thread) nil)
843     (setq *all-threads* (delete thread *all-threads*))
844     (when *session*
845       (%delete-thread-from-session thread *session*)))
846   #!+sb-lutex
847   (without-gcing
848     (/show0 "FREEING MUTEX LUTEX")
849     (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
850       (%lutex-destroy lutex))))
851
852 (defun terminate-session ()
853   #!+sb-doc
854   "Kill all threads in session except for this one.  Does nothing if current
855 thread is not the foreground thread."
856   ;; FIXME: threads created in other threads may escape termination
857   (let ((to-kill
858          (with-session-lock (*session*)
859            (and (eq *current-thread*
860                     (car (session-interactive-threads *session*)))
861                 (session-threads *session*)))))
862     ;; do the kill after dropping the mutex; unwind forms in dying
863     ;; threads may want to do session things
864     (dolist (thread to-kill)
865       (unless (eq thread *current-thread*)
866         ;; terminate the thread but don't be surprised if it has
867         ;; exited in the meantime
868         (handler-case (terminate-thread thread)
869           (interrupt-thread-error ()))))))
870
871 ;;; called from top of invoke-debugger
872 (defun debugger-wait-until-foreground-thread (stream)
873   "Returns T if thread had been running in background, NIL if it was
874 interactive."
875   (declare (ignore stream))
876   #!-sb-thread nil
877   #!+sb-thread
878   (prog1
879       (with-session-lock (*session*)
880         (not (member *current-thread*
881                      (session-interactive-threads *session*))))
882     (get-foreground)))
883
884 (defun get-foreground ()
885   #!-sb-thread t
886   #!+sb-thread
887   (let ((was-foreground t))
888     (loop
889      (/show0 "Looping in GET-FOREGROUND")
890      (with-session-lock (*session*)
891        (let ((int-t (session-interactive-threads *session*)))
892          (when (eq (car int-t) *current-thread*)
893            (unless was-foreground
894              (format *query-io* "Resuming thread ~A~%" *current-thread*))
895            (return-from get-foreground t))
896          (setf was-foreground nil)
897          (unless (member *current-thread* int-t)
898            (setf (cdr (last int-t))
899                  (list *current-thread*)))
900          (condition-wait
901           (session-interactive-threads-queue *session*)
902           (session-lock *session*)))))))
903
904 (defun release-foreground (&optional next)
905   #!+sb-doc
906   "Background this thread.  If NEXT is supplied, arrange for it to
907 have the foreground next."
908   #!-sb-thread (declare (ignore next))
909   #!-sb-thread nil
910   #!+sb-thread
911   (with-session-lock (*session*)
912     (when (rest (session-interactive-threads *session*))
913       (setf (session-interactive-threads *session*)
914             (delete *current-thread* (session-interactive-threads *session*))))
915     (when next
916       (setf (session-interactive-threads *session*)
917             (list* next
918                    (delete next (session-interactive-threads *session*)))))
919     (condition-broadcast (session-interactive-threads-queue *session*))))
920
921 (defun foreground-thread ()
922   (car (session-interactive-threads *session*)))
923
924 (defun make-listener-thread (tty-name)
925   (assert (probe-file tty-name))
926   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
927          (out (sb!unix:unix-dup in))
928          (err (sb!unix:unix-dup in)))
929     (labels ((thread-repl ()
930                (sb!unix::unix-setsid)
931                (let* ((sb!impl::*stdin*
932                        (make-fd-stream in :input t :buffering :line
933                                        :dual-channel-p t))
934                       (sb!impl::*stdout*
935                        (make-fd-stream out :output t :buffering :line
936                                               :dual-channel-p t))
937                       (sb!impl::*stderr*
938                        (make-fd-stream err :output t :buffering :line
939                                               :dual-channel-p t))
940                       (sb!impl::*tty*
941                        (make-fd-stream err :input t :output t
942                                               :buffering :line
943                                               :dual-channel-p t))
944                       (sb!impl::*descriptor-handlers* nil))
945                  (with-new-session ()
946                    (unwind-protect
947                         (sb!impl::toplevel-repl nil)
948                      (sb!int:flush-standard-output-streams))))))
949       (make-thread #'thread-repl))))
950 \f
951
952 ;;;; The beef
953
954 (defun make-thread (function &key name)
955   #!+sb-doc
956   "Create a new thread of NAME that runs FUNCTION. When the function
957 returns the thread exits. The return values of FUNCTION are kept
958 around and can be retrieved by JOIN-THREAD."
959   #!-sb-thread (declare (ignore function name))
960   #!-sb-thread (error "Not supported in unithread builds.")
961   #!+sb-thread
962   (let* ((thread (%make-thread :name name))
963          (setup-sem (make-semaphore :name "Thread setup semaphore"))
964          (real-function (coerce function 'function))
965          (initial-function
966           (named-lambda initial-thread-function ()
967             ;; In time we'll move some of the binding presently done in C
968             ;; here too.
969             ;;
970             ;; KLUDGE: Here we have a magic list of variables that are
971             ;; not thread-safe for one reason or another.  As people
972             ;; report problems with the thread safety of certain
973             ;; variables, (e.g. "*print-case* in multiple threads
974             ;; broken", sbcl-devel 2006-07-14), we add a few more
975             ;; bindings here.  The Right Thing is probably some variant
976             ;; of Allegro's *cl-default-special-bindings*, as that is at
977             ;; least accessible to users to secure their own libraries.
978             ;;   --njf, 2006-07-15
979             ;;
980             ;; As it is, this lambda must not cons until we are ready
981             ;; to run GC. Be very careful.
982             (let* ((*current-thread* thread)
983                    (*restart-clusters* nil)
984                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
985                    (*condition-restarts* nil)
986                    (sb!impl::*deadline* nil)
987                    (sb!impl::*deadline-seconds* nil)
988                    (sb!impl::*step-out* nil)
989                    ;; internal printer variables
990                    (sb!impl::*previous-case* nil)
991                    (sb!impl::*previous-readtable-case* nil)
992                    (sb!impl::*internal-symbol-output-fun* nil)
993                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
994               ;; Binding from C
995               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
996               (setf (thread-os-thread thread) (current-thread-os-thread))
997               (with-mutex ((thread-result-lock thread))
998                 (with-all-threads-lock
999                   (push thread *all-threads*))
1000                 (with-session-lock (*session*)
1001                   (push thread (session-threads *session*)))
1002                 (setf (thread-%alive-p thread) t)
1003                 (signal-semaphore setup-sem)
1004                 ;; can't use handling-end-of-the-world, because that flushes
1005                 ;; output streams, and we don't necessarily have any (or we
1006                 ;; could be sharing them)
1007                 (catch 'sb!impl::toplevel-catcher
1008                   (catch 'sb!impl::%end-of-the-world
1009                     (with-simple-restart
1010                         (terminate-thread
1011                          (format nil
1012                                  "~~@<Terminate this thread (~A)~~@:>"
1013                                  *current-thread*))
1014                       (without-interrupts
1015                         (unwind-protect
1016                              (with-local-interrupts
1017                                ;; Now that most things have a chance
1018                                ;; to work properly without messing up
1019                                ;; other threads, it's time to enable
1020                                ;; signals.
1021                                (sb!unix::unblock-deferrable-signals)
1022                                (setf (thread-result thread)
1023                                      (cons t
1024                                            (multiple-value-list
1025                                             (funcall real-function))))
1026                                ;; Try to block deferrables. An
1027                                ;; interrupt may unwind it, but for a
1028                                ;; normal exit it prevents interrupt
1029                                ;; loss.
1030                                (block-deferrable-signals))
1031                           ;; We're going down, can't handle interrupts
1032                           ;; sanely anymore. GC remains enabled.
1033                           (block-deferrable-signals)
1034                           ;; We don't want to run interrupts in a dead
1035                           ;; thread when we leave WITHOUT-INTERRUPTS.
1036                           ;; This potentially causes important
1037                           ;; interupts to be lost: SIGINT comes to
1038                           ;; mind.
1039                           (setq *interrupt-pending* nil)
1040                           (handle-thread-exit thread))))))))
1041             (values))))
1042     ;; If the starting thread is stopped for gc before it signals the
1043     ;; semaphore then we'd be stuck.
1044     (assert (not *gc-inhibit*))
1045     ;; Keep INITIAL-FUNCTION pinned until the child thread is
1046     ;; initialized properly. Wrap the whole thing in
1047     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1048     ;; thread.
1049     (without-interrupts
1050       (with-pinned-objects (initial-function)
1051         (let ((os-thread
1052                (%create-thread
1053                 (get-lisp-obj-address initial-function))))
1054           (when (zerop os-thread)
1055             (error "Can't create a new thread"))
1056           (wait-on-semaphore setup-sem)
1057           thread)))))
1058
1059 (defun join-thread (thread &key (default nil defaultp))
1060   #!+sb-doc
1061   "Suspend current thread until THREAD exits. Returns the result
1062 values of the thread function. If the thread does not exit normally,
1063 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
1064   (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
1065     (cond ((car (thread-result thread))
1066            (return-from join-thread
1067              (values-list (cdr (thread-result thread)))))
1068           (defaultp
1069            (return-from join-thread default))))
1070   (error 'join-thread-error :thread thread))
1071
1072 (defun destroy-thread (thread)
1073   #!+sb-doc
1074   "Deprecated. Same as TERMINATE-THREAD."
1075   (terminate-thread thread))
1076
1077 (defmacro with-interruptions-lock ((thread) &body body)
1078   `(with-system-mutex ((thread-interruptions-lock ,thread))
1079      ,@body))
1080
1081 ;;; Called from the signal handler.
1082 #!-win32
1083 (defun run-interruption ()
1084   (let ((interruption (with-interruptions-lock (*current-thread*)
1085                         (pop (thread-interruptions *current-thread*)))))
1086     ;; If there is more to do, then resignal and let the normal
1087     ;; interrupt deferral mechanism take care of the rest. From the
1088     ;; OS's point of view the signal we are in the handler for is no
1089     ;; longer pending, so the signal will not be lost.
1090     (when (thread-interruptions *current-thread*)
1091       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1092     (when interruption
1093       (funcall interruption))))
1094
1095 (defun interrupt-thread (thread function)
1096   #!+sb-doc
1097   "Interrupt the live THREAD and make it run FUNCTION. A moderate
1098 degree of care is expected for use of INTERRUPT-THREAD, due to its
1099 nature: if you interrupt a thread that was holding important locks
1100 then do something that turns out to need those locks, you probably
1101 won't like the effect. FUNCTION runs with interrupts disabled, but
1102 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1103 enable interrupts (GET-MUTEX when contended, for instance) so the
1104 first thing to do is usually a WITH-INTERRUPTS or a
1105 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1106 run in same the order they were sent."
1107   #!+win32
1108   (declare (ignore thread))
1109   #!+win32
1110   (with-interrupt-bindings
1111     (with-interrupts (funcall function)))
1112   #!-win32
1113   (let ((os-thread (thread-os-thread thread)))
1114     (cond ((not os-thread)
1115            (error 'interrupt-thread-error :thread thread))
1116           (t
1117            (with-interruptions-lock (thread)
1118              ;; Append to the end of the interruptions queue. It's
1119              ;; O(N), but it does not hurt to slow interruptors down a
1120              ;; bit when the queue gets long.
1121              (setf (thread-interruptions thread)
1122                    (append (thread-interruptions thread)
1123                            (list (lambda ()
1124                                    (without-interrupts
1125                                      (allow-with-interrupts
1126                                        (funcall function))))))))
1127            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1128              (error 'interrupt-thread-error :thread thread))))))
1129
1130 (defun terminate-thread (thread)
1131   #!+sb-doc
1132   "Terminate the thread identified by THREAD, by causing it to run
1133 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1134   (interrupt-thread thread 'sb!ext:quit))
1135
1136 (define-alien-routine "thread_yield" int)
1137
1138 #!+sb-doc
1139 (setf (fdocumentation 'thread-yield 'function)
1140       "Yield the processor to other threads.")
1141
1142 ;;; internal use only.  If you think you need to use these, either you
1143 ;;; are an SBCL developer, are doing something that you should discuss
1144 ;;; with an SBCL developer first, or are doing something that you
1145 ;;; should probably discuss with a professional psychiatrist first
1146 #!+sb-thread
1147 (progn
1148   (defun %thread-sap (thread)
1149     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1150           (target (thread-os-thread thread)))
1151       (loop
1152         (when (sap= thread-sap (int-sap 0)) (return nil))
1153         (let ((os-thread (sap-ref-word thread-sap
1154                                        (* sb!vm:n-word-bytes
1155                                           sb!vm::thread-os-thread-slot))))
1156           (when (= os-thread target) (return thread-sap))
1157           (setf thread-sap
1158                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1159                                            sb!vm::thread-next-slot)))))))
1160
1161   (defun %symbol-value-in-thread (symbol thread)
1162     ;; Prevent the thread from dying completely while we look for the TLS
1163     ;; area...
1164     (with-all-threads-lock
1165       (loop
1166         (if (thread-alive-p thread)
1167             (let* ((epoch sb!kernel::*gc-epoch*)
1168                    (offset (* sb!vm:n-word-bytes
1169                               (sb!vm::symbol-tls-index symbol)))
1170                    (tl-val (sap-ref-word (%thread-sap thread) offset)))
1171               (cond ((zerop offset)
1172                      (return (values nil :no-tls-value)))
1173                     ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1174                          (eql tl-val sb!vm:unbound-marker-widetag))
1175                      (return (values nil :unbound-in-thread)))
1176                     (t
1177                      (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1178                        ;; The value we constructed may be invalid if a GC has
1179                        ;; occurred. That is harmless, though, since OBJ is
1180                        ;; either in a register or on stack, and we are
1181                        ;; conservative on both on GENCGC -- so a bogus object
1182                        ;; is safe here as long as we don't return it. If we
1183                        ;; ever port threads to a non-conservative GC we must
1184                        ;; pin the TL-VAL address before constructing OBJ, or
1185                        ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1186                        ;;
1187                        ;; The reason we don't just rely on TL-VAL pinning the
1188                        ;; object is that the call to MAKE-LISP-OBJ may cause
1189                        ;; bignum allocation, at which point TL-VAL might not
1190                        ;; be alive anymore -- hence the epoch check.
1191                        (when (eq epoch sb!kernel::*gc-epoch*)
1192                          (if ok
1193                              (return (values obj :ok))
1194                              (return (values obj :invalid-tls-value))))))))
1195             (return (values nil :thread-dead))))))
1196
1197   (defun %set-symbol-value-in-thread (symbol thread value)
1198     (with-pinned-objects (value)
1199       ;; Prevent the thread from dying completely while we look for the TLS
1200       ;; area...
1201       (with-all-threads-lock
1202         (if (thread-alive-p thread)
1203             (let ((offset (* sb!vm:n-word-bytes
1204                              (sb!vm::symbol-tls-index symbol))))
1205               (cond ((zerop offset)
1206                      (values nil :no-tls-value))
1207                     (t
1208                      (setf (sap-ref-word (%thread-sap thread) offset)
1209                            (get-lisp-obj-address value))
1210                      (values value :ok))))
1211             (values nil :thread-dead))))))
1212
1213 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1214   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1215 on success.
1216
1217 If the value cannot be retrieved (because the thread has exited or because it
1218 has no local binding for NAME) and ERRORP is true signals an error of type
1219 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1220 NIL, and a secondary value of NIL.
1221
1222 Can also be used with SETF to change the thread-local value of SYMBOL.
1223
1224 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1225 mechanism for inter-thread communication."
1226   (declare (symbol symbol) (thread thread))
1227   #!+sb-thread
1228   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1229     (if (eq :ok status)
1230         (values res t)
1231         (if errorp
1232             (error 'symbol-value-in-thread-error
1233                    :name symbol
1234                    :thread thread
1235                    :info (list :read status))
1236             (values nil nil))))
1237   #!-sb-thread
1238   (if (boundp symbol)
1239       (values (symbol-value symbol) t)
1240       (if errorp
1241           (error 'symbol-value-in-thread-error
1242                  :name symbol
1243                  :thread thread
1244                  :info (list :read :unbound-in-thread))
1245           (values nil nil))))
1246
1247 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1248   (declare (symbol symbol) (thread thread))
1249   #!+sb-thread
1250   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1251     (if (eq :ok status)
1252         (values res t)
1253         (if errorp
1254             (error 'symbol-value-in-thread-error
1255                    :name symbol
1256                    :thread thread
1257                    :info (list :write status))
1258             (values nil nil))))
1259   #!-sb-thread
1260   (if (boundp symbol)
1261       (values (setf (symbol-value symbol) value) t)
1262       (if errorp
1263           (error 'symbol-value-in-thread-error
1264                  :name symbol
1265                  :thread thread
1266                  :info (list :write :unbound-in-thread))
1267           (values nil nil))))
1268
1269 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1270   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1271 \f
1272
1273 ;;;; Stepping
1274
1275 (defun thread-stepping ()
1276   (make-lisp-obj
1277    (sap-ref-word (current-thread-sap)
1278                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1279
1280 (defun (setf thread-stepping) (value)
1281   (setf (sap-ref-word (current-thread-sap)
1282                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1283         (get-lisp-obj-address value)))