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