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