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