killing lutexes, adding timeouts
[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 (error "Not supported in unithread builds.")
797   #!+sb-thread
798   (let ((me *current-thread*))
799     (barrier (:read))
800     (assert (eq me (mutex-%owner mutex)))
801     (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
802         (decode-timeout timeout)
803       (let ((status :interrupted))
804         ;; Need to disable interrupts so that we don't miss grabbing the
805         ;; mutex on our way out.
806         (without-interrupts
807           (unwind-protect
808                (progn
809                  #!-sb-futex
810                  (progn
811                    (%waitqueue-enqueue me queue)
812                    (release-mutex mutex)
813                    (setf status
814                          (or (flet ((wakeup ()
815                                       (when (neq queue (thread-waiting-for me))
816                                         :ok)))
817                                (declare (dynamic-extent #'wakeup))
818                                (allow-with-interrupts
819                                  (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
820                              :timeout)))
821                  #!+sb-futex
822                  (with-pinned-objects (queue me)
823                    (setf (waitqueue-token queue) me)
824                    (release-mutex mutex)
825                    ;; Now we go to sleep using futex-wait. If anyone else
826                    ;; manages to grab MUTEX and call CONDITION-NOTIFY during
827                    ;; this comment, it will change the token, and so futex-wait
828                    ;; returns immediately instead of sleeping. Ergo, no lost
829                    ;; wakeup. We may get spurious wakeups, but that's ok.
830                    (setf status
831                          (case (allow-with-interrupts
832                                  (futex-wait (waitqueue-token-address queue)
833                                              (get-lisp-obj-address me)
834                                              ;; our way of saying "no
835                                              ;; timeout":
836                                              (or to-sec -1)
837                                              (or to-usec 0)))
838                            ((1)
839                             ;;  1 = ETIMEDOUT
840                             :timeout)
841                            (t
842                             ;; -1 = EWOULDBLOCK, possibly spurious wakeup
843                             ;;  0 = normal wakeup
844                             ;;  2 = EINTR, a spurious wakeup
845                             :ok)))))
846             #!-sb-futex
847             (%with-cas-lock ((waitqueue-%owner queue))
848               (if (eq queue (thread-waiting-for me))
849                   (%waitqueue-drop me queue)
850                   (unless (eq :ok status)
851                     ;; CONDITION-NOTIFY thinks we've been woken up, but really
852                     ;; we're unwinding. Wake someone else up.
853                     (%waitqueue-wakeup queue 1))))
854             ;; Update timeout for mutex re-aquisition.
855             (when (and (eq :ok status) to-sec)
856               (setf (values to-sec to-usec)
857                     (sb!impl::relative-decoded-times stop-sec stop-usec)))
858             ;; If we ran into deadline, try to get the mutex before
859             ;; signaling. If we don't unwind it will look like a normal
860             ;; return from user perspective.
861             (when (and (eq :timeout status) deadlinep)
862               (let ((got-it (%try-mutex mutex me)))
863                 (allow-with-interrupts
864                   (signal-deadline))
865                 (cond (got-it
866                        (return-from condition-wait t))
867                       (t
868                        (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
869                              (decode-timeout timeout))))))
870             ;; Re-acquire the mutex for normal return.
871             (unless (or (%try-mutex mutex me)
872                         (allow-with-interrupts
873                           (%wait-for-mutex mutex me timeout
874                                            to-sec to-usec
875                                            stop-sec stop-usec deadlinep)))
876               ;; The only case we return normally without re-acquiring the
877               ;; mutex is when there is a :TIMEOUT that runs out.
878               (aver (and timeout (not deadlinep)))
879               (return-from condition-wait nil)))))))
880   t)
881
882 (defun condition-notify (queue &optional (n 1))
883   #!+sb-doc
884   "Notify N threads waiting on QUEUE.
885
886 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
887 must be held by this thread during this call."
888   #!-sb-thread
889   (declare (ignore queue n))
890   #!-sb-thread
891   (error "Not supported in unithread builds.")
892   #!+sb-thread
893   (declare (type (and fixnum (integer 1)) n))
894   (/show0 "Entering CONDITION-NOTIFY")
895   #!+sb-thread
896   (progn
897     #!-sb-futex
898     (with-cas-lock ((waitqueue-%owner queue))
899       (%waitqueue-wakeup queue n))
900     #!+sb-futex
901     (progn
902     ;; No problem if >1 thread notifies during the comment in condition-wait:
903     ;; as long as the value in queue-data isn't the waiting thread's id, it
904     ;; matters not what it is -- using the queue object itself is handy.
905     ;;
906     ;; XXX we should do something to ensure that the result of this setf
907     ;; is visible to all CPUs.
908     ;;
909     ;; ^-- surely futex_wake() involves a memory barrier?
910       (setf (waitqueue-token queue) queue)
911       (with-pinned-objects (queue)
912         (futex-wake (waitqueue-token-address queue) n)))))
913
914 (defun condition-broadcast (queue)
915   #!+sb-doc
916   "Notify all threads waiting on QUEUE.
917
918 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
919 must be held by this thread during this call."
920   (condition-notify queue
921                     ;; On a 64-bit platform truncating M-P-F to an int
922                     ;; results in -1, which wakes up only one thread.
923                     (ldb (byte 29 0)
924                          most-positive-fixnum)))
925 \f
926
927 ;;;; Semaphores
928
929 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
930   #!+sb-doc
931   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
932 should be considered an implementation detail, and may change in the
933 future."
934   (name    nil :type (or null thread-name))
935   (%count    0 :type (integer 0))
936   (waitcount 0 :type sb!vm:word)
937   (mutex (make-mutex))
938   (queue (make-waitqueue)))
939
940 (setf (fdocumentation 'semaphore-name 'function)
941       "The name of the semaphore INSTANCE. Setfable.")
942
943 (declaim (inline semaphore-count))
944 (defun semaphore-count (instance)
945   "Returns the current count of the semaphore INSTANCE."
946   (barrier (:read))
947   (semaphore-%count instance))
948
949 (defun make-semaphore (&key name (count 0))
950   #!+sb-doc
951   "Create a semaphore with the supplied COUNT and NAME."
952   (%make-semaphore name count))
953
954 (defun wait-on-semaphore (semaphore)
955   #!+sb-doc
956   "Decrement the count of SEMAPHORE if the count would not be
957 negative. Else blocks until the semaphore can be decremented."
958   ;; A more direct implementation based directly on futexes should be
959   ;; possible.
960   ;;
961   ;; We need to disable interrupts so that we don't forget to
962   ;; decrement the waitcount (which would happen if an asynch
963   ;; interrupt should catch us on our way out from the loop.)
964   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
965     ;; Quick check: is it positive? If not, enter the wait loop.
966     (let ((count (semaphore-%count semaphore)))
967       (if (plusp count)
968           (setf (semaphore-%count semaphore) (1- count))
969           (unwind-protect
970                (progn
971                  ;; Need to use ATOMIC-INCF despite the lock, because on our
972                  ;; way out from here we might not be locked anymore -- so
973                  ;; another thread might be tweaking this in parallel using
974                  ;; ATOMIC-DECF. No danger over overflow, since there it
975                  ;; at most one increment per thread waiting on the semaphore.
976                  (sb!ext:atomic-incf (semaphore-waitcount semaphore))
977                  (loop until (plusp (setf count (semaphore-%count semaphore)))
978                        do (condition-wait (semaphore-queue semaphore)
979                                           (semaphore-mutex semaphore)))
980                  (setf (semaphore-%count semaphore) (1- count)))
981             ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
982             ;; may unwind without the lock being held due to timeouts.
983             (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
984
985 (defun try-semaphore (semaphore &optional (n 1))
986   #!+sb-doc
987   "Try to decrement the count of SEMAPHORE by N. If the count were to
988 become negative, punt and return NIL, otherwise return true."
989   (declare (type (integer 1) n))
990   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
991     (let ((new-count (- (semaphore-%count semaphore) n)))
992       (when (not (minusp new-count))
993         (setf (semaphore-%count semaphore) new-count)))))
994
995 (defun signal-semaphore (semaphore &optional (n 1))
996   #!+sb-doc
997   "Increment the count of SEMAPHORE by N. If there are threads waiting
998 on this semaphore, then N of them is woken up."
999   (declare (type (integer 1) n))
1000   ;; Need to disable interrupts so that we don't lose a wakeup after
1001   ;; we have incremented the count.
1002   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1003     (let ((waitcount (semaphore-waitcount semaphore))
1004           (count (incf (semaphore-%count semaphore) n)))
1005       (when (plusp waitcount)
1006         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1007 \f
1008
1009 ;;;; Job control, independent listeners
1010
1011 (defstruct session
1012   (lock (make-mutex :name "session lock"))
1013   (threads nil)
1014   (interactive-threads nil)
1015   (interactive-threads-queue (make-waitqueue)))
1016
1017 (defvar *session* nil)
1018
1019 ;;; The debugger itself tries to acquire the session lock, don't let
1020 ;;; funny situations (like getting a sigint while holding the session
1021 ;;; lock) occur. At the same time we need to allow interrupts while
1022 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1023 ;;; be interruptible.
1024 ;;;
1025 ;;; Take care: we sometimes need to obtain the session lock while
1026 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1027 ;;; _after_ getting a session lock! (Deadlock risk.)
1028 ;;;
1029 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1030 ;;; like the above.
1031 (defmacro with-session-lock ((session) &body body)
1032   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1033      ,@body))
1034
1035 (defun new-session ()
1036   (make-session :threads (list *current-thread*)
1037                 :interactive-threads (list *current-thread*)))
1038
1039 (defun init-job-control ()
1040   (/show0 "Entering INIT-JOB-CONTROL")
1041   (setf *session* (new-session))
1042   (/show0 "Exiting INIT-JOB-CONTROL"))
1043
1044 (defun %delete-thread-from-session (thread session)
1045   (with-session-lock (session)
1046     (setf (session-threads session)
1047           (delete thread (session-threads session))
1048           (session-interactive-threads session)
1049           (delete thread (session-interactive-threads session)))))
1050
1051 (defun call-with-new-session (fn)
1052   (%delete-thread-from-session *current-thread* *session*)
1053   (let ((*session* (new-session)))
1054     (funcall fn)))
1055
1056 (defmacro with-new-session (args &body forms)
1057   (declare (ignore args))               ;for extensibility
1058   (sb!int:with-unique-names (fb-name)
1059     `(labels ((,fb-name () ,@forms))
1060       (call-with-new-session (function ,fb-name)))))
1061
1062 ;;; Remove thread from its session, if it has one.
1063 #!+sb-thread
1064 (defun handle-thread-exit (thread)
1065   (/show0 "HANDLING THREAD EXIT")
1066   ;; Lisp-side cleanup
1067   (with-all-threads-lock
1068     (setf (thread-%alive-p thread) nil)
1069     (setf (thread-os-thread thread) nil)
1070     (setq *all-threads* (delete thread *all-threads*))
1071     (when *session*
1072       (%delete-thread-from-session thread *session*))))
1073
1074 (defun terminate-session ()
1075   #!+sb-doc
1076   "Kill all threads in session except for this one.  Does nothing if current
1077 thread is not the foreground thread."
1078   ;; FIXME: threads created in other threads may escape termination
1079   (let ((to-kill
1080          (with-session-lock (*session*)
1081            (and (eq *current-thread*
1082                     (car (session-interactive-threads *session*)))
1083                 (session-threads *session*)))))
1084     ;; do the kill after dropping the mutex; unwind forms in dying
1085     ;; threads may want to do session things
1086     (dolist (thread to-kill)
1087       (unless (eq thread *current-thread*)
1088         ;; terminate the thread but don't be surprised if it has
1089         ;; exited in the meantime
1090         (handler-case (terminate-thread thread)
1091           (interrupt-thread-error ()))))))
1092
1093 ;;; called from top of invoke-debugger
1094 (defun debugger-wait-until-foreground-thread (stream)
1095   "Returns T if thread had been running in background, NIL if it was
1096 interactive."
1097   (declare (ignore stream))
1098   #!-sb-thread nil
1099   #!+sb-thread
1100   (prog1
1101       (with-session-lock (*session*)
1102         (not (member *current-thread*
1103                      (session-interactive-threads *session*))))
1104     (get-foreground)))
1105
1106 (defun get-foreground ()
1107   #!-sb-thread t
1108   #!+sb-thread
1109   (let ((was-foreground t))
1110     (loop
1111      (/show0 "Looping in GET-FOREGROUND")
1112      (with-session-lock (*session*)
1113        (let ((int-t (session-interactive-threads *session*)))
1114          (when (eq (car int-t) *current-thread*)
1115            (unless was-foreground
1116              (format *query-io* "Resuming thread ~A~%" *current-thread*))
1117            (return-from get-foreground t))
1118          (setf was-foreground nil)
1119          (unless (member *current-thread* int-t)
1120            (setf (cdr (last int-t))
1121                  (list *current-thread*)))
1122          (condition-wait
1123           (session-interactive-threads-queue *session*)
1124           (session-lock *session*)))))))
1125
1126 (defun release-foreground (&optional next)
1127   #!+sb-doc
1128   "Background this thread.  If NEXT is supplied, arrange for it to
1129 have the foreground next."
1130   #!-sb-thread (declare (ignore next))
1131   #!-sb-thread nil
1132   #!+sb-thread
1133   (with-session-lock (*session*)
1134     (when (rest (session-interactive-threads *session*))
1135       (setf (session-interactive-threads *session*)
1136             (delete *current-thread* (session-interactive-threads *session*))))
1137     (when next
1138       (setf (session-interactive-threads *session*)
1139             (list* next
1140                    (delete next (session-interactive-threads *session*)))))
1141     (condition-broadcast (session-interactive-threads-queue *session*))))
1142
1143 (defun foreground-thread ()
1144   (car (session-interactive-threads *session*)))
1145
1146 (defun make-listener-thread (tty-name)
1147   (assert (probe-file tty-name))
1148   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1149          (out (sb!unix:unix-dup in))
1150          (err (sb!unix:unix-dup in)))
1151     (labels ((thread-repl ()
1152                (sb!unix::unix-setsid)
1153                (let* ((sb!impl::*stdin*
1154                        (make-fd-stream in :input t :buffering :line
1155                                        :dual-channel-p t))
1156                       (sb!impl::*stdout*
1157                        (make-fd-stream out :output t :buffering :line
1158                                               :dual-channel-p t))
1159                       (sb!impl::*stderr*
1160                        (make-fd-stream err :output t :buffering :line
1161                                               :dual-channel-p t))
1162                       (sb!impl::*tty*
1163                        (make-fd-stream err :input t :output t
1164                                               :buffering :line
1165                                               :dual-channel-p t))
1166                       (sb!impl::*descriptor-handlers* nil))
1167                  (with-new-session ()
1168                    (unwind-protect
1169                         (sb!impl::toplevel-repl nil)
1170                      (sb!int:flush-standard-output-streams))))))
1171       (make-thread #'thread-repl))))
1172 \f
1173
1174 ;;;; The beef
1175
1176 (defun make-thread (function &key name arguments)
1177   #!+sb-doc
1178   "Create a new thread of NAME that runs FUNCTION with the argument
1179 list designator provided (defaults to no argument). When the function
1180 returns the thread exits. The return values of FUNCTION are kept
1181 around and can be retrieved by JOIN-THREAD."
1182   #!-sb-thread (declare (ignore function name arguments))
1183   #!-sb-thread (error "Not supported in unithread builds.")
1184   #!+sb-thread (assert (or (atom arguments)
1185                            (null (cdr (last arguments))))
1186                        (arguments)
1187                        "Argument passed to ~S, ~S, is an improper list."
1188                        'make-thread arguments)
1189   #!+sb-thread
1190   (let* ((thread (%make-thread :name name))
1191          (setup-sem (make-semaphore :name "Thread setup semaphore"))
1192          (real-function (coerce function 'function))
1193          (arguments     (if (listp arguments)
1194                             arguments
1195                             (list arguments)))
1196          (initial-function
1197           (named-lambda initial-thread-function ()
1198             ;; In time we'll move some of the binding presently done in C
1199             ;; here too.
1200             ;;
1201             ;; KLUDGE: Here we have a magic list of variables that are
1202             ;; not thread-safe for one reason or another.  As people
1203             ;; report problems with the thread safety of certain
1204             ;; variables, (e.g. "*print-case* in multiple threads
1205             ;; broken", sbcl-devel 2006-07-14), we add a few more
1206             ;; bindings here.  The Right Thing is probably some variant
1207             ;; of Allegro's *cl-default-special-bindings*, as that is at
1208             ;; least accessible to users to secure their own libraries.
1209             ;;   --njf, 2006-07-15
1210             ;;
1211             ;; As it is, this lambda must not cons until we are ready
1212             ;; to run GC. Be very careful.
1213             (let* ((*current-thread* thread)
1214                    (*restart-clusters* nil)
1215                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
1216                    (*condition-restarts* nil)
1217                    (sb!impl::*deadline* nil)
1218                    (sb!impl::*deadline-seconds* nil)
1219                    (sb!impl::*step-out* nil)
1220                    ;; internal printer variables
1221                    (sb!impl::*previous-case* nil)
1222                    (sb!impl::*previous-readtable-case* nil)
1223                    (sb!impl::*internal-symbol-output-fun* nil)
1224                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
1225               ;; Binding from C
1226               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1227               (setf (thread-os-thread thread) (current-thread-os-thread))
1228               (with-mutex ((thread-result-lock thread))
1229                 (with-all-threads-lock
1230                   (push thread *all-threads*))
1231                 (with-session-lock (*session*)
1232                   (push thread (session-threads *session*)))
1233                 (setf (thread-%alive-p thread) t)
1234                 (signal-semaphore setup-sem)
1235                 ;; can't use handling-end-of-the-world, because that flushes
1236                 ;; output streams, and we don't necessarily have any (or we
1237                 ;; could be sharing them)
1238                 (catch 'sb!impl::toplevel-catcher
1239                   (catch 'sb!impl::%end-of-the-world
1240                     (with-simple-restart
1241                         (terminate-thread
1242                          (format nil
1243                                  "~~@<Terminate this thread (~A)~~@:>"
1244                                  *current-thread*))
1245                       (without-interrupts
1246                         (unwind-protect
1247                              (with-local-interrupts
1248                                ;; Now that most things have a chance
1249                                ;; to work properly without messing up
1250                                ;; other threads, it's time to enable
1251                                ;; signals.
1252                                (sb!unix::unblock-deferrable-signals)
1253                                (setf (thread-result thread)
1254                                      (cons t
1255                                            (multiple-value-list
1256                                             (apply real-function arguments))))
1257                                ;; Try to block deferrables. An
1258                                ;; interrupt may unwind it, but for a
1259                                ;; normal exit it prevents interrupt
1260                                ;; loss.
1261                                (block-deferrable-signals))
1262                           ;; We're going down, can't handle interrupts
1263                           ;; sanely anymore. GC remains enabled.
1264                           (block-deferrable-signals)
1265                           ;; We don't want to run interrupts in a dead
1266                           ;; thread when we leave WITHOUT-INTERRUPTS.
1267                           ;; This potentially causes important
1268                           ;; interupts to be lost: SIGINT comes to
1269                           ;; mind.
1270                           (setq *interrupt-pending* nil)
1271                           (handle-thread-exit thread))))))))
1272             (values))))
1273     ;; If the starting thread is stopped for gc before it signals the
1274     ;; semaphore then we'd be stuck.
1275     (assert (not *gc-inhibit*))
1276     ;; Keep INITIAL-FUNCTION pinned until the child thread is
1277     ;; initialized properly. Wrap the whole thing in
1278     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1279     ;; thread.
1280     (without-interrupts
1281       (with-pinned-objects (initial-function)
1282         (let ((os-thread
1283                (%create-thread
1284                 (get-lisp-obj-address initial-function))))
1285           (when (zerop os-thread)
1286             (error "Can't create a new thread"))
1287           (wait-on-semaphore setup-sem)
1288           thread)))))
1289
1290 (defun join-thread (thread &key (default nil defaultp))
1291   #!+sb-doc
1292   "Suspend current thread until THREAD exits. Returns the result
1293 values of the thread function. If the thread does not exit normally,
1294 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
1295   (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
1296     (cond ((car (thread-result thread))
1297            (return-from join-thread
1298              (values-list (cdr (thread-result thread)))))
1299           (defaultp
1300            (return-from join-thread default))))
1301   (error 'join-thread-error :thread thread))
1302
1303 (defun destroy-thread (thread)
1304   #!+sb-doc
1305   "Deprecated. Same as TERMINATE-THREAD."
1306   (terminate-thread thread))
1307
1308 (defmacro with-interruptions-lock ((thread) &body body)
1309   `(with-system-mutex ((thread-interruptions-lock ,thread))
1310      ,@body))
1311
1312 ;;; Called from the signal handler.
1313 #!-win32
1314 (defun run-interruption ()
1315   (let ((interruption (with-interruptions-lock (*current-thread*)
1316                         (pop (thread-interruptions *current-thread*)))))
1317     ;; If there is more to do, then resignal and let the normal
1318     ;; interrupt deferral mechanism take care of the rest. From the
1319     ;; OS's point of view the signal we are in the handler for is no
1320     ;; longer pending, so the signal will not be lost.
1321     (when (thread-interruptions *current-thread*)
1322       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1323     (when interruption
1324       (funcall interruption))))
1325
1326 (defun interrupt-thread (thread function)
1327   #!+sb-doc
1328   "Interrupt the live THREAD and make it run FUNCTION. A moderate
1329 degree of care is expected for use of INTERRUPT-THREAD, due to its
1330 nature: if you interrupt a thread that was holding important locks
1331 then do something that turns out to need those locks, you probably
1332 won't like the effect. FUNCTION runs with interrupts disabled, but
1333 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1334 enable interrupts (GET-MUTEX when contended, for instance) so the
1335 first thing to do is usually a WITH-INTERRUPTS or a
1336 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1337 run in same the order they were sent."
1338   #!+win32
1339   (declare (ignore thread))
1340   #!+win32
1341   (with-interrupt-bindings
1342     (with-interrupts (funcall function)))
1343   #!-win32
1344   (let ((os-thread (thread-os-thread thread)))
1345     (cond ((not os-thread)
1346            (error 'interrupt-thread-error :thread thread))
1347           (t
1348            (with-interruptions-lock (thread)
1349              ;; Append to the end of the interruptions queue. It's
1350              ;; O(N), but it does not hurt to slow interruptors down a
1351              ;; bit when the queue gets long.
1352              (setf (thread-interruptions thread)
1353                    (append (thread-interruptions thread)
1354                            (list (lambda ()
1355                                    (without-interrupts
1356                                      (allow-with-interrupts
1357                                        (funcall function))))))))
1358            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1359              (error 'interrupt-thread-error :thread thread))))))
1360
1361 (defun terminate-thread (thread)
1362   #!+sb-doc
1363   "Terminate the thread identified by THREAD, by causing it to run
1364 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1365   (interrupt-thread thread 'sb!ext:quit))
1366
1367 (define-alien-routine "thread_yield" int)
1368
1369 #!+sb-doc
1370 (setf (fdocumentation 'thread-yield 'function)
1371       "Yield the processor to other threads.")
1372
1373 ;;; internal use only.  If you think you need to use these, either you
1374 ;;; are an SBCL developer, are doing something that you should discuss
1375 ;;; with an SBCL developer first, or are doing something that you
1376 ;;; should probably discuss with a professional psychiatrist first
1377 #!+sb-thread
1378 (progn
1379   (defun %thread-sap (thread)
1380     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1381           (target (thread-os-thread thread)))
1382       (loop
1383         (when (sap= thread-sap (int-sap 0)) (return nil))
1384         (let ((os-thread (sap-ref-word thread-sap
1385                                        (* sb!vm:n-word-bytes
1386                                           sb!vm::thread-os-thread-slot))))
1387           (when (= os-thread target) (return thread-sap))
1388           (setf thread-sap
1389                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1390                                            sb!vm::thread-next-slot)))))))
1391
1392   (defun %symbol-value-in-thread (symbol thread)
1393     ;; Prevent the thread from dying completely while we look for the TLS
1394     ;; area...
1395     (with-all-threads-lock
1396       (loop
1397         (if (thread-alive-p thread)
1398             (let* ((epoch sb!kernel::*gc-epoch*)
1399                    (offset (sb!kernel:get-lisp-obj-address
1400                             (sb!vm::symbol-tls-index symbol)))
1401                    (tl-val (sap-ref-word (%thread-sap thread) offset)))
1402               (cond ((zerop offset)
1403                      (return (values nil :no-tls-value)))
1404                     ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1405                          (eql tl-val sb!vm:unbound-marker-widetag))
1406                      (return (values nil :unbound-in-thread)))
1407                     (t
1408                      (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1409                        ;; The value we constructed may be invalid if a GC has
1410                        ;; occurred. That is harmless, though, since OBJ is
1411                        ;; either in a register or on stack, and we are
1412                        ;; conservative on both on GENCGC -- so a bogus object
1413                        ;; is safe here as long as we don't return it. If we
1414                        ;; ever port threads to a non-conservative GC we must
1415                        ;; pin the TL-VAL address before constructing OBJ, or
1416                        ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1417                        ;;
1418                        ;; The reason we don't just rely on TL-VAL pinning the
1419                        ;; object is that the call to MAKE-LISP-OBJ may cause
1420                        ;; bignum allocation, at which point TL-VAL might not
1421                        ;; be alive anymore -- hence the epoch check.
1422                        (when (eq epoch sb!kernel::*gc-epoch*)
1423                          (if ok
1424                              (return (values obj :ok))
1425                              (return (values obj :invalid-tls-value))))))))
1426             (return (values nil :thread-dead))))))
1427
1428   (defun %set-symbol-value-in-thread (symbol thread value)
1429     (with-pinned-objects (value)
1430       ;; Prevent the thread from dying completely while we look for the TLS
1431       ;; area...
1432       (with-all-threads-lock
1433         (if (thread-alive-p thread)
1434             (let ((offset (sb!kernel:get-lisp-obj-address
1435                            (sb!vm::symbol-tls-index symbol))))
1436               (cond ((zerop offset)
1437                      (values nil :no-tls-value))
1438                     (t
1439                      (setf (sap-ref-word (%thread-sap thread) offset)
1440                            (get-lisp-obj-address value))
1441                      (values value :ok))))
1442             (values nil :thread-dead)))))
1443
1444   (define-alien-variable tls-index-start unsigned-int)
1445
1446   ;; Get values from the TLS area of the current thread.
1447   (defun %thread-local-references ()
1448     (without-gcing
1449       (let ((sap (%thread-sap *current-thread*)))
1450         (loop for index from tls-index-start
1451                 below (symbol-value 'sb!vm::*free-tls-index*)
1452               for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1453               for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1454               unless (or (not ok)
1455                          (typep obj '(or fixnum character))
1456                          (member value
1457                                  '(#.sb!vm:no-tls-value-marker-widetag
1458                                    #.sb!vm:unbound-marker-widetag))
1459                          (member obj seen :test #'eq))
1460                 collect obj into seen
1461               finally (return seen))))))
1462
1463 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1464   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1465 on success.
1466
1467 If the value cannot be retrieved (because the thread has exited or because it
1468 has no local binding for NAME) and ERRORP is true signals an error of type
1469 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1470 NIL, and a secondary value of NIL.
1471
1472 Can also be used with SETF to change the thread-local value of SYMBOL.
1473
1474 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1475 mechanism for inter-thread communication."
1476   (declare (symbol symbol) (thread thread))
1477   #!+sb-thread
1478   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1479     (if (eq :ok status)
1480         (values res t)
1481         (if errorp
1482             (error 'symbol-value-in-thread-error
1483                    :name symbol
1484                    :thread thread
1485                    :info (list :read status))
1486             (values nil nil))))
1487   #!-sb-thread
1488   (if (boundp symbol)
1489       (values (symbol-value symbol) t)
1490       (if errorp
1491           (error 'symbol-value-in-thread-error
1492                  :name symbol
1493                  :thread thread
1494                  :info (list :read :unbound-in-thread))
1495           (values nil nil))))
1496
1497 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1498   (declare (symbol symbol) (thread thread))
1499   #!+sb-thread
1500   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1501     (if (eq :ok status)
1502         (values res t)
1503         (if errorp
1504             (error 'symbol-value-in-thread-error
1505                    :name symbol
1506                    :thread thread
1507                    :info (list :write status))
1508             (values nil nil))))
1509   #!-sb-thread
1510   (if (boundp symbol)
1511       (values (setf (symbol-value symbol) value) t)
1512       (if errorp
1513           (error 'symbol-value-in-thread-error
1514                  :name symbol
1515                  :thread thread
1516                  :info (list :write :unbound-in-thread))
1517           (values nil nil))))
1518
1519 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1520   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1521 \f
1522
1523 ;;;; Stepping
1524
1525 (defun thread-stepping ()
1526   (make-lisp-obj
1527    (sap-ref-word (current-thread-sap)
1528                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1529
1530 (defun (setf thread-stepping) (value)
1531   (setf (sap-ref-word (current-thread-sap)
1532                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1533         (get-lisp-obj-address value)))