unify locks
[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 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
497   (with-deadlocks (self mutex timeout)
498     (with-interrupts (check-deadlock))
499     (tagbody
500      :again
501        (return-from %wait-for-mutex
502          (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
503              (when deadlinep
504                (signal-deadline)
505                ;; FIXME: substract elapsed time from timeout...
506                (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
507                      (decode-timeout timeout))
508                (go :again)))))))
509
510 (defun get-mutex (mutex &optional new-owner (waitp t) (timeout nil))
511   #!+sb-doc
512   "Deprecated in favor of GRAB-MUTEX."
513   (declare (ignorable waitp timeout))
514   (let ((new-owner (or new-owner *current-thread*)))
515     (or (%try-mutex mutex new-owner)
516         #!+sb-thread
517         (when waitp
518           (multiple-value-call #'%wait-for-mutex
519             mutex new-owner timeout (decode-timeout timeout))))))
520
521 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
522   #!+sb-doc
523   "Acquire MUTEX for the current thread. If WAITP is true (the default) and
524 the mutex is not immediately available, sleep until it is available.
525
526 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
527 GRAB-MUTEX should try to acquire the lock in the contested case.
528
529 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
530 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
531 that GRAB-MUTEX did -not- acquire the lock.
532
533 Notes:
534
535   - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
536
537       (WITHOUT-INTERRUPTS
538         ...
539         (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
540         ...)
541
542     WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
543     while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
544     allows the call to be interrupted from sleep.
545
546   - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
547     (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
548     DEADLINE-TIMEOUT if the global deadline was due already on entering
549     GRAB-MUTEX.
550
551     The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
552     future versions.
553
554   - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
555     directly.
556 "
557   (declare (ignorable waitp timeout))
558   (let ((self *current-thread*))
559     (or (%try-mutex mutex self)
560         #!+sb-thread
561         (when waitp
562           (multiple-value-call #'%wait-for-mutex
563             mutex self timeout (decode-timeout timeout))))))
564
565 (defun release-mutex (mutex &key (if-not-owner :punt))
566   #!+sb-doc
567   "Release MUTEX by setting it to NIL. Wake up threads waiting for
568 this mutex.
569
570 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
571 around calls to it.
572
573 If the current thread is not the owner of the mutex then it silently
574 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
575 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
576 IF-NOT-OWNER is :FORCE)."
577   (declare (type mutex mutex))
578   ;; Order matters: set owner to NIL before releasing state.
579   (let* ((self *current-thread*)
580          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
581     (unless (eq self old-owner)
582       (ecase if-not-owner
583         ((:punt) (return-from release-mutex nil))
584         ((:warn)
585          (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
586         ((:force)))
587       (setf (mutex-%owner mutex) nil)
588       ;; FIXME: Is a :memory barrier too strong here?  Can we use a :write
589       ;; barrier instead?
590       (barrier (:memory)))
591     #!+sb-futex
592     (when old-owner
593       ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
594       ;; unsigned-byte type this can be used:
595       ;;
596       ;;     (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
597       ;;       (unless (eql old +lock-free+)
598       ;;         (setf (mutex-state mutex) +lock-free+)
599       ;;         (with-pinned-objects (mutex)
600       ;;           (futex-wake (mutex-state-address mutex) 1))))
601       (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
602                                           +lock-taken+ +lock-free+)))
603         (when (eql old +lock-contested+)
604           (sb!ext:compare-and-swap (mutex-state mutex)
605                                    +lock-contested+ +lock-free+)
606           (with-pinned-objects (mutex)
607             (futex-wake (mutex-state-address mutex) 1))))
608       nil)))
609 \f
610
611 ;;;; Waitqueues/condition variables
612
613 #!+(or (not sb-thread) sb-futex)
614 (defstruct (waitqueue (:constructor %make-waitqueue))
615   #!+sb-doc
616   "Waitqueue type."
617   (name nil :type (or null thread-name))
618   #!+sb-futex
619   (token nil))
620
621 #!+(and sb-thread (not sb-futex))
622 (progn
623   (defstruct (waitqueue (:constructor %make-waitqueue))
624     #!+sb-doc
625     "Waitqueue type."
626     (name nil :type (or null thread-name))
627     ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
628     ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
629     ;; lock. In most cases this should be uncontested thanks to the mutex --
630     ;; the only case where that might not be true is when CONDITION-WAIT
631     ;; unwinds and %WAITQUEUE-DROP is called.
632     %owner
633     %head
634     %tail)
635
636   (defun %waitqueue-enqueue (thread queue)
637     (setf (thread-waiting-for thread) queue)
638     (let ((head (waitqueue-%head queue))
639           (tail (waitqueue-%tail queue))
640           (new (list thread)))
641       (unless head
642         (setf (waitqueue-%head queue) new))
643       (when tail
644         (setf (cdr tail) new))
645       (setf (waitqueue-%tail queue) new)
646       nil))
647   (defun %waitqueue-drop (thread queue)
648     (setf (thread-waiting-for thread) nil)
649     (let ((head (waitqueue-%head queue)))
650       (do ((list head (cdr list))
651            (prev nil))
652           ((eq (car list) thread)
653            (let ((rest (cdr list)))
654              (cond (prev
655                     (setf (cdr prev) rest))
656                    (t
657                     (setf (waitqueue-%head queue) rest
658                           prev rest)))
659              (unless rest
660                (setf (waitqueue-%tail queue) prev))))
661         (setf prev list)))
662     nil)
663   (defun %waitqueue-wakeup (queue n)
664     (declare (fixnum n))
665     (loop while (plusp n)
666           for next = (let ((head (waitqueue-%head queue))
667                            (tail (waitqueue-%tail queue)))
668                        (when head
669                          (if (eq head tail)
670                              (setf (waitqueue-%head queue) nil
671                                    (waitqueue-%tail queue) nil)
672                              (setf (waitqueue-%head queue) (cdr head)))
673                          (car head)))
674           while next
675           do (when (eq queue (sb!ext:compare-and-swap (thread-waiting-for next) queue nil))
676                (decf n)))
677     nil))
678
679 (def!method print-object ((waitqueue waitqueue) stream)
680   (print-unreadable-object (waitqueue stream :type t :identity t)
681     (format stream "~@[~A~]" (waitqueue-name waitqueue))))
682
683 (defun make-waitqueue (&key name)
684   #!+sb-doc
685   "Create a waitqueue."
686   (%make-waitqueue :name name))
687
688 #!+sb-doc
689 (setf (fdocumentation 'waitqueue-name 'function)
690       "The name of the waitqueue. Setfable.")
691
692 #!+(and sb-thread sb-futex)
693 (define-structure-slot-addressor waitqueue-token-address
694     :structure waitqueue
695     :slot token)
696
697 (defun condition-wait (queue mutex &key timeout)
698   #!+sb-doc
699   "Atomically release MUTEX and start waiting on QUEUE for till another thread
700 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
701 queue, at which point we re-acquire MUTEX and return T.
702
703 Spurious wakeups are possible.
704
705 If TIMEOUT is given, it is the maximum number of seconds to wait, including
706 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
707 wakeup and re-acquisition do not occur within the given time, returns NIL
708 without re-acquiring the mutex.
709
710 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
711
712 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
713 occurred the correct way to write code that uses CONDITION-WAIT is to loop
714 around the call, checking the the associated data:
715
716   (defvar *data* nil)
717   (defvar *queue* (make-waitqueue))
718   (defvar *lock* (make-mutex))
719
720   ;; Consumer
721   (defun pop-data (&optional timeout)
722     (with-mutex (*lock*)
723       (loop until *data*
724             do (or (condition-wait *queue* *lock* :timeout timeout)
725                    ;; Lock not held, must unwind without touching *data*.
726                    (return-from pop-data nil)))
727       (pop *data*)))
728
729   ;; Producer
730   (defun push-data (data)
731     (with-mutex (*lock*)
732       (push data *data*)
733       (condition-notify *queue*)))
734 "
735   #!-sb-thread (declare (ignore queue timeout))
736   (assert mutex)
737   #!-sb-thread
738   (wait-for nil :timeout timeout) ; Yeah...
739   #!+sb-thread
740   (let ((me *current-thread*))
741     (barrier (:read))
742     (assert (eq me (mutex-%owner mutex)))
743     (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
744         (decode-timeout timeout)
745       (let ((status :interrupted))
746         ;; Need to disable interrupts so that we don't miss grabbing the
747         ;; mutex on our way out.
748         (without-interrupts
749           (unwind-protect
750                (progn
751                  #!-sb-futex
752                  (progn
753                    (%waitqueue-enqueue me queue)
754                    (release-mutex mutex)
755                    (setf status
756                          (or (flet ((wakeup ()
757                                       (when (neq queue (thread-waiting-for me))
758                                         :ok)))
759                                (declare (dynamic-extent #'wakeup))
760                                (allow-with-interrupts
761                                  (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
762                              :timeout)))
763                  #!+sb-futex
764                  (with-pinned-objects (queue me)
765                    (setf (waitqueue-token queue) me)
766                    (release-mutex mutex)
767                    ;; Now we go to sleep using futex-wait. If anyone else
768                    ;; manages to grab MUTEX and call CONDITION-NOTIFY during
769                    ;; this comment, it will change the token, and so futex-wait
770                    ;; returns immediately instead of sleeping. Ergo, no lost
771                    ;; wakeup. We may get spurious wakeups, but that's ok.
772                    (setf status
773                          (case (allow-with-interrupts
774                                  (futex-wait (waitqueue-token-address queue)
775                                              (get-lisp-obj-address me)
776                                              ;; our way of saying "no
777                                              ;; timeout":
778                                              (or to-sec -1)
779                                              (or to-usec 0)))
780                            ((1)
781                             ;;  1 = ETIMEDOUT
782                             :timeout)
783                            (t
784                             ;; -1 = EWOULDBLOCK, possibly spurious wakeup
785                             ;;  0 = normal wakeup
786                             ;;  2 = EINTR, a spurious wakeup
787                             :ok)))))
788             #!-sb-futex
789             (%with-cas-lock ((waitqueue-%owner queue))
790               (if (eq queue (thread-waiting-for me))
791                   (%waitqueue-drop me queue)
792                   (unless (eq :ok status)
793                     ;; CONDITION-NOTIFY thinks we've been woken up, but really
794                     ;; we're unwinding. Wake someone else up.
795                     (%waitqueue-wakeup queue 1))))
796             ;; Update timeout for mutex re-aquisition.
797             (when (and (eq :ok status) to-sec)
798               (setf (values to-sec to-usec)
799                     (sb!impl::relative-decoded-times stop-sec stop-usec)))
800             ;; If we ran into deadline, try to get the mutex before
801             ;; signaling. If we don't unwind it will look like a normal
802             ;; return from user perspective.
803             (when (and (eq :timeout status) deadlinep)
804               (let ((got-it (%try-mutex mutex me)))
805                 (allow-with-interrupts
806                   (signal-deadline)
807                   (cond (got-it
808                          (return-from condition-wait t))
809                         (t
810                          ;; The deadline may have changed.
811                          (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
812                                (decode-timeout timeout))
813                          (setf status :ok))))))
814             ;; Re-acquire the mutex for normal return.
815             (when (eq :ok status)
816               (unless (or (%try-mutex mutex me)
817                           (allow-with-interrupts
818                             (%wait-for-mutex mutex me timeout
819                                              to-sec to-usec
820                                              stop-sec stop-usec deadlinep)))
821                 (setf status :timeout)))))
822         (or (eq :ok status)
823             (unless (eq :timeout status)
824               ;; The only case we return normally without re-acquiring the
825               ;; mutex is when there is a :TIMEOUT that runs out.
826               (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
827
828 (defun condition-notify (queue &optional (n 1))
829   #!+sb-doc
830   "Notify N threads waiting on QUEUE.
831
832 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
833 must be held by this thread during this call."
834   #!-sb-thread
835   (declare (ignore queue n))
836   #!-sb-thread
837   (error "Not supported in unithread builds.")
838   #!+sb-thread
839   (declare (type (and fixnum (integer 1)) n))
840   (/show0 "Entering CONDITION-NOTIFY")
841   #!+sb-thread
842   (progn
843     #!-sb-futex
844     (with-cas-lock ((waitqueue-%owner queue))
845       (%waitqueue-wakeup queue n))
846     #!+sb-futex
847     (progn
848     ;; No problem if >1 thread notifies during the comment in condition-wait:
849     ;; as long as the value in queue-data isn't the waiting thread's id, it
850     ;; matters not what it is -- using the queue object itself is handy.
851     ;;
852     ;; XXX we should do something to ensure that the result of this setf
853     ;; is visible to all CPUs.
854     ;;
855     ;; ^-- surely futex_wake() involves a memory barrier?
856       (setf (waitqueue-token queue) queue)
857       (with-pinned-objects (queue)
858         (futex-wake (waitqueue-token-address queue) n)))))
859
860 (defun condition-broadcast (queue)
861   #!+sb-doc
862   "Notify all threads waiting on QUEUE.
863
864 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
865 must be held by this thread during this call."
866   (condition-notify queue
867                     ;; On a 64-bit platform truncating M-P-F to an int
868                     ;; results in -1, which wakes up only one thread.
869                     (ldb (byte 29 0)
870                          most-positive-fixnum)))
871 \f
872
873 ;;;; Semaphores
874
875 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
876   #!+sb-doc
877   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
878 should be considered an implementation detail, and may change in the
879 future."
880   (name    nil :type (or null thread-name))
881   (%count    0 :type (integer 0))
882   (waitcount 0 :type sb!vm:word)
883   (mutex (make-mutex))
884   (queue (make-waitqueue)))
885
886 (setf (fdocumentation 'semaphore-name 'function)
887       "The name of the semaphore INSTANCE. Setfable.")
888
889 (declaim (inline semaphore-count))
890 (defun semaphore-count (instance)
891   "Returns the current count of the semaphore INSTANCE."
892   (barrier (:read))
893   (semaphore-%count instance))
894
895 (defun make-semaphore (&key name (count 0))
896   #!+sb-doc
897   "Create a semaphore with the supplied COUNT and NAME."
898   (%make-semaphore name count))
899
900 (defun wait-on-semaphore (semaphore &key timeout)
901   #!+sb-doc
902   "Decrement the count of SEMAPHORE if the count would not be negative. Else
903 blocks until the semaphore can be decremented. Returns T on success.
904
905 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
906 cannot be decremented in that time, returns NIL without decrementing the
907 count."
908   ;; A more direct implementation based directly on futexes should be
909   ;; possible.
910   ;;
911   ;; We need to disable interrupts so that we don't forget to
912   ;; decrement the waitcount (which would happen if an asynch
913   ;; interrupt should catch us on our way out from the loop.)
914   ;;
915   ;; FIXME: No timeout on initial mutex acquisition.
916   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
917     ;; Quick check: is it positive? If not, enter the wait loop.
918     (let ((count (semaphore-%count semaphore)))
919       (if (plusp count)
920           (setf (semaphore-%count semaphore) (1- count))
921           (unwind-protect
922                (progn
923                  ;; Need to use ATOMIC-INCF despite the lock, because on our
924                  ;; way out from here we might not be locked anymore -- so
925                  ;; another thread might be tweaking this in parallel using
926                  ;; ATOMIC-DECF. No danger over overflow, since there it
927                  ;; at most one increment per thread waiting on the semaphore.
928                  (sb!ext:atomic-incf (semaphore-waitcount semaphore))
929                  (loop until (plusp (setf count (semaphore-%count semaphore)))
930                        do (or (condition-wait (semaphore-queue semaphore)
931                                               (semaphore-mutex semaphore)
932                                               :timeout timeout)
933                               (return-from wait-on-semaphore nil)))
934                  (setf (semaphore-%count semaphore) (1- count)))
935             ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
936             ;; may unwind without the lock being held due to timeouts.
937             (sb!ext:atomic-decf (semaphore-waitcount semaphore))))))
938   t)
939
940 (defun try-semaphore (semaphore &optional (n 1))
941   #!+sb-doc
942   "Try to decrement the count of SEMAPHORE by N. If the count were to
943 become negative, punt and return NIL, otherwise return true."
944   (declare (type (integer 1) n))
945   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
946     (let ((new-count (- (semaphore-%count semaphore) n)))
947       (when (not (minusp new-count))
948         (setf (semaphore-%count semaphore) new-count)))))
949
950 (defun signal-semaphore (semaphore &optional (n 1))
951   #!+sb-doc
952   "Increment the count of SEMAPHORE by N. If there are threads waiting
953 on this semaphore, then N of them is woken up."
954   (declare (type (integer 1) n))
955   ;; Need to disable interrupts so that we don't lose a wakeup after
956   ;; we have incremented the count.
957   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
958     (let ((waitcount (semaphore-waitcount semaphore))
959           (count (incf (semaphore-%count semaphore) n)))
960       (when (plusp waitcount)
961         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
962 \f
963
964 ;;;; Job control, independent listeners
965
966 (defstruct session
967   (lock (make-mutex :name "session lock"))
968   (threads nil)
969   (interactive-threads nil)
970   (interactive-threads-queue (make-waitqueue)))
971
972 (defvar *session* nil)
973
974 ;;; The debugger itself tries to acquire the session lock, don't let
975 ;;; funny situations (like getting a sigint while holding the session
976 ;;; lock) occur. At the same time we need to allow interrupts while
977 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
978 ;;; be interruptible.
979 ;;;
980 ;;; Take care: we sometimes need to obtain the session lock while
981 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
982 ;;; _after_ getting a session lock! (Deadlock risk.)
983 ;;;
984 ;;; FIXME: It would be good to have ordered locks to ensure invariants
985 ;;; like the above.
986 (defmacro with-session-lock ((session) &body body)
987   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
988      ,@body))
989
990 (defun new-session ()
991   (make-session :threads (list *current-thread*)
992                 :interactive-threads (list *current-thread*)))
993
994 (defun init-job-control ()
995   (/show0 "Entering INIT-JOB-CONTROL")
996   (setf *session* (new-session))
997   (/show0 "Exiting INIT-JOB-CONTROL"))
998
999 (defun %delete-thread-from-session (thread session)
1000   (with-session-lock (session)
1001     (setf (session-threads session)
1002           (delete thread (session-threads session))
1003           (session-interactive-threads session)
1004           (delete thread (session-interactive-threads session)))))
1005
1006 (defun call-with-new-session (fn)
1007   (%delete-thread-from-session *current-thread* *session*)
1008   (let ((*session* (new-session)))
1009     (funcall fn)))
1010
1011 (defmacro with-new-session (args &body forms)
1012   (declare (ignore args))               ;for extensibility
1013   (sb!int:with-unique-names (fb-name)
1014     `(labels ((,fb-name () ,@forms))
1015       (call-with-new-session (function ,fb-name)))))
1016
1017 ;;; Remove thread from its session, if it has one.
1018 #!+sb-thread
1019 (defun handle-thread-exit (thread)
1020   (/show0 "HANDLING THREAD EXIT")
1021   ;; Lisp-side cleanup
1022   (with-all-threads-lock
1023     (setf (thread-%alive-p thread) nil)
1024     (setf (thread-os-thread thread) nil)
1025     (setq *all-threads* (delete thread *all-threads*))
1026     (when *session*
1027       (%delete-thread-from-session thread *session*))))
1028
1029 (defun terminate-session ()
1030   #!+sb-doc
1031   "Kill all threads in session except for this one.  Does nothing if current
1032 thread is not the foreground thread."
1033   ;; FIXME: threads created in other threads may escape termination
1034   (let ((to-kill
1035          (with-session-lock (*session*)
1036            (and (eq *current-thread*
1037                     (car (session-interactive-threads *session*)))
1038                 (session-threads *session*)))))
1039     ;; do the kill after dropping the mutex; unwind forms in dying
1040     ;; threads may want to do session things
1041     (dolist (thread to-kill)
1042       (unless (eq thread *current-thread*)
1043         ;; terminate the thread but don't be surprised if it has
1044         ;; exited in the meantime
1045         (handler-case (terminate-thread thread)
1046           (interrupt-thread-error ()))))))
1047
1048 ;;; called from top of invoke-debugger
1049 (defun debugger-wait-until-foreground-thread (stream)
1050   "Returns T if thread had been running in background, NIL if it was
1051 interactive."
1052   (declare (ignore stream))
1053   #!-sb-thread nil
1054   #!+sb-thread
1055   (prog1
1056       (with-session-lock (*session*)
1057         (not (member *current-thread*
1058                      (session-interactive-threads *session*))))
1059     (get-foreground)))
1060
1061 (defun get-foreground ()
1062   #!-sb-thread t
1063   #!+sb-thread
1064   (let ((was-foreground t))
1065     (loop
1066      (/show0 "Looping in GET-FOREGROUND")
1067      (with-session-lock (*session*)
1068        (let ((int-t (session-interactive-threads *session*)))
1069          (when (eq (car int-t) *current-thread*)
1070            (unless was-foreground
1071              (format *query-io* "Resuming thread ~A~%" *current-thread*))
1072            (return-from get-foreground t))
1073          (setf was-foreground nil)
1074          (unless (member *current-thread* int-t)
1075            (setf (cdr (last int-t))
1076                  (list *current-thread*)))
1077          (condition-wait
1078           (session-interactive-threads-queue *session*)
1079           (session-lock *session*)))))))
1080
1081 (defun release-foreground (&optional next)
1082   #!+sb-doc
1083   "Background this thread.  If NEXT is supplied, arrange for it to
1084 have the foreground next."
1085   #!-sb-thread (declare (ignore next))
1086   #!-sb-thread nil
1087   #!+sb-thread
1088   (with-session-lock (*session*)
1089     (when (rest (session-interactive-threads *session*))
1090       (setf (session-interactive-threads *session*)
1091             (delete *current-thread* (session-interactive-threads *session*))))
1092     (when next
1093       (setf (session-interactive-threads *session*)
1094             (list* next
1095                    (delete next (session-interactive-threads *session*)))))
1096     (condition-broadcast (session-interactive-threads-queue *session*))))
1097
1098 (defun foreground-thread ()
1099   (car (session-interactive-threads *session*)))
1100
1101 (defun make-listener-thread (tty-name)
1102   (assert (probe-file tty-name))
1103   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1104          (out (sb!unix:unix-dup in))
1105          (err (sb!unix:unix-dup in)))
1106     (labels ((thread-repl ()
1107                (sb!unix::unix-setsid)
1108                (let* ((sb!impl::*stdin*
1109                        (make-fd-stream in :input t :buffering :line
1110                                        :dual-channel-p t))
1111                       (sb!impl::*stdout*
1112                        (make-fd-stream out :output t :buffering :line
1113                                               :dual-channel-p t))
1114                       (sb!impl::*stderr*
1115                        (make-fd-stream err :output t :buffering :line
1116                                               :dual-channel-p t))
1117                       (sb!impl::*tty*
1118                        (make-fd-stream err :input t :output t
1119                                               :buffering :line
1120                                               :dual-channel-p t))
1121                       (sb!impl::*descriptor-handlers* nil))
1122                  (with-new-session ()
1123                    (unwind-protect
1124                         (sb!impl::toplevel-repl nil)
1125                      (sb!int:flush-standard-output-streams))))))
1126       (make-thread #'thread-repl))))
1127 \f
1128
1129 ;;;; The beef
1130
1131 (defun make-thread (function &key name arguments)
1132   #!+sb-doc
1133   "Create a new thread of NAME that runs FUNCTION with the argument
1134 list designator provided (defaults to no argument). When the function
1135 returns the thread exits. The return values of FUNCTION are kept
1136 around and can be retrieved by JOIN-THREAD."
1137   #!-sb-thread (declare (ignore function name arguments))
1138   #!-sb-thread (error "Not supported in unithread builds.")
1139   #!+sb-thread (assert (or (atom arguments)
1140                            (null (cdr (last arguments))))
1141                        (arguments)
1142                        "Argument passed to ~S, ~S, is an improper list."
1143                        'make-thread arguments)
1144   #!+sb-thread
1145   (let* ((thread (%make-thread :name name))
1146          (setup-sem (make-semaphore :name "Thread setup semaphore"))
1147          (real-function (coerce function 'function))
1148          (arguments     (if (listp arguments)
1149                             arguments
1150                             (list arguments)))
1151          (initial-function
1152           (named-lambda initial-thread-function ()
1153             ;; In time we'll move some of the binding presently done in C
1154             ;; here too.
1155             ;;
1156             ;; KLUDGE: Here we have a magic list of variables that are
1157             ;; not thread-safe for one reason or another.  As people
1158             ;; report problems with the thread safety of certain
1159             ;; variables, (e.g. "*print-case* in multiple threads
1160             ;; broken", sbcl-devel 2006-07-14), we add a few more
1161             ;; bindings here.  The Right Thing is probably some variant
1162             ;; of Allegro's *cl-default-special-bindings*, as that is at
1163             ;; least accessible to users to secure their own libraries.
1164             ;;   --njf, 2006-07-15
1165             ;;
1166             ;; As it is, this lambda must not cons until we are ready
1167             ;; to run GC. Be very careful.
1168             (let* ((*current-thread* thread)
1169                    (*restart-clusters* nil)
1170                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
1171                    (*condition-restarts* nil)
1172                    (sb!impl::*deadline* nil)
1173                    (sb!impl::*deadline-seconds* nil)
1174                    (sb!impl::*step-out* nil)
1175                    ;; internal printer variables
1176                    (sb!impl::*previous-case* nil)
1177                    (sb!impl::*previous-readtable-case* nil)
1178                    (sb!impl::*internal-symbol-output-fun* nil)
1179                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
1180               ;; Binding from C
1181               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1182               (setf (thread-os-thread thread) (current-thread-os-thread))
1183               (with-mutex ((thread-result-lock thread))
1184                 (with-all-threads-lock
1185                   (push thread *all-threads*))
1186                 (with-session-lock (*session*)
1187                   (push thread (session-threads *session*)))
1188                 (setf (thread-%alive-p thread) t)
1189                 (signal-semaphore setup-sem)
1190                 ;; can't use handling-end-of-the-world, because that flushes
1191                 ;; output streams, and we don't necessarily have any (or we
1192                 ;; could be sharing them)
1193                 (catch 'sb!impl::toplevel-catcher
1194                   (catch 'sb!impl::%end-of-the-world
1195                     (with-simple-restart
1196                         (terminate-thread
1197                          (format nil
1198                                  "~~@<Terminate this thread (~A)~~@:>"
1199                                  *current-thread*))
1200                       (without-interrupts
1201                         (unwind-protect
1202                              (with-local-interrupts
1203                                ;; Now that most things have a chance
1204                                ;; to work properly without messing up
1205                                ;; other threads, it's time to enable
1206                                ;; signals.
1207                                (sb!unix::unblock-deferrable-signals)
1208                                (setf (thread-result thread)
1209                                      (cons t
1210                                            (multiple-value-list
1211                                             (apply real-function arguments))))
1212                                ;; Try to block deferrables. An
1213                                ;; interrupt may unwind it, but for a
1214                                ;; normal exit it prevents interrupt
1215                                ;; loss.
1216                                (block-deferrable-signals))
1217                           ;; We're going down, can't handle interrupts
1218                           ;; sanely anymore. GC remains enabled.
1219                           (block-deferrable-signals)
1220                           ;; We don't want to run interrupts in a dead
1221                           ;; thread when we leave WITHOUT-INTERRUPTS.
1222                           ;; This potentially causes important
1223                           ;; interupts to be lost: SIGINT comes to
1224                           ;; mind.
1225                           (setq *interrupt-pending* nil)
1226                           (handle-thread-exit thread))))))))
1227             (values))))
1228     ;; If the starting thread is stopped for gc before it signals the
1229     ;; semaphore then we'd be stuck.
1230     (assert (not *gc-inhibit*))
1231     ;; Keep INITIAL-FUNCTION pinned until the child thread is
1232     ;; initialized properly. Wrap the whole thing in
1233     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1234     ;; thread.
1235     (without-interrupts
1236       (with-pinned-objects (initial-function)
1237         (let ((os-thread
1238                (%create-thread
1239                 (get-lisp-obj-address initial-function))))
1240           (when (zerop os-thread)
1241             (error "Can't create a new thread"))
1242           (wait-on-semaphore setup-sem)
1243           thread)))))
1244
1245 (defun join-thread (thread &key (default nil defaultp) timeout)
1246   #!+sb-doc
1247   "Suspend current thread until THREAD exits. Return the result values of the
1248 thread function.
1249
1250 If the thread does not exit normally within TIMEOUT seconds return DEFAULT if
1251 given, or else signal JOIN-THREAD-ERROR.
1252
1253 NOTE: Return convention in case of a timeout is exprimental and subject to
1254 change."
1255   (let ((lock (thread-result-lock thread))
1256         (got-it nil)
1257         (problem :timeout))
1258     (without-interrupts
1259       (unwind-protect
1260            (if (setf got-it
1261                      (allow-with-interrupts
1262                        ;; Don't use the timeout if the thread is not alive anymore.
1263                        (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1264                (cond ((car (thread-result thread))
1265                       (return-from join-thread
1266                         (values-list (cdr (thread-result thread)))))
1267                      (defaultp
1268                       (return-from join-thread default))
1269                      (t
1270                       (setf problem :abort)))
1271                (when defaultp
1272                  (return-from join-thread default)))
1273         (when got-it
1274           (release-mutex lock))))
1275     (error 'join-thread-error :thread thread :problem problem)))
1276
1277 (defun destroy-thread (thread)
1278   #!+sb-doc
1279   "Deprecated. Same as TERMINATE-THREAD."
1280   (terminate-thread thread))
1281
1282 (defmacro with-interruptions-lock ((thread) &body body)
1283   `(with-system-mutex ((thread-interruptions-lock ,thread))
1284      ,@body))
1285
1286 ;;; Called from the signal handler.
1287 #!-win32
1288 (defun run-interruption ()
1289   (let ((interruption (with-interruptions-lock (*current-thread*)
1290                         (pop (thread-interruptions *current-thread*)))))
1291     ;; If there is more to do, then resignal and let the normal
1292     ;; interrupt deferral mechanism take care of the rest. From the
1293     ;; OS's point of view the signal we are in the handler for is no
1294     ;; longer pending, so the signal will not be lost.
1295     (when (thread-interruptions *current-thread*)
1296       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1297     (when interruption
1298       (funcall interruption))))
1299
1300 (defun interrupt-thread (thread function)
1301   #!+sb-doc
1302   "Interrupt the live THREAD and make it run FUNCTION. A moderate
1303 degree of care is expected for use of INTERRUPT-THREAD, due to its
1304 nature: if you interrupt a thread that was holding important locks
1305 then do something that turns out to need those locks, you probably
1306 won't like the effect. FUNCTION runs with interrupts disabled, but
1307 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1308 enable interrupts (GET-MUTEX when contended, for instance) so the
1309 first thing to do is usually a WITH-INTERRUPTS or a
1310 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1311 run in same the order they were sent."
1312   #!+win32
1313   (declare (ignore thread))
1314   #!+win32
1315   (with-interrupt-bindings
1316     (with-interrupts (funcall function)))
1317   #!-win32
1318   (let ((os-thread (thread-os-thread thread)))
1319     (cond ((not os-thread)
1320            (error 'interrupt-thread-error :thread thread))
1321           (t
1322            (with-interruptions-lock (thread)
1323              ;; Append to the end of the interruptions queue. It's
1324              ;; O(N), but it does not hurt to slow interruptors down a
1325              ;; bit when the queue gets long.
1326              (setf (thread-interruptions thread)
1327                    (append (thread-interruptions thread)
1328                            (list (lambda ()
1329                                    (without-interrupts
1330                                      (allow-with-interrupts
1331                                        (funcall function))))))))
1332            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1333              (error 'interrupt-thread-error :thread thread))))))
1334
1335 (defun terminate-thread (thread)
1336   #!+sb-doc
1337   "Terminate the thread identified by THREAD, by causing it to run
1338 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1339   (interrupt-thread thread 'sb!ext:quit))
1340
1341 (define-alien-routine "thread_yield" int)
1342
1343 #!+sb-doc
1344 (setf (fdocumentation 'thread-yield 'function)
1345       "Yield the processor to other threads.")
1346
1347 ;;; internal use only.  If you think you need to use these, either you
1348 ;;; are an SBCL developer, are doing something that you should discuss
1349 ;;; with an SBCL developer first, or are doing something that you
1350 ;;; should probably discuss with a professional psychiatrist first
1351 #!+sb-thread
1352 (progn
1353   (defun %thread-sap (thread)
1354     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1355           (target (thread-os-thread thread)))
1356       (loop
1357         (when (sap= thread-sap (int-sap 0)) (return nil))
1358         (let ((os-thread (sap-ref-word thread-sap
1359                                        (* sb!vm:n-word-bytes
1360                                           sb!vm::thread-os-thread-slot))))
1361           (when (= os-thread target) (return thread-sap))
1362           (setf thread-sap
1363                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1364                                            sb!vm::thread-next-slot)))))))
1365
1366   (defun %symbol-value-in-thread (symbol thread)
1367     ;; Prevent the thread from dying completely while we look for the TLS
1368     ;; area...
1369     (with-all-threads-lock
1370       (loop
1371         (if (thread-alive-p thread)
1372             (let* ((epoch sb!kernel::*gc-epoch*)
1373                    (offset (sb!kernel:get-lisp-obj-address
1374                             (sb!vm::symbol-tls-index symbol)))
1375                    (tl-val (sap-ref-word (%thread-sap thread) offset)))
1376               (cond ((zerop offset)
1377                      (return (values nil :no-tls-value)))
1378                     ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1379                          (eql tl-val sb!vm:unbound-marker-widetag))
1380                      (return (values nil :unbound-in-thread)))
1381                     (t
1382                      (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1383                        ;; The value we constructed may be invalid if a GC has
1384                        ;; occurred. That is harmless, though, since OBJ is
1385                        ;; either in a register or on stack, and we are
1386                        ;; conservative on both on GENCGC -- so a bogus object
1387                        ;; is safe here as long as we don't return it. If we
1388                        ;; ever port threads to a non-conservative GC we must
1389                        ;; pin the TL-VAL address before constructing OBJ, or
1390                        ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1391                        ;;
1392                        ;; The reason we don't just rely on TL-VAL pinning the
1393                        ;; object is that the call to MAKE-LISP-OBJ may cause
1394                        ;; bignum allocation, at which point TL-VAL might not
1395                        ;; be alive anymore -- hence the epoch check.
1396                        (when (eq epoch sb!kernel::*gc-epoch*)
1397                          (if ok
1398                              (return (values obj :ok))
1399                              (return (values obj :invalid-tls-value))))))))
1400             (return (values nil :thread-dead))))))
1401
1402   (defun %set-symbol-value-in-thread (symbol thread value)
1403     (with-pinned-objects (value)
1404       ;; Prevent the thread from dying completely while we look for the TLS
1405       ;; area...
1406       (with-all-threads-lock
1407         (if (thread-alive-p thread)
1408             (let ((offset (sb!kernel:get-lisp-obj-address
1409                            (sb!vm::symbol-tls-index symbol))))
1410               (cond ((zerop offset)
1411                      (values nil :no-tls-value))
1412                     (t
1413                      (setf (sap-ref-word (%thread-sap thread) offset)
1414                            (get-lisp-obj-address value))
1415                      (values value :ok))))
1416             (values nil :thread-dead)))))
1417
1418   (define-alien-variable tls-index-start unsigned-int)
1419
1420   ;; Get values from the TLS area of the current thread.
1421   (defun %thread-local-references ()
1422     (without-gcing
1423       (let ((sap (%thread-sap *current-thread*)))
1424         (loop for index from tls-index-start
1425                 below (symbol-value 'sb!vm::*free-tls-index*)
1426               for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1427               for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1428               unless (or (not ok)
1429                          (typep obj '(or fixnum character))
1430                          (member value
1431                                  '(#.sb!vm:no-tls-value-marker-widetag
1432                                    #.sb!vm:unbound-marker-widetag))
1433                          (member obj seen :test #'eq))
1434                 collect obj into seen
1435               finally (return seen))))))
1436
1437 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1438   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1439 on success.
1440
1441 If the value cannot be retrieved (because the thread has exited or because it
1442 has no local binding for NAME) and ERRORP is true signals an error of type
1443 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1444 NIL, and a secondary value of NIL.
1445
1446 Can also be used with SETF to change the thread-local value of SYMBOL.
1447
1448 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1449 mechanism for inter-thread communication."
1450   (declare (symbol symbol) (thread thread))
1451   #!+sb-thread
1452   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1453     (if (eq :ok status)
1454         (values res t)
1455         (if errorp
1456             (error 'symbol-value-in-thread-error
1457                    :name symbol
1458                    :thread thread
1459                    :info (list :read status))
1460             (values nil nil))))
1461   #!-sb-thread
1462   (if (boundp symbol)
1463       (values (symbol-value symbol) t)
1464       (if errorp
1465           (error 'symbol-value-in-thread-error
1466                  :name symbol
1467                  :thread thread
1468                  :info (list :read :unbound-in-thread))
1469           (values nil nil))))
1470
1471 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1472   (declare (symbol symbol) (thread thread))
1473   #!+sb-thread
1474   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1475     (if (eq :ok status)
1476         (values res t)
1477         (if errorp
1478             (error 'symbol-value-in-thread-error
1479                    :name symbol
1480                    :thread thread
1481                    :info (list :write status))
1482             (values nil nil))))
1483   #!-sb-thread
1484   (if (boundp symbol)
1485       (values (setf (symbol-value symbol) value) t)
1486       (if errorp
1487           (error 'symbol-value-in-thread-error
1488                  :name symbol
1489                  :thread thread
1490                  :info (list :write :unbound-in-thread))
1491           (values nil nil))))
1492
1493 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1494   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1495 \f
1496
1497 ;;;; Stepping
1498
1499 (defun thread-stepping ()
1500   (make-lisp-obj
1501    (sap-ref-word (current-thread-sap)
1502                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1503
1504 (defun (setf thread-stepping) (value)
1505   (setf (sap-ref-word (current-thread-sap)
1506                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1507         (get-lisp-obj-address value)))