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