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