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