1.0.45.15: make waitqueue printing prettier
[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 (def!method print-object ((waitqueue waitqueue) stream)
531   (print-unreadable-object (waitqueue stream :type t :identity t)
532     (format stream "~@[~A~]" (waitqueue-name waitqueue))))
533
534 (defun make-waitqueue (&key name)
535   #!+sb-doc
536   "Create a waitqueue."
537   (%make-waitqueue :name name))
538
539 #!+sb-doc
540 (setf (fdocumentation 'waitqueue-name 'function)
541       "The name of the waitqueue. Setfable.")
542
543 #!+(and sb-thread (not sb-lutex))
544 (define-structure-slot-addressor waitqueue-token-address
545     :structure waitqueue
546     :slot token)
547
548 (defun condition-wait (queue mutex)
549   #!+sb-doc
550   "Atomically release MUTEX and enqueue ourselves on QUEUE. Another thread may
551 subsequently notify us using CONDITION-NOTIFY, at which time we reacquire
552 MUTEX and return to the caller.
553
554 Important: CONDITION-WAIT may return without CONDITION-NOTIFY having occurred.
555 The correct way to write code that uses CONDITION-WAIT is to loop around the
556 call, checking the the associated data:
557
558   (defvar *data* nil)
559   (defvar *queue* (make-waitqueue))
560   (defvar *lock* (make-mutex))
561
562   ;; Consumer
563   (defun pop-data ()
564     (with-mutex (*lock*)
565       (loop until *data*
566             do (condition-wait *queue* *lock*))
567       (pop *data*)))
568
569   ;; Producer
570   (defun push-data (data)
571     (with-mutex (*lock*)
572       (push data *data*)
573       (condition-notify *queue*)))
574
575 Also note that if CONDITION-WAIT unwinds (due to eg. a timeout) instead of
576 returning normally, it may do so without holding the mutex."
577   #!-sb-thread (declare (ignore queue))
578   (assert mutex)
579   #!-sb-thread (error "Not supported in unithread builds.")
580   #!+sb-thread
581   (let ((me *current-thread*))
582     (barrier (:read))
583     (assert (eq me (mutex-%owner mutex)))
584     (/show0 "CONDITION-WAITing")
585     #!+sb-lutex
586     ;; Need to disable interrupts so that we don't miss setting the
587     ;; owner on our way out. (pthread_cond_wait handles the actual
588     ;; re-acquisition.)
589     (without-interrupts
590       (unwind-protect
591            (progn
592              (setf (mutex-%owner mutex) nil)
593              (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
594                (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
595                  (with-local-interrupts
596                    (%lutex-wait queue-lutex-address mutex-lutex-address)))))
597         (barrier (:write)
598           (setf (mutex-%owner mutex) me))))
599     #!-sb-lutex
600     ;; Need to disable interrupts so that we don't miss grabbing the
601     ;; mutex on our way out.
602     (without-interrupts
603       ;; This setf becomes visible to other CPUS due to the usual
604       ;; memory barrier semantics of lock acquire/release. This must
605       ;; not be moved into the loop else wakeups may be lost upon
606       ;; continuing after a deadline or EINTR.
607       (setf (waitqueue-token queue) me)
608       (loop
609         (multiple-value-bind (to-sec to-usec)
610             (allow-with-interrupts (decode-timeout nil))
611           (case (unwind-protect
612                      (with-pinned-objects (queue me)
613                        ;; RELEASE-MUTEX is purposefully as close to
614                        ;; FUTEX-WAIT as possible to reduce the size of
615                        ;; the window where the token may be set by a
616                        ;; notifier.
617                        (release-mutex mutex)
618                        ;; Now we go to sleep using futex-wait. If
619                        ;; anyone else manages to grab MUTEX and call
620                        ;; CONDITION-NOTIFY during this comment, it
621                        ;; will change the token, and so futex-wait
622                        ;; returns immediately instead of sleeping.
623                        ;; Ergo, no lost wakeup. We may get spurious
624                        ;; wakeups, but that's ok.
625                        (allow-with-interrupts
626                          (futex-wait (waitqueue-token-address queue)
627                                      (get-lisp-obj-address me)
628                                      ;; our way of saying "no
629                                      ;; timeout":
630                                      (or to-sec -1)
631                                      (or to-usec 0))))
632                   ;; If we are interrupted while waiting, we should
633                   ;; do these things before returning. Ideally, in
634                   ;; the case of an unhandled signal, we should do
635                   ;; them before entering the debugger, but this is
636                   ;; better than nothing.
637                   (allow-with-interrupts (get-mutex mutex)))
638             ;; ETIMEDOUT; we know it was a timeout, yet we cannot
639             ;; signal a deadline unconditionally here because the
640             ;; call to GET-MUTEX may already have signaled it.
641             ((1))
642             ;; EINTR; we do not need to return to the caller because
643             ;; an interleaved wakeup would change the token causing an
644             ;; EWOULDBLOCK in the next iteration.
645             ((2))
646             ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
647             ;; case. 0 is the normal wakeup.
648             (otherwise (return))))))))
649
650 (defun condition-notify (queue &optional (n 1))
651   #!+sb-doc
652   "Notify N threads waiting on QUEUE. The same mutex that is used in
653 the corresponding CONDITION-WAIT must be held by this thread during
654 this call."
655   #!-sb-thread (declare (ignore queue n))
656   #!-sb-thread (error "Not supported in unithread builds.")
657   #!+sb-thread
658   (declare (type (and fixnum (integer 1)) n))
659   (/show0 "Entering CONDITION-NOTIFY")
660   #!+sb-thread
661   (progn
662     #!+sb-lutex
663     (with-lutex-address (lutex (waitqueue-lutex queue))
664       (%lutex-wake lutex n))
665     ;; No problem if >1 thread notifies during the comment in condition-wait:
666     ;; as long as the value in queue-data isn't the waiting thread's id, it
667     ;; matters not what it is -- using the queue object itself is handy.
668     ;;
669     ;; XXX we should do something to ensure that the result of this setf
670     ;; is visible to all CPUs.
671     ;;
672     ;; ^-- surely futex_wake() involves a memory barrier?
673     #!-sb-lutex
674     (progn
675       (setf (waitqueue-token queue) queue)
676       (with-pinned-objects (queue)
677         (futex-wake (waitqueue-token-address queue) n)))))
678
679 (defun condition-broadcast (queue)
680   #!+sb-doc
681   "Notify all threads waiting on QUEUE."
682   (condition-notify queue
683                     ;; On a 64-bit platform truncating M-P-F to an int
684                     ;; results in -1, which wakes up only one thread.
685                     (ldb (byte 29 0)
686                          most-positive-fixnum)))
687 \f
688
689 ;;;; Semaphores
690
691 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
692   #!+sb-doc
693   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
694 should be considered an implementation detail, and may change in the
695 future."
696   (name    nil :type (or null thread-name))
697   (%count    0 :type (integer 0))
698   (waitcount 0 :type sb!vm:word)
699   (mutex (make-mutex))
700   (queue (make-waitqueue)))
701
702 (setf (fdocumentation 'semaphore-name 'function)
703       "The name of the semaphore INSTANCE. Setfable.")
704
705 (declaim (inline semaphore-count))
706 (defun semaphore-count (instance)
707   "Returns the current count of the semaphore INSTANCE."
708   (semaphore-%count instance))
709
710 (defun make-semaphore (&key name (count 0))
711   #!+sb-doc
712   "Create a semaphore with the supplied COUNT and NAME."
713   (%make-semaphore name count))
714
715 (defun wait-on-semaphore (semaphore)
716   #!+sb-doc
717   "Decrement the count of SEMAPHORE if the count would not be
718 negative. Else blocks until the semaphore can be decremented."
719   ;; A more direct implementation based directly on futexes should be
720   ;; possible.
721   ;;
722   ;; We need to disable interrupts so that we don't forget to
723   ;; decrement the waitcount (which would happen if an asynch
724   ;; interrupt should catch us on our way out from the loop.)
725   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
726     ;; Quick check: is it positive? If not, enter the wait loop.
727     (let ((count (semaphore-%count semaphore)))
728       (if (plusp count)
729           (setf (semaphore-%count semaphore) (1- count))
730           (unwind-protect
731                (progn
732                  ;; Need to use ATOMIC-INCF despite the lock, because on our
733                  ;; way out from here we might not be locked anymore -- so
734                  ;; another thread might be tweaking this in parallel using
735                  ;; ATOMIC-DECF. No danger over overflow, since there it
736                  ;; at most one increment per thread waiting on the semaphore.
737                  (sb!ext:atomic-incf (semaphore-waitcount semaphore))
738                  (loop until (plusp (setf count (semaphore-%count semaphore)))
739                        do (condition-wait (semaphore-queue semaphore)
740                                           (semaphore-mutex semaphore)))
741                  (setf (semaphore-%count semaphore) (1- count)))
742             ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
743             ;; may unwind without the lock being held due to timeouts.
744             (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
745
746 (defun try-semaphore (semaphore &optional (n 1))
747   #!+sb-doc
748   "Try to decrement the count of SEMAPHORE by N. If the count were to
749 become negative, punt and return NIL, otherwise return true."
750   (declare (type (integer 1) n))
751   (with-mutex ((semaphore-mutex semaphore))
752     (let ((new-count (- (semaphore-%count semaphore) n)))
753       (when (not (minusp new-count))
754         (setf (semaphore-%count semaphore) new-count)))))
755
756 (defun signal-semaphore (semaphore &optional (n 1))
757   #!+sb-doc
758   "Increment the count of SEMAPHORE by N. If there are threads waiting
759 on this semaphore, then N of them is woken up."
760   (declare (type (integer 1) n))
761   ;; Need to disable interrupts so that we don't lose a wakeup after
762   ;; we have incremented the count.
763   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
764     (let ((waitcount (semaphore-waitcount semaphore))
765           (count (incf (semaphore-%count semaphore) n)))
766       (when (plusp waitcount)
767         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
768 \f
769
770 ;;;; Job control, independent listeners
771
772 (defstruct session
773   (lock (make-mutex :name "session lock"))
774   (threads nil)
775   (interactive-threads nil)
776   (interactive-threads-queue (make-waitqueue)))
777
778 (defvar *session* nil)
779
780 ;;; The debugger itself tries to acquire the session lock, don't let
781 ;;; funny situations (like getting a sigint while holding the session
782 ;;; lock) occur. At the same time we need to allow interrupts while
783 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
784 ;;; be interruptible.
785 ;;;
786 ;;; Take care: we sometimes need to obtain the session lock while
787 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
788 ;;; _after_ getting a session lock! (Deadlock risk.)
789 ;;;
790 ;;; FIXME: It would be good to have ordered locks to ensure invariants
791 ;;; like the above.
792 (defmacro with-session-lock ((session) &body body)
793   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
794      ,@body))
795
796 (defun new-session ()
797   (make-session :threads (list *current-thread*)
798                 :interactive-threads (list *current-thread*)))
799
800 (defun init-job-control ()
801   (/show0 "Entering INIT-JOB-CONTROL")
802   (setf *session* (new-session))
803   (/show0 "Exiting INIT-JOB-CONTROL"))
804
805 (defun %delete-thread-from-session (thread session)
806   (with-session-lock (session)
807     (setf (session-threads session)
808           (delete thread (session-threads session))
809           (session-interactive-threads session)
810           (delete thread (session-interactive-threads session)))))
811
812 (defun call-with-new-session (fn)
813   (%delete-thread-from-session *current-thread* *session*)
814   (let ((*session* (new-session)))
815     (funcall fn)))
816
817 (defmacro with-new-session (args &body forms)
818   (declare (ignore args))               ;for extensibility
819   (sb!int:with-unique-names (fb-name)
820     `(labels ((,fb-name () ,@forms))
821       (call-with-new-session (function ,fb-name)))))
822
823 ;;; Remove thread from its session, if it has one.
824 #!+sb-thread
825 (defun handle-thread-exit (thread)
826   (/show0 "HANDLING THREAD EXIT")
827   ;; Lisp-side cleanup
828   (with-all-threads-lock
829     (setf (thread-%alive-p thread) nil)
830     (setf (thread-os-thread thread) nil)
831     (setq *all-threads* (delete thread *all-threads*))
832     (when *session*
833       (%delete-thread-from-session thread *session*)))
834   #!+sb-lutex
835   (without-gcing
836     (/show0 "FREEING MUTEX LUTEX")
837     (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
838       (%lutex-destroy lutex))))
839
840 (defun terminate-session ()
841   #!+sb-doc
842   "Kill all threads in session except for this one.  Does nothing if current
843 thread is not the foreground thread."
844   ;; FIXME: threads created in other threads may escape termination
845   (let ((to-kill
846          (with-session-lock (*session*)
847            (and (eq *current-thread*
848                     (car (session-interactive-threads *session*)))
849                 (session-threads *session*)))))
850     ;; do the kill after dropping the mutex; unwind forms in dying
851     ;; threads may want to do session things
852     (dolist (thread to-kill)
853       (unless (eq thread *current-thread*)
854         ;; terminate the thread but don't be surprised if it has
855         ;; exited in the meantime
856         (handler-case (terminate-thread thread)
857           (interrupt-thread-error ()))))))
858
859 ;;; called from top of invoke-debugger
860 (defun debugger-wait-until-foreground-thread (stream)
861   "Returns T if thread had been running in background, NIL if it was
862 interactive."
863   (declare (ignore stream))
864   #!-sb-thread nil
865   #!+sb-thread
866   (prog1
867       (with-session-lock (*session*)
868         (not (member *current-thread*
869                      (session-interactive-threads *session*))))
870     (get-foreground)))
871
872 (defun get-foreground ()
873   #!-sb-thread t
874   #!+sb-thread
875   (let ((was-foreground t))
876     (loop
877      (/show0 "Looping in GET-FOREGROUND")
878      (with-session-lock (*session*)
879        (let ((int-t (session-interactive-threads *session*)))
880          (when (eq (car int-t) *current-thread*)
881            (unless was-foreground
882              (format *query-io* "Resuming thread ~A~%" *current-thread*))
883            (return-from get-foreground t))
884          (setf was-foreground nil)
885          (unless (member *current-thread* int-t)
886            (setf (cdr (last int-t))
887                  (list *current-thread*)))
888          (condition-wait
889           (session-interactive-threads-queue *session*)
890           (session-lock *session*)))))))
891
892 (defun release-foreground (&optional next)
893   #!+sb-doc
894   "Background this thread.  If NEXT is supplied, arrange for it to
895 have the foreground next."
896   #!-sb-thread (declare (ignore next))
897   #!-sb-thread nil
898   #!+sb-thread
899   (with-session-lock (*session*)
900     (when (rest (session-interactive-threads *session*))
901       (setf (session-interactive-threads *session*)
902             (delete *current-thread* (session-interactive-threads *session*))))
903     (when next
904       (setf (session-interactive-threads *session*)
905             (list* next
906                    (delete next (session-interactive-threads *session*)))))
907     (condition-broadcast (session-interactive-threads-queue *session*))))
908
909 (defun foreground-thread ()
910   (car (session-interactive-threads *session*)))
911
912 (defun make-listener-thread (tty-name)
913   (assert (probe-file tty-name))
914   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
915          (out (sb!unix:unix-dup in))
916          (err (sb!unix:unix-dup in)))
917     (labels ((thread-repl ()
918                (sb!unix::unix-setsid)
919                (let* ((sb!impl::*stdin*
920                        (make-fd-stream in :input t :buffering :line
921                                        :dual-channel-p t))
922                       (sb!impl::*stdout*
923                        (make-fd-stream out :output t :buffering :line
924                                               :dual-channel-p t))
925                       (sb!impl::*stderr*
926                        (make-fd-stream err :output t :buffering :line
927                                               :dual-channel-p t))
928                       (sb!impl::*tty*
929                        (make-fd-stream err :input t :output t
930                                               :buffering :line
931                                               :dual-channel-p t))
932                       (sb!impl::*descriptor-handlers* nil))
933                  (with-new-session ()
934                    (unwind-protect
935                         (sb!impl::toplevel-repl nil)
936                      (sb!int:flush-standard-output-streams))))))
937       (make-thread #'thread-repl))))
938 \f
939
940 ;;;; The beef
941
942 (defun make-thread (function &key name)
943   #!+sb-doc
944   "Create a new thread of NAME that runs FUNCTION. When the function
945 returns the thread exits. The return values of FUNCTION are kept
946 around and can be retrieved by JOIN-THREAD."
947   #!-sb-thread (declare (ignore function name))
948   #!-sb-thread (error "Not supported in unithread builds.")
949   #!+sb-thread
950   (let* ((thread (%make-thread :name name))
951          (setup-sem (make-semaphore :name "Thread setup semaphore"))
952          (real-function (coerce function 'function))
953          (initial-function
954           (named-lambda initial-thread-function ()
955             ;; In time we'll move some of the binding presently done in C
956             ;; here too.
957             ;;
958             ;; KLUDGE: Here we have a magic list of variables that are
959             ;; not thread-safe for one reason or another.  As people
960             ;; report problems with the thread safety of certain
961             ;; variables, (e.g. "*print-case* in multiple threads
962             ;; broken", sbcl-devel 2006-07-14), we add a few more
963             ;; bindings here.  The Right Thing is probably some variant
964             ;; of Allegro's *cl-default-special-bindings*, as that is at
965             ;; least accessible to users to secure their own libraries.
966             ;;   --njf, 2006-07-15
967             ;;
968             ;; As it is, this lambda must not cons until we are ready
969             ;; to run GC. Be very careful.
970             (let* ((*current-thread* thread)
971                    (*restart-clusters* nil)
972                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
973                    (*condition-restarts* nil)
974                    (sb!impl::*deadline* nil)
975                    (sb!impl::*deadline-seconds* nil)
976                    (sb!impl::*step-out* nil)
977                    ;; internal printer variables
978                    (sb!impl::*previous-case* nil)
979                    (sb!impl::*previous-readtable-case* nil)
980                    (sb!impl::*internal-symbol-output-fun* nil)
981                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
982               ;; Binding from C
983               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
984               (setf (thread-os-thread thread) (current-thread-os-thread))
985               (with-mutex ((thread-result-lock thread))
986                 (with-all-threads-lock
987                   (push thread *all-threads*))
988                 (with-session-lock (*session*)
989                   (push thread (session-threads *session*)))
990                 (setf (thread-%alive-p thread) t)
991                 (signal-semaphore setup-sem)
992                 ;; can't use handling-end-of-the-world, because that flushes
993                 ;; output streams, and we don't necessarily have any (or we
994                 ;; could be sharing them)
995                 (catch 'sb!impl::toplevel-catcher
996                   (catch 'sb!impl::%end-of-the-world
997                     (with-simple-restart
998                         (terminate-thread
999                          (format nil
1000                                  "~~@<Terminate this thread (~A)~~@:>"
1001                                  *current-thread*))
1002                       (without-interrupts
1003                         (unwind-protect
1004                              (with-local-interrupts
1005                                ;; Now that most things have a chance
1006                                ;; to work properly without messing up
1007                                ;; other threads, it's time to enable
1008                                ;; signals.
1009                                (sb!unix::unblock-deferrable-signals)
1010                                (setf (thread-result thread)
1011                                      (cons t
1012                                            (multiple-value-list
1013                                             (funcall real-function))))
1014                                ;; Try to block deferrables. An
1015                                ;; interrupt may unwind it, but for a
1016                                ;; normal exit it prevents interrupt
1017                                ;; loss.
1018                                (block-deferrable-signals))
1019                           ;; We're going down, can't handle interrupts
1020                           ;; sanely anymore. GC remains enabled.
1021                           (block-deferrable-signals)
1022                           ;; We don't want to run interrupts in a dead
1023                           ;; thread when we leave WITHOUT-INTERRUPTS.
1024                           ;; This potentially causes important
1025                           ;; interupts to be lost: SIGINT comes to
1026                           ;; mind.
1027                           (setq *interrupt-pending* nil)
1028                           (handle-thread-exit thread))))))))
1029             (values))))
1030     ;; If the starting thread is stopped for gc before it signals the
1031     ;; semaphore then we'd be stuck.
1032     (assert (not *gc-inhibit*))
1033     ;; Keep INITIAL-FUNCTION pinned until the child thread is
1034     ;; initialized properly. Wrap the whole thing in
1035     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1036     ;; thread.
1037     (without-interrupts
1038       (with-pinned-objects (initial-function)
1039         (let ((os-thread
1040                (%create-thread
1041                 (get-lisp-obj-address initial-function))))
1042           (when (zerop os-thread)
1043             (error "Can't create a new thread"))
1044           (wait-on-semaphore setup-sem)
1045           thread)))))
1046
1047 (defun join-thread (thread &key (default nil defaultp))
1048   #!+sb-doc
1049   "Suspend current thread until THREAD exits. Returns the result
1050 values of the thread function. If the thread does not exit normally,
1051 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
1052   (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
1053     (cond ((car (thread-result thread))
1054            (return-from join-thread
1055              (values-list (cdr (thread-result thread)))))
1056           (defaultp
1057            (return-from join-thread default))))
1058   (error 'join-thread-error :thread thread))
1059
1060 (defun destroy-thread (thread)
1061   #!+sb-doc
1062   "Deprecated. Same as TERMINATE-THREAD."
1063   (terminate-thread thread))
1064
1065 (defmacro with-interruptions-lock ((thread) &body body)
1066   `(with-system-mutex ((thread-interruptions-lock ,thread))
1067      ,@body))
1068
1069 ;;; Called from the signal handler.
1070 #!-win32
1071 (defun run-interruption ()
1072   (let ((interruption (with-interruptions-lock (*current-thread*)
1073                         (pop (thread-interruptions *current-thread*)))))
1074     ;; If there is more to do, then resignal and let the normal
1075     ;; interrupt deferral mechanism take care of the rest. From the
1076     ;; OS's point of view the signal we are in the handler for is no
1077     ;; longer pending, so the signal will not be lost.
1078     (when (thread-interruptions *current-thread*)
1079       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1080     (when interruption
1081       (funcall interruption))))
1082
1083 (defun interrupt-thread (thread function)
1084   #!+sb-doc
1085   "Interrupt the live THREAD and make it run FUNCTION. A moderate
1086 degree of care is expected for use of INTERRUPT-THREAD, due to its
1087 nature: if you interrupt a thread that was holding important locks
1088 then do something that turns out to need those locks, you probably
1089 won't like the effect. FUNCTION runs with interrupts disabled, but
1090 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1091 enable interrupts (GET-MUTEX when contended, for instance) so the
1092 first thing to do is usually a WITH-INTERRUPTS or a
1093 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1094 run in same the order they were sent."
1095   #!+win32
1096   (declare (ignore thread))
1097   #!+win32
1098   (with-interrupt-bindings
1099     (with-interrupts (funcall function)))
1100   #!-win32
1101   (let ((os-thread (thread-os-thread thread)))
1102     (cond ((not os-thread)
1103            (error 'interrupt-thread-error :thread thread))
1104           (t
1105            (with-interruptions-lock (thread)
1106              ;; Append to the end of the interruptions queue. It's
1107              ;; O(N), but it does not hurt to slow interruptors down a
1108              ;; bit when the queue gets long.
1109              (setf (thread-interruptions thread)
1110                    (append (thread-interruptions thread)
1111                            (list (lambda ()
1112                                    (without-interrupts
1113                                      (allow-with-interrupts
1114                                        (funcall function))))))))
1115            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1116              (error 'interrupt-thread-error :thread thread))))))
1117
1118 (defun terminate-thread (thread)
1119   #!+sb-doc
1120   "Terminate the thread identified by THREAD, by causing it to run
1121 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1122   (interrupt-thread thread 'sb!ext:quit))
1123
1124 (define-alien-routine "thread_yield" int)
1125
1126 #!+sb-doc
1127 (setf (fdocumentation 'thread-yield 'function)
1128       "Yield the processor to other threads.")
1129
1130 ;;; internal use only.  If you think you need to use these, either you
1131 ;;; are an SBCL developer, are doing something that you should discuss
1132 ;;; with an SBCL developer first, or are doing something that you
1133 ;;; should probably discuss with a professional psychiatrist first
1134 #!+sb-thread
1135 (progn
1136   (defun %thread-sap (thread)
1137     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1138           (target (thread-os-thread thread)))
1139       (loop
1140         (when (sap= thread-sap (int-sap 0)) (return nil))
1141         (let ((os-thread (sap-ref-word thread-sap
1142                                        (* sb!vm:n-word-bytes
1143                                           sb!vm::thread-os-thread-slot))))
1144           (when (= os-thread target) (return thread-sap))
1145           (setf thread-sap
1146                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1147                                            sb!vm::thread-next-slot)))))))
1148
1149   (defun %symbol-value-in-thread (symbol thread)
1150     ;; Prevent the thread from dying completely while we look for the TLS
1151     ;; area...
1152     (with-all-threads-lock
1153       (loop
1154         (if (thread-alive-p thread)
1155             (let* ((epoch sb!kernel::*gc-epoch*)
1156                    (offset (* sb!vm:n-word-bytes
1157                               (sb!vm::symbol-tls-index symbol)))
1158                    (tl-val (sap-ref-word (%thread-sap thread) offset)))
1159               (cond ((zerop offset)
1160                      (return (values nil :no-tls-value)))
1161                     ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1162                          (eql tl-val sb!vm:unbound-marker-widetag))
1163                      (return (values nil :unbound-in-thread)))
1164                     (t
1165                      (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1166                        ;; The value we constructed may be invalid if a GC has
1167                        ;; occurred. That is harmless, though, since OBJ is
1168                        ;; either in a register or on stack, and we are
1169                        ;; conservative on both on GENCGC -- so a bogus object
1170                        ;; is safe here as long as we don't return it. If we
1171                        ;; ever port threads to a non-conservative GC we must
1172                        ;; pin the TL-VAL address before constructing OBJ, or
1173                        ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1174                        ;;
1175                        ;; The reason we don't just rely on TL-VAL pinning the
1176                        ;; object is that the call to MAKE-LISP-OBJ may cause
1177                        ;; bignum allocation, at which point TL-VAL might not
1178                        ;; be alive anymore -- hence the epoch check.
1179                        (when (eq epoch sb!kernel::*gc-epoch*)
1180                          (if ok
1181                              (return (values obj :ok))
1182                              (return (values obj :invalid-tls-value))))))))
1183             (return (values nil :thread-dead))))))
1184
1185   (defun %set-symbol-value-in-thread (symbol thread value)
1186     (with-pinned-objects (value)
1187       ;; Prevent the thread from dying completely while we look for the TLS
1188       ;; area...
1189       (with-all-threads-lock
1190         (if (thread-alive-p thread)
1191             (let ((offset (* sb!vm:n-word-bytes
1192                              (sb!vm::symbol-tls-index symbol))))
1193               (cond ((zerop offset)
1194                      (values nil :no-tls-value))
1195                     (t
1196                      (setf (sap-ref-word (%thread-sap thread) offset)
1197                            (get-lisp-obj-address value))
1198                      (values value :ok))))
1199             (values nil :thread-dead))))))
1200
1201 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1202   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1203 on success.
1204
1205 If the value cannot be retrieved (because the thread has exited or because it
1206 has no local binding for NAME) and ERRORP is true signals an error of type
1207 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1208 NIL, and a secondary value of NIL.
1209
1210 Can also be used with SETF to change the thread-local value of SYMBOL.
1211
1212 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1213 mechanism for inter-thread communication."
1214   (declare (symbol symbol) (thread thread))
1215   #!+sb-thread
1216   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1217     (if (eq :ok status)
1218         (values res t)
1219         (if errorp
1220             (error 'symbol-value-in-thread-error
1221                    :name symbol
1222                    :thread thread
1223                    :info (list :read status))
1224             (values nil nil))))
1225   #!-sb-thread
1226   (if (boundp symbol)
1227       (values (symbol-value symbol) t)
1228       (if errorp
1229           (error 'symbol-value-in-thread-error
1230                  :name symbol
1231                  :thread thread
1232                  :info (list :read :unbound-in-thread))
1233           (values nil nil))))
1234
1235 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1236   (declare (symbol symbol) (thread thread))
1237   #!+sb-thread
1238   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1239     (if (eq :ok status)
1240         (values res t)
1241         (if errorp
1242             (error 'symbol-value-in-thread-error
1243                    :name symbol
1244                    :thread thread
1245                    :info (list :write status))
1246             (values nil nil))))
1247   #!-sb-thread
1248   (if (boundp symbol)
1249       (values (setf (symbol-value symbol) value) t)
1250       (if errorp
1251           (error 'symbol-value-in-thread-error
1252                  :name symbol
1253                  :thread thread
1254                  :info (list :write :unbound-in-thread))
1255           (values nil nil))))
1256
1257 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1258   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1259 \f
1260
1261 ;;;; Stepping
1262
1263 (defun thread-stepping ()
1264   (make-lisp-obj
1265    (sap-ref-word (current-thread-sap)
1266                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1267
1268 (defun (setf thread-stepping) (value)
1269   (setf (sap-ref-word (current-thread-sap)
1270                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1271         (get-lisp-obj-address value)))