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