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