1.0.26.4: less pessimal waitqueues
[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)
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 Signals a WARNING if current thread is not the current owner of the
379 mutex."
380   (declare (type mutex mutex))
381   ;; Order matters: set owner to NIL before releasing state.
382   (let* ((self *current-thread*)
383          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
384     (unless  (eql self old-owner)
385       (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
386       (setf (mutex-%owner mutex) nil)))
387   #!+sb-thread
388   (progn
389     #!+sb-lutex
390     (with-lutex-address (lutex (mutex-lutex mutex))
391       (%lutex-unlock lutex))
392     #!-sb-lutex
393     ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
394     ;; unsigned-byte type this can be used:
395     ;;
396     ;;     (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
397     ;;       (unless (eql old +lock-free+)
398     ;;         (setf (mutex-state mutex) +lock-free+)
399     ;;         (with-pinned-objects (mutex)
400     ;;           (futex-wake (mutex-state-address mutex) 1))))
401     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
402                                         +lock-taken+ +lock-free+)))
403       (when (eql old +lock-contested+)
404         (sb!ext:compare-and-swap (mutex-state mutex)
405                                  +lock-contested+ +lock-free+)
406         (with-pinned-objects (mutex)
407           (futex-wake (mutex-state-address mutex) 1))))
408     nil))
409 \f
410
411 ;;;; Waitqueues/condition variables
412
413 (defstruct (waitqueue (:constructor %make-waitqueue))
414   #!+sb-doc
415   "Waitqueue type."
416   (name nil :type (or null simple-string))
417   #!+(and sb-lutex sb-thread)
418   (lutex (make-lutex))
419   #!-sb-lutex
420   (data nil))
421
422 (defun make-waitqueue (&key name)
423   #!+sb-doc
424   "Create a waitqueue."
425   (%make-waitqueue :name name))
426
427 #!+sb-doc
428 (setf (fdocumentation 'waitqueue-name 'function)
429       "The name of the waitqueue. Setfable.")
430
431 #!+(and sb-thread (not sb-lutex))
432 (define-structure-slot-addressor waitqueue-data-address
433     :structure waitqueue
434     :slot data)
435
436 (defun condition-wait (queue mutex)
437   #!+sb-doc
438   "Atomically release MUTEX and enqueue ourselves on QUEUE.  Another
439 thread may subsequently notify us using CONDITION-NOTIFY, at which
440 time we reacquire MUTEX and return to the caller."
441   #!-sb-thread (declare (ignore queue))
442   (assert mutex)
443   #!-sb-thread (error "Not supported in unithread builds.")
444   #!+sb-thread
445   (let ((me *current-thread*))
446     (assert (eq me (mutex-%owner mutex)))
447     (/show0 "CONDITION-WAITing")
448     #!+sb-lutex
449     ;; Need to disable interrupts so that we don't miss setting the
450     ;; owner on our way out. (pthread_cond_wait handles the actual
451     ;; re-acquisition.)
452     (without-interrupts
453       (unwind-protect
454            (progn
455              (setf (mutex-%owner mutex) nil)
456              (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
457                (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
458                  (with-local-interrupts
459                    (%lutex-wait queue-lutex-address mutex-lutex-address)))))
460         (setf (mutex-%owner mutex) me)))
461     #!-sb-lutex
462     ;; Need to disable interrupts so that we don't miss grabbing the
463     ;; mutex on our way out.
464     (without-interrupts
465       (unwind-protect
466            (let ((me nil))
467              ;; This setf becomes visible to other CPUS due to the
468              ;; usual memory barrier semantics of lock
469              ;; acquire/release.
470              (setf (waitqueue-data queue) me)
471              (release-mutex mutex)
472              ;; Now we go to sleep using futex-wait. If anyone else
473              ;; manages to grab MUTEX and call CONDITION-NOTIFY during
474              ;; this comment, it will change queue->data, and so
475              ;; futex-wait returns immediately instead of sleeping.
476              ;; Ergo, no lost wakeup. We may get spurious wakeups, but
477              ;; that's ok.
478              (loop
479               (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
480                 (case (with-pinned-objects (queue me)
481                         (allow-with-interrupts
482                           (futex-wait (waitqueue-data-address queue)
483                                       (get-lisp-obj-address me)
484                                       ;; our way if saying "no
485                                       ;; timeout":
486                                       (or to-sec -1)
487                                       (or to-usec 0))))
488                   ((1) (signal-deadline))
489                   ((2))
490                   ;; EWOULDBLOCK, -1 here, is the possible spurious
491                   ;; wakeup case. 0 is the normal wakeup.
492                   (otherwise (return))))))
493         ;; If we are interrupted while waiting, we should do these
494         ;; things before returning. Ideally, in the case of an
495         ;; unhandled signal, we should do them before entering the
496         ;; debugger, but this is better than nothing.
497         (get-mutex mutex)))))
498
499 (defun condition-notify (queue &optional (n 1))
500   #!+sb-doc
501   "Notify N threads waiting on QUEUE. The same mutex that is used in
502 the corresponding CONDITION-WAIT must be held by this thread during
503 this call."
504   #!-sb-thread (declare (ignore queue n))
505   #!-sb-thread (error "Not supported in unithread builds.")
506   #!+sb-thread
507   (declare (type (and fixnum (integer 1)) n))
508   (/show0 "Entering CONDITION-NOTIFY")
509   #!+sb-thread
510   (progn
511     #!+sb-lutex
512     (with-lutex-address (lutex (waitqueue-lutex queue))
513       (%lutex-wake lutex n))
514     ;; no problem if >1 thread notifies during the comment in
515     ;; condition-wait: as long as the value in queue-data isn't the
516     ;; waiting thread's id, it matters not what it is
517     ;; XXX we should do something to ensure that the result of this setf
518     ;; is visible to all CPUs
519     #!-sb-lutex
520     (let ((me *current-thread*))
521       (progn
522         (setf (waitqueue-data queue) me)
523         (with-pinned-objects (queue)
524           (futex-wake (waitqueue-data-address queue) n))))))
525
526 (defun condition-broadcast (queue)
527   #!+sb-doc
528   "Notify all threads waiting on QUEUE."
529   (condition-notify queue
530                     ;; On a 64-bit platform truncating M-P-F to an int
531                     ;; results in -1, which wakes up only one thread.
532                     (ldb (byte 29 0)
533                          most-positive-fixnum)))
534 \f
535
536 ;;;; Semaphores
537
538 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
539   #!+sb-doc
540   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
541 should be considered an implementation detail, and may change in the
542 future."
543   (name nil :type (or null simple-string))
544   (%count 0 :type (integer 0))
545   (waitcount 0 :type (integer 0))
546   (mutex (make-mutex))
547   (queue (make-waitqueue)))
548
549 (setf (fdocumentation 'semaphore-name 'function)
550       "The name of the semaphore INSTANCE. Setfable.")
551
552 (declaim (inline semaphore-count))
553 (defun semaphore-count (instance)
554   "Returns the current count of the semaphore INSTANCE."
555   (semaphore-%count instance))
556
557 (defun make-semaphore (&key name (count 0))
558   #!+sb-doc
559   "Create a semaphore with the supplied COUNT and NAME."
560   (%make-semaphore name count))
561
562 (defun wait-on-semaphore (semaphore)
563   #!+sb-doc
564   "Decrement the count of SEMAPHORE if the count would not be
565 negative. Else blocks until the semaphore can be decremented."
566   ;; A more direct implementation based directly on futexes should be
567   ;; possible.
568   ;;
569   ;; We need to disable interrupts so that we don't forget to
570   ;; decrement the waitcount (which would happen if an asynch
571   ;; interrupt should catch us on our way out from the loop.)
572   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
573     ;; Quick check: is it positive? If not, enter the wait loop.
574     (let ((count (semaphore-%count semaphore)))
575       (if (plusp count)
576           (setf (semaphore-%count semaphore) (1- count))
577           (unwind-protect
578                (progn
579                  (incf (semaphore-waitcount semaphore))
580                  (loop until (plusp (setf count (semaphore-%count semaphore)))
581                        do (condition-wait (semaphore-queue semaphore)
582                                           (semaphore-mutex semaphore)))
583                  (setf (semaphore-%count semaphore) (1- count)))
584             (decf (semaphore-waitcount semaphore)))))))
585
586 (defun signal-semaphore (semaphore &optional (n 1))
587   #!+sb-doc
588   "Increment the count of SEMAPHORE by N. If there are threads waiting
589 on this semaphore, then N of them is woken up."
590   (declare (type (integer 1) n))
591   ;; Need to disable interrupts so that we don't lose a wakeup after
592   ;; we have incremented the count.
593   (with-system-mutex ((semaphore-mutex semaphore))
594     (let ((waitcount (semaphore-waitcount semaphore))
595           (count (incf (semaphore-%count semaphore) n)))
596       (when (plusp waitcount)
597         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
598 \f
599
600 ;;;; Job control, independent listeners
601
602 (defstruct session
603   (lock (make-mutex :name "session lock"))
604   (threads nil)
605   (interactive-threads nil)
606   (interactive-threads-queue (make-waitqueue)))
607
608 (defvar *session* nil)
609
610 ;;; The debugger itself tries to acquire the session lock, don't let
611 ;;; funny situations (like getting a sigint while holding the session
612 ;;; lock) occur. At the same time we need to allow interrupts while
613 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
614 ;;; be interruptible.
615 ;;;
616 ;;; Take care: we sometimes need to obtain the session lock while
617 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
618 ;;; _after_ getting a session lock! (Deadlock risk.)
619 ;;;
620 ;;; FIXME: It would be good to have ordered locks to ensure invariants
621 ;;; like the above.
622 (defmacro with-session-lock ((session) &body body)
623   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
624      ,@body))
625
626 (defun new-session ()
627   (make-session :threads (list *current-thread*)
628                 :interactive-threads (list *current-thread*)))
629
630 (defun init-job-control ()
631   (/show0 "Entering INIT-JOB-CONTROL")
632   (setf *session* (new-session))
633   (/show0 "Exiting INIT-JOB-CONTROL"))
634
635 (defun %delete-thread-from-session (thread session)
636   (with-session-lock (session)
637     (setf (session-threads session)
638           (delete thread (session-threads session))
639           (session-interactive-threads session)
640           (delete thread (session-interactive-threads session)))))
641
642 (defun call-with-new-session (fn)
643   (%delete-thread-from-session *current-thread* *session*)
644   (let ((*session* (new-session)))
645     (funcall fn)))
646
647 (defmacro with-new-session (args &body forms)
648   (declare (ignore args))               ;for extensibility
649   (sb!int:with-unique-names (fb-name)
650     `(labels ((,fb-name () ,@forms))
651       (call-with-new-session (function ,fb-name)))))
652
653 ;;; Remove thread from its session, if it has one.
654 #!+sb-thread
655 (defun handle-thread-exit (thread)
656   (/show0 "HANDLING THREAD EXIT")
657   ;; Lisp-side cleanup
658   (with-all-threads-lock
659     (setf (thread-%alive-p thread) nil)
660     (setf (thread-os-thread thread) nil)
661     (setq *all-threads* (delete thread *all-threads*))
662     (when *session*
663       (%delete-thread-from-session thread *session*)))
664   #!+sb-lutex
665   (without-gcing
666     (/show0 "FREEING MUTEX LUTEX")
667     (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
668       (%lutex-destroy lutex))))
669
670 (defun terminate-session ()
671   #!+sb-doc
672   "Kill all threads in session except for this one.  Does nothing if current
673 thread is not the foreground thread."
674   ;; FIXME: threads created in other threads may escape termination
675   (let ((to-kill
676          (with-session-lock (*session*)
677            (and (eq *current-thread*
678                     (car (session-interactive-threads *session*)))
679                 (session-threads *session*)))))
680     ;; do the kill after dropping the mutex; unwind forms in dying
681     ;; threads may want to do session things
682     (dolist (thread to-kill)
683       (unless (eq thread *current-thread*)
684         ;; terminate the thread but don't be surprised if it has
685         ;; exited in the meantime
686         (handler-case (terminate-thread thread)
687           (interrupt-thread-error ()))))))
688
689 ;;; called from top of invoke-debugger
690 (defun debugger-wait-until-foreground-thread (stream)
691   "Returns T if thread had been running in background, NIL if it was
692 interactive."
693   (declare (ignore stream))
694   #!-sb-thread nil
695   #!+sb-thread
696   (prog1
697       (with-session-lock (*session*)
698         (not (member *current-thread*
699                      (session-interactive-threads *session*))))
700     (get-foreground)))
701
702 (defun get-foreground ()
703   #!-sb-thread t
704   #!+sb-thread
705   (let ((was-foreground t))
706     (loop
707      (/show0 "Looping in GET-FOREGROUND")
708      (with-session-lock (*session*)
709        (let ((int-t (session-interactive-threads *session*)))
710          (when (eq (car int-t) *current-thread*)
711            (unless was-foreground
712              (format *query-io* "Resuming thread ~A~%" *current-thread*))
713            (return-from get-foreground t))
714          (setf was-foreground nil)
715          (unless (member *current-thread* int-t)
716            (setf (cdr (last int-t))
717                  (list *current-thread*)))
718          (condition-wait
719           (session-interactive-threads-queue *session*)
720           (session-lock *session*)))))))
721
722 (defun release-foreground (&optional next)
723   #!+sb-doc
724   "Background this thread.  If NEXT is supplied, arrange for it to
725 have the foreground next."
726   #!-sb-thread (declare (ignore next))
727   #!-sb-thread nil
728   #!+sb-thread
729   (with-session-lock (*session*)
730     (when (rest (session-interactive-threads *session*))
731       (setf (session-interactive-threads *session*)
732             (delete *current-thread* (session-interactive-threads *session*))))
733     (when next
734       (setf (session-interactive-threads *session*)
735             (list* next
736                    (delete next (session-interactive-threads *session*)))))
737     (condition-broadcast (session-interactive-threads-queue *session*))))
738
739 (defun foreground-thread ()
740   (car (session-interactive-threads *session*)))
741
742 (defun make-listener-thread (tty-name)
743   (assert (probe-file tty-name))
744   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
745          (out (sb!unix:unix-dup in))
746          (err (sb!unix:unix-dup in)))
747     (labels ((thread-repl ()
748                (sb!unix::unix-setsid)
749                (let* ((sb!impl::*stdin*
750                        (make-fd-stream in :input t :buffering :line
751                                        :dual-channel-p t))
752                       (sb!impl::*stdout*
753                        (make-fd-stream out :output t :buffering :line
754                                               :dual-channel-p t))
755                       (sb!impl::*stderr*
756                        (make-fd-stream err :output t :buffering :line
757                                               :dual-channel-p t))
758                       (sb!impl::*tty*
759                        (make-fd-stream err :input t :output t
760                                               :buffering :line
761                                               :dual-channel-p t))
762                       (sb!impl::*descriptor-handlers* nil))
763                  (with-new-session ()
764                    (unwind-protect
765                         (sb!impl::toplevel-repl nil)
766                      (sb!int:flush-standard-output-streams))))))
767       (make-thread #'thread-repl))))
768 \f
769
770 ;;;; The beef
771
772 (defun make-thread (function &key name)
773   #!+sb-doc
774   "Create a new thread of NAME that runs FUNCTION. When the function
775 returns the thread exits. The return values of FUNCTION are kept
776 around and can be retrieved by JOIN-THREAD."
777   #!-sb-thread (declare (ignore function name))
778   #!-sb-thread (error "Not supported in unithread builds.")
779   #!+sb-thread
780   (let* ((thread (%make-thread :name name))
781          (setup-sem (make-semaphore :name "Thread setup semaphore"))
782          (real-function (coerce function 'function))
783          (initial-function
784           (lambda ()
785             ;; In time we'll move some of the binding presently done in C
786             ;; here too.
787             ;;
788             ;; KLUDGE: Here we have a magic list of variables that are
789             ;; not thread-safe for one reason or another.  As people
790             ;; report problems with the thread safety of certain
791             ;; variables, (e.g. "*print-case* in multiple threads
792             ;; broken", sbcl-devel 2006-07-14), we add a few more
793             ;; bindings here.  The Right Thing is probably some variant
794             ;; of Allegro's *cl-default-special-bindings*, as that is at
795             ;; least accessible to users to secure their own libraries.
796             ;;   --njf, 2006-07-15
797             ;;
798             ;; As it is, this lambda must not cons until we are ready
799             ;; to run GC. Be very careful.
800             (let* ((*current-thread* thread)
801                    (*restart-clusters* nil)
802                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
803                    (*condition-restarts* nil)
804                    (sb!impl::*deadline* nil)
805                    (sb!impl::*step-out* nil)
806                    ;; internal printer variables
807                    (sb!impl::*previous-case* nil)
808                    (sb!impl::*previous-readtable-case* nil)
809                    (empty (vector))
810                    (sb!impl::*merge-sort-temp-vector* empty)
811                    (sb!impl::*zap-array-data-temp* empty)
812                    (sb!impl::*internal-symbol-output-fun* nil)
813                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
814               ;; Binding from C
815               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
816               (setf (thread-os-thread thread) (current-thread-os-thread))
817               (with-mutex ((thread-result-lock thread))
818                 (with-all-threads-lock
819                   (push thread *all-threads*))
820                 (with-session-lock (*session*)
821                   (push thread (session-threads *session*)))
822                 (setf (thread-%alive-p thread) t)
823                 (signal-semaphore setup-sem)
824                 ;; can't use handling-end-of-the-world, because that flushes
825                 ;; output streams, and we don't necessarily have any (or we
826                 ;; could be sharing them)
827                 (catch 'sb!impl::toplevel-catcher
828                   (catch 'sb!impl::%end-of-the-world
829                     (with-simple-restart
830                         (terminate-thread
831                          (format nil
832                                  "~~@<Terminate this thread (~A)~~@:>"
833                                  *current-thread*))
834                       (without-interrupts
835                         (unwind-protect
836                              (with-local-interrupts
837                                ;; Now that most things have a chance
838                                ;; to work properly without messing up
839                                ;; other threads, it's time to enable
840                                ;; signals.
841                                (sb!unix::unblock-deferrable-signals)
842                                (setf (thread-result thread)
843                                      (cons t
844                                            (multiple-value-list
845                                             (funcall real-function))))
846                                ;; Try to block deferrables. An
847                                ;; interrupt may unwind it, but for a
848                                ;; normal exit it prevents interrupt
849                                ;; loss.
850                                (block-deferrable-signals))
851                           ;; We're going down, can't handle interrupts
852                           ;; sanely anymore. GC remains enabled.
853                           (block-deferrable-signals)
854                           ;; We don't want to run interrupts in a dead
855                           ;; thread when we leave WITHOUT-INTERRUPTS.
856                           ;; This potentially causes important
857                           ;; interupts to be lost: SIGINT comes to
858                           ;; mind.
859                           (setq *interrupt-pending* nil)
860                           (handle-thread-exit thread))))))))
861             (values))))
862     ;; If the starting thread is stopped for gc before it signals the
863     ;; semaphore then we'd be stuck.
864     (assert (not *gc-inhibit*))
865     ;; Keep INITIAL-FUNCTION pinned until the child thread is
866     ;; initialized properly. Wrap the whole thing in
867     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
868     ;; thread.
869     (without-interrupts
870       (with-pinned-objects (initial-function)
871         (let ((os-thread
872                (%create-thread
873                 (get-lisp-obj-address initial-function))))
874           (when (zerop os-thread)
875             (error "Can't create a new thread"))
876           (wait-on-semaphore setup-sem)
877           thread)))))
878
879 (define-condition join-thread-error (error)
880   ((thread :reader join-thread-error-thread :initarg :thread))
881   #!+sb-doc
882   (:documentation "Joining thread failed.")
883   (:report (lambda (c s)
884              (format s "Joining thread failed: thread ~A ~
885                         has not returned normally."
886                      (join-thread-error-thread c)))))
887
888 #!+sb-doc
889 (setf (fdocumentation 'join-thread-error-thread 'function)
890       "The thread that we failed to join.")
891
892 (defun join-thread (thread &key (default nil defaultp))
893   #!+sb-doc
894   "Suspend current thread until THREAD exits. Returns the result
895 values of the thread function. If the thread does not exit normally,
896 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
897   (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
898     (cond ((car (thread-result thread))
899            (return-from join-thread
900              (values-list (cdr (thread-result thread)))))
901           (defaultp
902            (return-from join-thread default))))
903   (error 'join-thread-error :thread thread))
904
905 (defun destroy-thread (thread)
906   #!+sb-doc
907   "Deprecated. Same as TERMINATE-THREAD."
908   (terminate-thread thread))
909
910 (define-condition interrupt-thread-error (error)
911   ((thread :reader interrupt-thread-error-thread :initarg :thread))
912   #!+sb-doc
913   (:documentation "Interrupting thread failed.")
914   (:report (lambda (c s)
915              (format s "Interrupt thread failed: thread ~A has exited."
916                      (interrupt-thread-error-thread c)))))
917
918 #!+sb-doc
919 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
920       "The thread that was not interrupted.")
921
922 (defmacro with-interruptions-lock ((thread) &body body)
923   `(with-system-mutex ((thread-interruptions-lock ,thread))
924      ,@body))
925
926 ;;; Called from the signal handler.
927 #!-win32
928 (defun run-interruption ()
929   (let ((interruption (with-interruptions-lock (*current-thread*)
930                         (pop (thread-interruptions *current-thread*)))))
931     ;; If there is more to do, then resignal and let the normal
932     ;; interrupt deferral mechanism take care of the rest. From the
933     ;; OS's point of view the signal we are in the handler for is no
934     ;; longer pending, so the signal will not be lost.
935     (when (thread-interruptions *current-thread*)
936       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
937     (when interruption
938       (funcall interruption))))
939
940 (defun interrupt-thread (thread function)
941   #!+sb-doc
942   "Interrupt the live THREAD and make it run FUNCTION. A moderate
943 degree of care is expected for use of INTERRUPT-THREAD, due to its
944 nature: if you interrupt a thread that was holding important locks
945 then do something that turns out to need those locks, you probably
946 won't like the effect. FUNCTION runs with interrupts disabled, but
947 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
948 enable interrupts (GET-MUTEX when contended, for instance) so the
949 first thing to do is usually a WITH-INTERRUPTS or a
950 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
951 run in same the order they were sent."
952   #!+win32
953   (declare (ignore thread))
954   #!+win32
955   (with-interrupt-bindings
956     (with-interrupts (funcall function)))
957   #!-win32
958   (let ((os-thread (thread-os-thread thread)))
959     (cond ((not os-thread)
960            (error 'interrupt-thread-error :thread thread))
961           (t
962            (with-interruptions-lock (thread)
963              ;; Append to the end of the interruptions queue. It's
964              ;; O(N), but it does not hurt to slow interruptors down a
965              ;; bit when the queue gets long.
966              (setf (thread-interruptions thread)
967                    (append (thread-interruptions thread)
968                            (list (lambda ()
969                                    (without-interrupts
970                                      (allow-with-interrupts
971                                        (funcall function))))))))
972            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
973              (error 'interrupt-thread-error :thread thread))))))
974
975 (defun terminate-thread (thread)
976   #!+sb-doc
977   "Terminate the thread identified by THREAD, by causing it to run
978 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
979   (interrupt-thread thread 'sb!ext:quit))
980
981 (define-alien-routine "thread_yield" int)
982
983 #!+sb-doc
984 (setf (fdocumentation 'thread-yield 'function)
985       "Yield the processor to other threads.")
986
987 ;;; internal use only.  If you think you need to use these, either you
988 ;;; are an SBCL developer, are doing something that you should discuss
989 ;;; with an SBCL developer first, or are doing something that you
990 ;;; should probably discuss with a professional psychiatrist first
991 #!+sb-thread
992 (progn
993   (defun %thread-sap (thread)
994     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
995           (target (thread-os-thread thread)))
996       (loop
997         (when (sap= thread-sap (int-sap 0)) (return nil))
998         (let ((os-thread (sap-ref-word thread-sap
999                                        (* sb!vm:n-word-bytes
1000                                           sb!vm::thread-os-thread-slot))))
1001           (when (= os-thread target) (return thread-sap))
1002           (setf thread-sap
1003                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1004                                            sb!vm::thread-next-slot)))))))
1005
1006   (defun %symbol-value-in-thread (symbol thread)
1007     (tagbody
1008        ;; Prevent the dead from dying completely while we look for the
1009        ;; TLS area...
1010        (with-all-threads-lock
1011          (if (thread-alive-p thread)
1012              (let* ((offset (* sb!vm:n-word-bytes
1013                                (sb!vm::symbol-tls-index symbol)))
1014                     (tl-val (sap-ref-word (%thread-sap thread) offset)))
1015                (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1016                    (go :unbound)
1017                    (return-from %symbol-value-in-thread
1018                      (values (make-lisp-obj tl-val) t))))
1019              (return-from %symbol-value-in-thread (values nil nil))))
1020      :unbound
1021        (error "Cannot read thread-local symbol value: ~S unbound in ~S"
1022               symbol thread)))
1023
1024   (defun %set-symbol-value-in-thread (symbol thread value)
1025     (tagbody
1026        (with-pinned-objects (value)
1027          ;; Prevent the dead from dying completely while we look for
1028          ;; the TLS area...
1029          (with-all-threads-lock
1030            (if (thread-alive-p thread)
1031                (let* ((offset (* sb!vm:n-word-bytes
1032                                  (sb!vm::symbol-tls-index symbol)))
1033                       (sap (%thread-sap thread))
1034                       (tl-val (sap-ref-word sap offset)))
1035                  (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1036                      (go :unbound)
1037                      (setf (sap-ref-word sap offset)
1038                            (get-lisp-obj-address value)))
1039                  (return-from %set-symbol-value-in-thread (values value t)))
1040                (return-from %set-symbol-value-in-thread (values nil nil)))))
1041      :unbound
1042        (error "Cannot set thread-local symbol value: ~S unbound in ~S"
1043               symbol thread))))
1044
1045 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1046   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1047 \f
1048
1049 ;;;; Stepping
1050
1051 (defun thread-stepping ()
1052   (make-lisp-obj
1053    (sap-ref-word (current-thread-sap)
1054                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1055
1056 (defun (setf thread-stepping) (value)
1057   (setf (sap-ref-word (current-thread-sap)
1058                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1059         (get-lisp-obj-address value)))