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