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