1.0.24.26: fix release spinlock
[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 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
15 ;;; necessary because threads are only supported with the conservative
16 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
17 ;;; are treated as references.
18
19 ;;; set the doc here because in early-thread FDOCUMENTATION is not
20 ;;; available, yet
21 #!+sb-doc
22 (setf (fdocumentation '*current-thread* 'variable)
23       "Bound in each thread to the thread itself.")
24
25 (defstruct (thread (:constructor %make-thread))
26   #!+sb-doc
27   "Thread type. Do not rely on threads being structs as it may change
28 in future versions."
29   name
30   %alive-p
31   os-thread
32   interruptions
33   (interruptions-lock (make-mutex :name "thread interruptions lock"))
34   result
35   (result-lock (make-mutex :name "thread result lock")))
36
37 #!+sb-doc
38 (setf (fdocumentation 'thread-name 'function)
39       "The name of the thread. Setfable.")
40
41 (def!method print-object ((thread thread) stream)
42   (print-unreadable-object (thread stream :type t :identity t)
43     (let* ((cookie (list thread))
44            (info (if (thread-alive-p thread)
45                      :running
46                      (multiple-value-list (join-thread thread :default cookie))))
47            (state (if (eq :running info)
48                       info
49                       (if (eq cookie (car info))
50                           :aborted
51                           :finished)))
52            (values (when (eq :finished state) info)))
53       (format stream "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
54               (thread-name thread)
55               (eq :finished state)
56               state
57               values))))
58
59 (defun thread-alive-p (thread)
60   #!+sb-doc
61   "Check if THREAD is running."
62   (thread-%alive-p thread))
63
64 ;; A thread is eligible for gc iff it has finished and there are no
65 ;; more references to it. This list is supposed to keep a reference to
66 ;; all running threads.
67 (defvar *all-threads* ())
68 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
69
70 (defvar *default-alloc-signal* nil)
71
72 (defmacro with-all-threads-lock (&body body)
73   `(with-system-mutex (*all-threads-lock*)
74      ,@body))
75
76 (defun list-all-threads ()
77   #!+sb-doc
78   "Return a list of the live threads."
79   (with-all-threads-lock
80     (copy-list *all-threads*)))
81
82 (declaim (inline current-thread-sap))
83 (defun current-thread-sap ()
84   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
85
86 (declaim (inline current-thread-os-thread))
87 (defun current-thread-os-thread ()
88   (sap-int
89    (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
90
91 (defun init-initial-thread ()
92   (/show0 "Entering INIT-INITIAL-THREAD")
93   (let ((initial-thread (%make-thread :name "initial thread"
94                                       :%alive-p t
95                                       :os-thread (current-thread-os-thread))))
96     (setq *current-thread* initial-thread)
97     ;; Either *all-threads* is empty or it contains exactly one thread
98     ;; in case we are in reinit since saving core with multiple
99     ;; threads doesn't work.
100     (setq *all-threads* (list initial-thread))))
101
102 ;;;;
103
104 #!+sb-thread
105 (progn
106   ;; FIXME it would be good to define what a thread id is or isn't
107   ;; (our current assumption is that it's a fixnum).  It so happens
108   ;; that on Linux it's a pid, but it might not be on posix thread
109   ;; implementations.
110   (define-alien-routine ("create_thread" %create-thread)
111       unsigned-long (lisp-fun-address unsigned-long))
112
113   (define-alien-routine "signal_interrupt_thread"
114       integer (os-thread unsigned-long))
115
116   (define-alien-routine "block_deferrable_signals"
117       void)
118
119   #!+sb-lutex
120   (progn
121     (declaim (inline %lutex-init %lutex-wait %lutex-wake
122                      %lutex-lock %lutex-unlock))
123
124     (define-alien-routine ("lutex_init" %lutex-init)
125         int (lutex unsigned-long))
126
127     (define-alien-routine ("lutex_wait" %lutex-wait)
128         int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
129
130     (define-alien-routine ("lutex_wake" %lutex-wake)
131         int (lutex unsigned-long) (n int))
132
133     (define-alien-routine ("lutex_lock" %lutex-lock)
134         int (lutex unsigned-long))
135
136     (define-alien-routine ("lutex_trylock" %lutex-trylock)
137         int (lutex unsigned-long))
138
139     (define-alien-routine ("lutex_unlock" %lutex-unlock)
140         int (lutex unsigned-long))
141
142     (define-alien-routine ("lutex_destroy" %lutex-destroy)
143         int (lutex unsigned-long))
144
145     ;; FIXME: Defining a whole bunch of alien-type machinery just for
146     ;; passing primitive lutex objects directly to foreign functions
147     ;; doesn't seem like fun right now. So instead we just manually
148     ;; pin the lutex, get its address, and let the callee untag it.
149     (defmacro with-lutex-address ((name lutex) &body body)
150       `(let ((,name ,lutex))
151          (with-pinned-objects (,name)
152            (let ((,name (get-lisp-obj-address ,name)))
153              ,@body))))
154
155     (defun make-lutex ()
156       (/show0 "Entering MAKE-LUTEX")
157       ;; Suppress GC until the lutex has been properly registered with
158       ;; the GC.
159       (without-gcing
160         (let ((lutex (sb!vm::%make-lutex)))
161           (/show0 "LUTEX=..")
162           (/hexstr lutex)
163           (with-lutex-address (lutex lutex)
164             (%lutex-init lutex))
165           lutex))))
166
167   #!-sb-lutex
168   (progn
169     (declaim (inline futex-wait %futex-wait futex-wake))
170
171     (define-alien-routine ("futex_wait" %futex-wait)
172         int (word unsigned-long) (old-value unsigned-long)
173         (to-sec long) (to-usec unsigned-long))
174
175     (defun futex-wait (word old to-sec to-usec)
176       (with-interrupts
177         (%futex-wait word old to-sec to-usec)))
178
179     (define-alien-routine "futex_wake"
180         int (word unsigned-long) (n unsigned-long))))
181
182 ;;; used by debug-int.lisp to access interrupt contexts
183 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
184 #!-sb-thread
185 (defun sb!vm::current-thread-offset-sap (n)
186   (declare (type (unsigned-byte 27) n))
187   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
188                (* n sb!vm:n-word-bytes)))
189
190 #!+sb-thread
191 (defun sb!vm::current-thread-offset-sap (n)
192   (declare (type (unsigned-byte 27) n))
193   (sb!vm::current-thread-offset-sap n))
194
195 (declaim (inline get-spinlock release-spinlock))
196
197 ;; Should always be called with interrupts disabled.
198 (defun get-spinlock (spinlock)
199   (declare (optimize (speed 3) (safety 0)))
200   (let* ((new *current-thread*)
201          (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
202     (when old
203       (when (eq old new)
204         (error "Recursive lock attempt on ~S." spinlock))
205       #!+sb-thread
206       (flet ((cas ()
207                (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
208                    (thread-yield)
209                    (return-from get-spinlock t))))
210         (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
211             ;; If interrupts are enabled, but we are allowed to enabled them,
212             ;; check for pending interrupts every once in a while.
213             (loop
214               (loop repeat 128 do (cas)) ; 128 is arbitrary here
215               (sb!unix::%check-interrupts))
216             (loop (cas)))))
217     t))
218
219 (defun release-spinlock (spinlock)
220   (declare (optimize (speed 3) (safety 0)))
221   ;; Simply setting SPINLOCK-VALUE to NIL is not enough as it does not
222   ;; propagate to other processors, plus without a memory barrier the
223   ;; CPU might reorder instructions allowing code from the critical
224   ;; section to leak out. Use COMPARE-AND-SWAP for the memory barrier
225   ;; effect and do some sanity checking while we are at it.
226   (unless (eq *current-thread*
227               (sb!ext:compare-and-swap (spinlock-value spinlock)
228                                        *current-thread* nil))
229     (error "Only the owner can release the spinlock ~S." spinlock)))
230
231 ;;;; mutexes
232
233 #!+sb-doc
234 (setf (fdocumentation 'make-mutex 'function)
235       "Create a mutex."
236       (fdocumentation 'mutex-name 'function)
237       "The name of the mutex. Setfable.")
238
239 #!+(and sb-thread (not sb-lutex))
240 (progn
241   (define-structure-slot-addressor mutex-state-address
242       :structure mutex
243       :slot state)
244   ;; Important: current code assumes these are fixnums or other
245   ;; lisp objects that don't need pinning.
246   (defconstant +lock-free+ 0)
247   (defconstant +lock-taken+ 1)
248   (defconstant +lock-contested+ 2))
249
250 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
251   #!+sb-doc
252   "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
253 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
254 non-NIL and the mutex is in use, sleep until it is available.
255
256 Note: using GET-MUTEX to assign a MUTEX to another thread then the
257 current one is not recommended, and liable to be deprecated.
258
259 GET-MUTEX is not interrupt safe. The correct way to call it is:
260
261  (WITHOUT-INTERRUPTS
262    ...
263    (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
264    ...)
265
266 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
267 call while the mutex is in an inconsistent state while
268 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
269
270 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
271 directly."
272   (declare (type mutex mutex) (optimize (speed 3))
273            #!-sb-thread (ignore waitp))
274   (unless new-owner
275     (setq new-owner *current-thread*))
276   (let ((old (mutex-%owner mutex)))
277     (when (eq new-owner old)
278       (error "Recursive lock attempt ~S." mutex))
279     #!-sb-thread
280     (if old
281         (error "Strange deadlock on ~S in an unithreaded build?" mutex)
282         (setf (mutex-%owner mutex) new-owner)))
283   #!+sb-thread
284   (progn
285     ;; FIXME: Lutexes do not currently support deadlines, as at least
286     ;; on Darwin pthread_foo_timedbar functions are not supported:
287     ;; this means that we probably need to use the Carbon multiprocessing
288     ;; functions on Darwin.
289     ;;
290     ;; FIXME: This is definitely not interrupt safe: what happens if
291     ;; we get hit (1) during the lutex calls (ok, they may be safe,
292     ;; but has that been checked?) (2) after the lutex call, but
293     ;; before setting the mutex owner.
294     #!+sb-lutex
295     (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
296                    (if waitp
297                        (with-interrupts (%lutex-lock lutex))
298                        (%lutex-trylock lutex))))
299       (setf (mutex-%owner mutex) new-owner)
300       t)
301     #!-sb-lutex
302     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
303                                         +lock-free+
304                                         +lock-taken+)))
305       (unless (or (eql +lock-free+ old) (not waitp))
306         (tagbody
307          :retry
308            (when (or (eql +lock-contested+ old)
309                      (not (eql +lock-free+
310                                (sb!ext:compare-and-swap (mutex-state mutex)
311                                                         +lock-taken+
312                                                         +lock-contested+))))
313              ;; Wait on the contested lock.
314              (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
315                (when (= 1 (with-pinned-objects (mutex)
316                             (futex-wait (mutex-state-address mutex)
317                                         (get-lisp-obj-address +lock-contested+)
318                                         (or to-sec -1)
319                                         (or to-usec 0))))
320                  (signal-deadline))))
321            (setf old (sb!ext:compare-and-swap (mutex-state mutex)
322                                               +lock-free+
323                                               +lock-contested+))
324            ;; Did we get it?
325            (unless (eql +lock-free+ old)
326              (go :retry))))
327       (cond ((eql +lock-free+ old)
328              (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
329                                                   nil new-owner)))
330                (when prev
331                  (bug "Old owner in free mutex: ~S" prev))
332                t))
333             (waitp
334              (bug "Failed to acquire lock with WAITP."))))))
335
336 (defun release-mutex (mutex)
337   #!+sb-doc
338   "Release MUTEX by setting it to NIL. Wake up threads waiting for
339 this mutex.
340
341 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
342 around calls to it.
343
344 Signals a WARNING is current thread is not the current owner of the
345 mutex."
346   (declare (type mutex mutex))
347   ;; Order matters: set owner to NIL before releasing state.
348   (let* ((self *current-thread*)
349          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
350     (unless  (eql self old-owner)
351       (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
352       (setf (mutex-%owner mutex) nil)))
353   #!+sb-thread
354   (progn
355     #!+sb-lutex
356     (with-lutex-address (lutex (mutex-lutex mutex))
357       (%lutex-unlock lutex))
358     #!-sb-lutex
359     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
360                                         +lock-taken+ +lock-free+)))
361       (when (eql old +lock-contested+)
362         (sb!ext:compare-and-swap (mutex-state mutex)
363                                  +lock-contested+ +lock-free+)
364         (with-pinned-objects (mutex)
365           (futex-wake (mutex-state-address mutex) 1))))
366     nil))
367
368 ;;;; waitqueues/condition variables
369
370 (defstruct (waitqueue (:constructor %make-waitqueue))
371   #!+sb-doc
372   "Waitqueue type."
373   (name nil :type (or null simple-string))
374   #!+(and sb-lutex sb-thread)
375   (lutex (make-lutex))
376   #!-sb-lutex
377   (data nil))
378
379 (defun make-waitqueue (&key name)
380   #!+sb-doc
381   "Create a waitqueue."
382   (%make-waitqueue :name name))
383
384 #!+sb-doc
385 (setf (fdocumentation 'waitqueue-name 'function)
386       "The name of the waitqueue. Setfable.")
387
388 #!+(and sb-thread (not sb-lutex))
389 (define-structure-slot-addressor waitqueue-data-address
390     :structure waitqueue
391     :slot data)
392
393 (defun condition-wait (queue mutex)
394   #!+sb-doc
395   "Atomically release MUTEX and enqueue ourselves on QUEUE.  Another
396 thread may subsequently notify us using CONDITION-NOTIFY, at which
397 time we reacquire MUTEX and return to the caller."
398   #!-sb-thread (declare (ignore queue))
399   (assert mutex)
400   #!-sb-thread (error "Not supported in unithread builds.")
401   #!+sb-thread
402   (let ((me *current-thread*))
403     (assert (eq me (mutex-%owner mutex)))
404     (/show0 "CONDITION-WAITing")
405     #!+sb-lutex
406     ;; Need to disable interrupts so that we don't miss setting the owner on
407     ;; our way out. (pthread_cond_wait handles the actual re-acquisition.)
408     (without-interrupts
409       (unwind-protect
410            (progn
411              (setf (mutex-%owner mutex) nil)
412              (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
413                (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
414                  (with-local-interrupts
415                    (%lutex-wait queue-lutex-address mutex-lutex-address)))))
416         (setf (mutex-%owner mutex) me)))
417     #!-sb-lutex
418     ;; Need to disable interrupts so that we don't miss grabbing the mutex
419     ;; on our way out.
420     (without-interrupts
421       (unwind-protect
422            (let ((me *current-thread*))
423              ;; FIXME: should we do something to ensure that the result
424              ;; of this setf is visible to all CPUs?
425              (setf (waitqueue-data queue) me)
426              (release-mutex mutex)
427              ;; Now we go to sleep using futex-wait.  If anyone else
428              ;; manages to grab MUTEX and call CONDITION-NOTIFY during
429              ;; this comment, it will change queue->data, and so
430              ;; futex-wait returns immediately instead of sleeping.
431              ;; Ergo, no lost wakeup. We may get spurious wakeups,
432              ;; but that's ok.
433              (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
434                (when (= 1 (with-pinned-objects (queue me)
435                             (allow-with-interrupts
436                               (futex-wait (waitqueue-data-address queue)
437                                           (get-lisp-obj-address me)
438                                           (or to-sec -1) ;; our way if saying "no timeout"
439                                           (or to-usec 0)))))
440                  (signal-deadline))))
441         ;; If we are interrupted while waiting, we should do these things
442         ;; before returning.  Ideally, in the case of an unhandled signal,
443         ;; we should do them before entering the debugger, but this is
444         ;; better than nothing.
445         (get-mutex mutex)))))
446
447 (defun condition-notify (queue &optional (n 1))
448   #!+sb-doc
449   "Notify N threads waiting on QUEUE."
450   #!-sb-thread (declare (ignore queue n))
451   #!-sb-thread (error "Not supported in unithread builds.")
452   #!+sb-thread
453   (declare (type (and fixnum (integer 1)) n))
454   (/show0 "Entering CONDITION-NOTIFY")
455   #!+sb-thread
456   (progn
457     #!+sb-lutex
458     (with-lutex-address (lutex (waitqueue-lutex queue))
459       (%lutex-wake lutex n))
460     ;; no problem if >1 thread notifies during the comment in
461     ;; condition-wait: as long as the value in queue-data isn't the
462     ;; waiting thread's id, it matters not what it is
463     ;; XXX we should do something to ensure that the result of this setf
464     ;; is visible to all CPUs
465     #!-sb-lutex
466     (let ((me *current-thread*))
467       (progn
468         (setf (waitqueue-data queue) me)
469         (with-pinned-objects (queue)
470           (futex-wake (waitqueue-data-address queue) n))))))
471
472 (defun condition-broadcast (queue)
473   #!+sb-doc
474   "Notify all threads waiting on QUEUE."
475   (condition-notify queue
476                     ;; On a 64-bit platform truncating M-P-F to an int results
477                     ;; in -1, which wakes up only one thread.
478                     (ldb (byte 29 0)
479                          most-positive-fixnum)))
480
481 ;;;; semaphores
482
483 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
484   #!+sb-doc
485   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
486 should be considered an implementation detail, and may change in the
487 future."
488   (name nil :type (or null simple-string))
489   (%count 0 :type (integer 0))
490   (waitcount 0 :type (integer 0))
491   (mutex (make-mutex))
492   (queue (make-waitqueue)))
493
494 (setf (fdocumentation 'semaphore-name 'function)
495       "The name of the semaphore INSTANCE. Setfable.")
496
497 (declaim (inline semaphore-count))
498 (defun semaphore-count (instance)
499   "Returns the current count of the semaphore INSTANCE."
500   (semaphore-%count instance))
501
502 (defun make-semaphore (&key name (count 0))
503   #!+sb-doc
504   "Create a semaphore with the supplied COUNT and NAME."
505   (%make-semaphore name count))
506
507 (defun wait-on-semaphore (semaphore)
508   #!+sb-doc
509   "Decrement the count of SEMAPHORE if the count would not be
510 negative. Else blocks until the semaphore can be decremented."
511   ;; A more direct implementation based directly on futexes should be
512   ;; possible.
513   ;;
514   ;; We need to disable interrupts so that we don't forget to decrement the
515   ;; waitcount (which would happen if an asynch interrupt should catch us on
516   ;; our way out from the loop.)
517   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
518     ;; Quick check: is it positive? If not, enter the wait loop.
519     (let ((count (semaphore-%count semaphore)))
520       (if (plusp count)
521           (setf (semaphore-%count semaphore) (1- count))
522           (unwind-protect
523                (progn
524                  (incf (semaphore-waitcount semaphore))
525                  (loop until (plusp (setf count (semaphore-%count semaphore)))
526                        do (condition-wait (semaphore-queue semaphore) (semaphore-mutex semaphore)))
527                  (setf (semaphore-%count semaphore) (1- count)))
528             (decf (semaphore-waitcount semaphore)))))))
529
530 (defun signal-semaphore (semaphore &optional (n 1))
531   #!+sb-doc
532   "Increment the count of SEMAPHORE by N. If there are threads waiting
533 on this semaphore, then N of them is woken up."
534   (declare (type (integer 1) n))
535   ;; Need to disable interrupts so that we don't lose a wakeup after we have
536   ;; incremented the count.
537   (with-system-mutex ((semaphore-mutex semaphore))
538     (let ((waitcount (semaphore-waitcount semaphore))
539           (count (incf (semaphore-%count semaphore) n)))
540       (when (plusp waitcount)
541         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
542
543 ;;;; job control, independent listeners
544
545 (defstruct session
546   (lock (make-mutex :name "session lock"))
547   (threads nil)
548   (interactive-threads nil)
549   (interactive-threads-queue (make-waitqueue)))
550
551 (defvar *session* nil)
552
553 ;;; The debugger itself tries to acquire the session lock, don't let
554 ;;; funny situations (like getting a sigint while holding the session
555 ;;; lock) occur. At the same time we need to allow interrupts while
556 ;;; *waiting* for the session lock for things like GET-FOREGROUND
557 ;;; to be interruptible.
558 ;;;
559 ;;; Take care: we sometimes need to obtain the session lock while holding
560 ;;; on to *ALL-THREADS-LOCK*, so we must _never_ obtain it _after_ getting
561 ;;; a session lock! (Deadlock risk.)
562 ;;;
563 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
564 ;;; the above.
565 (defmacro with-session-lock ((session) &body body)
566   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
567      ,@body))
568
569 (defun new-session ()
570   (make-session :threads (list *current-thread*)
571                 :interactive-threads (list *current-thread*)))
572
573 (defun init-job-control ()
574   (/show0 "Entering INIT-JOB-CONTROL")
575   (setf *session* (new-session))
576   (/show0 "Exiting INIT-JOB-CONTROL"))
577
578 (defun %delete-thread-from-session (thread session)
579   (with-session-lock (session)
580     (setf (session-threads session)
581           (delete thread (session-threads session))
582           (session-interactive-threads session)
583           (delete thread (session-interactive-threads session)))))
584
585 (defun call-with-new-session (fn)
586   (%delete-thread-from-session *current-thread* *session*)
587   (let ((*session* (new-session)))
588     (funcall fn)))
589
590 (defmacro with-new-session (args &body forms)
591   (declare (ignore args))               ;for extensibility
592   (sb!int:with-unique-names (fb-name)
593     `(labels ((,fb-name () ,@forms))
594       (call-with-new-session (function ,fb-name)))))
595
596 ;;; Remove thread from its session, if it has one.
597 #!+sb-thread
598 (defun handle-thread-exit (thread)
599   (/show0 "HANDLING THREAD EXIT")
600   ;; We're going down, can't handle interrupts sanely anymore.
601   ;; GC remains enabled.
602   (block-deferrable-signals)
603   ;; Lisp-side cleanup
604   (with-all-threads-lock
605     (setf (thread-%alive-p thread) nil)
606     (setf (thread-os-thread thread) nil)
607     (setq *all-threads* (delete thread *all-threads*))
608     (when *session*
609       (%delete-thread-from-session thread *session*)))
610   #!+sb-lutex
611   (without-gcing
612     (/show0 "FREEING MUTEX LUTEX")
613     (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
614       (%lutex-destroy lutex))))
615
616 (defun terminate-session ()
617   #!+sb-doc
618   "Kill all threads in session except for this one.  Does nothing if current
619 thread is not the foreground thread."
620   ;; FIXME: threads created in other threads may escape termination
621   (let ((to-kill
622          (with-session-lock (*session*)
623            (and (eq *current-thread*
624                     (car (session-interactive-threads *session*)))
625                 (session-threads *session*)))))
626     ;; do the kill after dropping the mutex; unwind forms in dying
627     ;; threads may want to do session things
628     (dolist (thread to-kill)
629       (unless (eq thread *current-thread*)
630         ;; terminate the thread but don't be surprised if it has
631         ;; exited in the meantime
632         (handler-case (terminate-thread thread)
633           (interrupt-thread-error ()))))))
634
635 ;;; called from top of invoke-debugger
636 (defun debugger-wait-until-foreground-thread (stream)
637   "Returns T if thread had been running in background, NIL if it was
638 interactive."
639   (declare (ignore stream))
640   #!-sb-thread nil
641   #!+sb-thread
642   (prog1
643       (with-session-lock (*session*)
644         (not (member *current-thread*
645                      (session-interactive-threads *session*))))
646     (get-foreground)))
647
648 (defun get-foreground ()
649   #!-sb-thread t
650   #!+sb-thread
651   (let ((was-foreground t))
652     (loop
653      (/show0 "Looping in GET-FOREGROUND")
654      (with-session-lock (*session*)
655        (let ((int-t (session-interactive-threads *session*)))
656          (when (eq (car int-t) *current-thread*)
657            (unless was-foreground
658              (format *query-io* "Resuming thread ~A~%" *current-thread*))
659            (return-from get-foreground t))
660          (setf was-foreground nil)
661          (unless (member *current-thread* int-t)
662            (setf (cdr (last int-t))
663                  (list *current-thread*)))
664          (condition-wait
665           (session-interactive-threads-queue *session*)
666           (session-lock *session*)))))))
667
668 (defun release-foreground (&optional next)
669   #!+sb-doc
670   "Background this thread.  If NEXT is supplied, arrange for it to
671 have the foreground next."
672   #!-sb-thread (declare (ignore next))
673   #!-sb-thread nil
674   #!+sb-thread
675   (with-session-lock (*session*)
676     (when (rest (session-interactive-threads *session*))
677       (setf (session-interactive-threads *session*)
678             (delete *current-thread* (session-interactive-threads *session*))))
679     (when next
680       (setf (session-interactive-threads *session*)
681             (list* next
682                    (delete next (session-interactive-threads *session*)))))
683     (condition-broadcast (session-interactive-threads-queue *session*))))
684
685 (defun foreground-thread ()
686   (car (session-interactive-threads *session*)))
687
688 (defun make-listener-thread (tty-name)
689   (assert (probe-file tty-name))
690   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
691          (out (sb!unix:unix-dup in))
692          (err (sb!unix:unix-dup in)))
693     (labels ((thread-repl ()
694                (sb!unix::unix-setsid)
695                (let* ((sb!impl::*stdin*
696                        (make-fd-stream in :input t :buffering :line
697                                        :dual-channel-p t))
698                       (sb!impl::*stdout*
699                        (make-fd-stream out :output t :buffering :line
700                                               :dual-channel-p t))
701                       (sb!impl::*stderr*
702                        (make-fd-stream err :output t :buffering :line
703                                               :dual-channel-p t))
704                       (sb!impl::*tty*
705                        (make-fd-stream err :input t :output t
706                                               :buffering :line
707                                               :dual-channel-p t))
708                       (sb!impl::*descriptor-handlers* nil))
709                  (with-new-session ()
710                    (unwind-protect
711                         (sb!impl::toplevel-repl nil)
712                      (sb!int:flush-standard-output-streams))))))
713       (make-thread #'thread-repl))))
714
715 ;;;; the beef
716
717 (defun make-thread (function &key name)
718   #!+sb-doc
719   "Create a new thread of NAME that runs FUNCTION. When the function
720 returns the thread exits. The return values of FUNCTION are kept
721 around and can be retrieved by JOIN-THREAD."
722   #!-sb-thread (declare (ignore function name))
723   #!-sb-thread (error "Not supported in unithread builds.")
724   #!+sb-thread
725   (let* ((thread (%make-thread :name name))
726          (setup-sem (make-semaphore :name "Thread setup semaphore"))
727          (real-function (coerce function 'function))
728          (initial-function
729           (lambda ()
730             ;; In time we'll move some of the binding presently done in C
731             ;; here too.
732             ;;
733             ;; KLUDGE: Here we have a magic list of variables that are
734             ;; not thread-safe for one reason or another.  As people
735             ;; report problems with the thread safety of certain
736             ;; variables, (e.g. "*print-case* in multiple threads
737             ;; broken", sbcl-devel 2006-07-14), we add a few more
738             ;; bindings here.  The Right Thing is probably some variant
739             ;; of Allegro's *cl-default-special-bindings*, as that is at
740             ;; least accessible to users to secure their own libraries.
741             ;;   --njf, 2006-07-15
742             (let* ((*current-thread* thread)
743                    (*restart-clusters* nil)
744                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
745                    (*condition-restarts* nil)
746                    (sb!impl::*deadline* nil)
747                    (sb!impl::*step-out* nil)
748                    ;; internal printer variables
749                    (sb!impl::*previous-case* nil)
750                    (sb!impl::*previous-readtable-case* nil)
751                    (empty (vector))
752                    (sb!impl::*merge-sort-temp-vector* empty)
753                    (sb!impl::*zap-array-data-temp* empty)
754                    (sb!impl::*internal-symbol-output-fun* nil)
755                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
756               ;; Binding from C
757               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
758               (setf (thread-os-thread thread) (current-thread-os-thread))
759               (with-mutex ((thread-result-lock thread))
760                 (with-all-threads-lock
761                   (push thread *all-threads*))
762                 (with-session-lock (*session*)
763                   (push thread (session-threads *session*)))
764                 (setf (thread-%alive-p thread) t)
765                 (signal-semaphore setup-sem)
766                 ;; can't use handling-end-of-the-world, because that flushes
767                 ;; output streams, and we don't necessarily have any (or we
768                 ;; could be sharing them)
769                 (catch 'sb!impl::toplevel-catcher
770                   (catch 'sb!impl::%end-of-the-world
771                     (with-simple-restart
772                         (terminate-thread
773                          (format nil
774                                  "~~@<Terminate this thread (~A)~~@:>"
775                                  *current-thread*))
776                       (unwind-protect
777                            (progn
778                              ;; now that most things have a chance to
779                              ;; work properly without messing up other
780                              ;; threads, it's time to enable signals
781                              (sb!unix::reset-signal-mask)
782                              (setf (thread-result thread)
783                                    (cons t
784                                          (multiple-value-list
785                                           (funcall real-function)))))
786                         (handle-thread-exit thread)))))))
787             (values))))
788     ;; Keep INITIAL-FUNCTION pinned until the child thread is
789     ;; initialized properly.
790     (with-pinned-objects (initial-function)
791       (let ((os-thread
792              (%create-thread
793               (get-lisp-obj-address initial-function))))
794         (when (zerop os-thread)
795           (error "Can't create a new thread"))
796         (wait-on-semaphore setup-sem)
797         thread))))
798
799 (define-condition join-thread-error (error)
800   ((thread :reader join-thread-error-thread :initarg :thread))
801   #!+sb-doc
802   (:documentation "Joining thread failed.")
803   (:report (lambda (c s)
804              (format s "Joining thread failed: thread ~A ~
805                         has not returned normally."
806                      (join-thread-error-thread c)))))
807
808 #!+sb-doc
809 (setf (fdocumentation 'join-thread-error-thread 'function)
810       "The thread that we failed to join.")
811
812 (defun join-thread (thread &key (default nil defaultp))
813   #!+sb-doc
814   "Suspend current thread until THREAD exits. Returns the result
815 values of the thread function. If the thread does not exit normally,
816 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
817   (with-mutex ((thread-result-lock thread))
818     (cond ((car (thread-result thread))
819            (values-list (cdr (thread-result thread))))
820           (defaultp
821            default)
822           (t
823            (error 'join-thread-error :thread thread)))))
824
825 (defun destroy-thread (thread)
826   #!+sb-doc
827   "Deprecated. Same as TERMINATE-THREAD."
828   (terminate-thread thread))
829
830 (define-condition interrupt-thread-error (error)
831   ((thread :reader interrupt-thread-error-thread :initarg :thread))
832   #!+sb-doc
833   (:documentation "Interrupting thread failed.")
834   (:report (lambda (c s)
835              (format s "Interrupt thread failed: thread ~A has exited."
836                      (interrupt-thread-error-thread c)))))
837
838 #!+sb-doc
839 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
840       "The thread that was not interrupted.")
841
842 (defmacro with-interruptions-lock ((thread) &body body)
843   `(with-system-mutex ((thread-interruptions-lock ,thread))
844      ,@body))
845
846 ;; Called from the signal handler in C.
847 (defun run-interruption ()
848   (in-interruption ()
849     (loop
850        (let ((interruption (with-interruptions-lock (*current-thread*)
851                              (pop (thread-interruptions *current-thread*)))))
852          (if interruption
853              (with-interrupts
854                (funcall interruption))
855              (return))))))
856
857 ;; The order of interrupt execution is peculiar. If thread A
858 ;; interrupts thread B with I1, I2 and B for some reason receives I1
859 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
860 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
861 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
862 ;; just one scenario, and the order of thread interrupt execution is
863 ;; undefined.
864 (defun interrupt-thread (thread function)
865   #!+sb-doc
866   "Interrupt the live THREAD and make it run FUNCTION. A moderate
867 degree of care is expected for use of INTERRUPT-THREAD, due to its
868 nature: if you interrupt a thread that was holding important locks
869 then do something that turns out to need those locks, you probably
870 won't like the effect."
871   #!-sb-thread (declare (ignore thread))
872   #!-sb-thread
873   (with-interrupt-bindings
874     (with-interrupts (funcall function)))
875   #!+sb-thread
876   (if (eq thread *current-thread*)
877       (with-interrupt-bindings
878         (with-interrupts (funcall function)))
879       (let ((os-thread (thread-os-thread thread)))
880         (cond ((not os-thread)
881                (error 'interrupt-thread-error :thread thread))
882               (t
883                (with-interruptions-lock (thread)
884                  (push function (thread-interruptions thread)))
885                (when (minusp (signal-interrupt-thread os-thread))
886                  (error 'interrupt-thread-error :thread thread)))))))
887
888 (defun terminate-thread (thread)
889   #!+sb-doc
890   "Terminate the thread identified by THREAD, by causing it to run
891 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
892   (interrupt-thread thread 'sb!ext:quit))
893
894 (define-alien-routine "thread_yield" int)
895
896 #!+sb-doc
897 (setf (fdocumentation 'thread-yield 'function)
898       "Yield the processor to other threads.")
899
900 ;;; internal use only.  If you think you need to use these, either you
901 ;;; are an SBCL developer, are doing something that you should discuss
902 ;;; with an SBCL developer first, or are doing something that you
903 ;;; should probably discuss with a professional psychiatrist first
904 #!+sb-thread
905 (progn
906   (defun %thread-sap (thread)
907     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
908           (target (thread-os-thread thread)))
909       (loop
910         (when (sap= thread-sap (int-sap 0)) (return nil))
911         (let ((os-thread (sap-ref-word thread-sap
912                                        (* sb!vm:n-word-bytes
913                                           sb!vm::thread-os-thread-slot))))
914           (when (= os-thread target) (return thread-sap))
915           (setf thread-sap
916                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
917                                            sb!vm::thread-next-slot)))))))
918
919   (defun %symbol-value-in-thread (symbol thread)
920     (tagbody
921        ;; Prevent the dead from dying completely while we look for the TLS area...
922        (with-all-threads-lock
923          (if (thread-alive-p thread)
924              (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
925                     (tl-val (sap-ref-word (%thread-sap thread) offset)))
926                (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
927                    (go :unbound)
928                    (return-from %symbol-value-in-thread (values (make-lisp-obj tl-val) t))))
929              (return-from %symbol-value-in-thread (values nil nil))))
930      :unbound
931        (error "Cannot read thread-local symbol value: ~S unbound in ~S" symbol thread)))
932
933   (defun %set-symbol-value-in-thread (symbol thread value)
934     (tagbody
935        (with-pinned-objects (value)
936          ;; Prevent the dead from dying completely while we look for the TLS area...
937          (with-all-threads-lock
938            (if (thread-alive-p thread)
939                (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
940                       (sap (%thread-sap thread))
941                       (tl-val (sap-ref-word sap offset)))
942                  (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
943                      (go :unbound)
944                      (setf (sap-ref-word sap offset) (get-lisp-obj-address value)))
945                  (return-from %set-symbol-value-in-thread (values value t)))
946                (return-from %set-symbol-value-in-thread (values nil nil)))))
947      :unbound
948        (error "Cannot set thread-local symbol value: ~S unbound in ~S" symbol thread))))
949
950 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
951   (sb!vm::locked-symbol-global-value-add symbol-name delta))
952
953 ;;; Stepping
954
955 (defun thread-stepping ()
956   (make-lisp-obj
957    (sap-ref-word (current-thread-sap)
958                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
959
960 (defun (setf thread-stepping) (value)
961   (setf (sap-ref-word (current-thread-sap)
962                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
963         (get-lisp-obj-address value)))