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