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