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