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