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