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