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