1.0.42.43: FD-STREAMS no longer hook into SERVE-EVENT by default
[sbcl.git] / src / code / serve-event.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3 ;;;;
4 ;;;; This software is derived from the CMU CL system, which was
5 ;;;; written at Carnegie Mellon University and released into the
6 ;;;; public domain. The software is in the public domain and is
7 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
8 ;;;; files for more information.
9
10 (in-package "SB!IMPL")
11
12 ;;;; file descriptor I/O noise
13
14 (defstruct (handler
15             (:constructor make-handler (direction descriptor function))
16             (:copier nil))
17   ;; Reading or writing...
18   (direction nil :type (member :input :output))
19   ;; File descriptor this handler is tied to.
20   (descriptor 0 :type (mod #.sb!unix:fd-setsize))
21   ;; T iff this handler is running.
22   ;;
23   ;; FIXME: unused. At some point this used to be set to T
24   ;; around the call to the handler-function, but that was commented
25   ;; out with the verbose explantion "Doesn't work -- ACK".
26   active
27   ;; Function to call.
28   (function nil :type function)
29   ;; T if this descriptor is bogus.
30   bogus)
31
32 (def!method print-object ((handler handler) stream)
33   (print-unreadable-object (handler stream :type t)
34     (format stream
35             "~A on ~:[~;BOGUS ~]descriptor ~W: ~S"
36             (handler-direction handler)
37             (handler-bogus handler)
38             (handler-descriptor handler)
39             (handler-function handler))))
40
41 (defvar *descriptor-handlers* nil
42   #!+sb-doc
43   "List of all the currently active handlers for file descriptors")
44
45 (sb!xc:defmacro with-descriptor-handlers (&body forms)
46   ;; FD-STREAM functionality can add and remove descriptors on it's
47   ;; own, so getting an interrupt while modifying this and the
48   ;; starting to recursively modify it could lose...
49   `(without-interrupts ,@forms))
50
51 (defun list-all-descriptor-handlers ()
52   (with-descriptor-handlers
53     (copy-list *descriptor-handlers*)))
54
55 (defun select-descriptor-handlers (function)
56   (declare (function function))
57   (with-descriptor-handlers
58     (remove-if-not function *descriptor-handlers*)))
59
60 (defun map-descriptor-handlers (function)
61   (declare (function function))
62   (with-descriptor-handlers
63     (dolist (handler *descriptor-handlers*)
64       (funcall function handler))))
65
66 ;;; Add a new handler to *descriptor-handlers*.
67 (defun add-fd-handler (fd direction function)
68   #!+sb-doc
69   "Arange to call FUNCTION whenever FD is usable. DIRECTION should be
70   either :INPUT or :OUTPUT. The value returned should be passed to
71   SYSTEM:REMOVE-FD-HANDLER when it is no longer needed."
72   (unless (member direction '(:input :output))
73     ;; FIXME: should be TYPE-ERROR?
74     (error "Invalid direction ~S, must be either :INPUT or :OUTPUT" direction))
75   (let ((handler (make-handler direction fd function)))
76     (with-descriptor-handlers
77       (push handler *descriptor-handlers*))
78     handler))
79
80 ;;; Remove an old handler from *descriptor-handlers*.
81 (defun remove-fd-handler (handler)
82   #!+sb-doc
83   "Removes HANDLER from the list of active handlers."
84   (with-descriptor-handlers
85     (setf *descriptor-handlers*
86           (delete handler *descriptor-handlers*))))
87
88 ;;; Search *descriptor-handlers* for any reference to fd, and nuke 'em.
89 (defun invalidate-descriptor (fd)
90   #!+sb-doc
91   "Remove any handers refering to fd. This should only be used when attempting
92   to recover from a detected inconsistancy."
93   (with-descriptor-handlers
94     (setf *descriptor-handlers*
95           (delete fd *descriptor-handlers*
96                   :key #'handler-descriptor))))
97
98 ;;; Add the handler to *descriptor-handlers* for the duration of BODY.
99 (defmacro with-fd-handler ((fd direction function) &rest body)
100   #!+sb-doc
101   "Establish a handler with SYSTEM:ADD-FD-HANDLER for the duration of BODY.
102    DIRECTION should be either :INPUT or :OUTPUT, FD is the file descriptor to
103    use, and FUNCTION is the function to call whenever FD is usable."
104   (let ((handler (gensym)))
105     `(let (,handler)
106        (unwind-protect
107            (progn
108              (setf ,handler (add-fd-handler ,fd ,direction ,function))
109              ,@body)
110          (when ,handler
111            (remove-fd-handler ,handler))))))
112
113 ;;; First, get a list and mark bad file descriptors. Then signal an error
114 ;;; offering a few restarts.
115 (defun handler-descriptors-error ()
116   (let ((bogus-handlers nil))
117     (dolist (handler (list-all-descriptor-handlers))
118       (unless (or (handler-bogus handler)
119                   (sb!unix:unix-fstat (handler-descriptor handler)))
120         (setf (handler-bogus handler) t)
121         (push handler bogus-handlers)))
122     (when bogus-handlers
123       (restart-case (error "~S ~[have~;has a~:;have~] bad file descriptor~:P."
124                            bogus-handlers (length bogus-handlers))
125         (remove-them ()
126           :report "Remove bogus handlers."
127           (with-descriptor-handlers
128             (setf *descriptor-handlers*
129                   (delete-if #'handler-bogus *descriptor-handlers*))))
130         (retry-them ()
131           :report "Retry bogus handlers."
132           (dolist (handler bogus-handlers)
133             (setf (handler-bogus handler) nil)))
134         (continue ()
135           :report "Go on, leaving handlers marked as bogus."))))
136   nil)
137
138 \f
139 ;;;; SERVE-ALL-EVENTS, SERVE-EVENT, and friends
140
141 ;;; When a *periodic-polling-function* is defined the server will not
142 ;;; block for more than the maximum event timeout and will call the
143 ;;; polling function if it does time out.
144 (declaim (type (or null symbol function) *periodic-polling-function*))
145 (defvar *periodic-polling-function* nil
146   "Either NIL, or a designator for a function callable without any
147 arguments. Called when the system has been waiting for input for
148 longer then *PERIODIC-POLLING-PERIOD* seconds. Shared between all
149 threads, unless locally bound. EXPERIMENTAL.")
150 (declaim (real *periodic-polling-period*))
151 (defvar *periodic-polling-period* 0
152   "A real number designating the number of seconds to wait for input
153 at maximum, before calling the *PERIODIC-POLLING-FUNCTION* \(if any.)
154 Shared between all threads, unless locally bound. EXPERIMENTAL.")
155
156 ;;; Wait until FD is usable for DIRECTION. The timeout given to serve-event is
157 ;;; recalculated each time through the loop so that WAIT-UNTIL-FD-USABLE will
158 ;;; timeout at the correct time irrespective of how many events are handled in
159 ;;; the meantime.
160 (defun wait-until-fd-usable (fd direction &optional timeout (serve-events t))
161   #!+sb-doc
162   "Wait until FD is usable for DIRECTION. DIRECTION should be either :INPUT or
163 :OUTPUT. TIMEOUT, if supplied, is the number of seconds to wait before giving
164 up. Returns true once the FD is usable, NIL return indicates timeout.
165
166 If SERVE-EVENTS is true (the default), events on other FDs are served while
167 waiting."
168   (tagbody
169    :restart
170      (multiple-value-bind (to-sec to-usec stop-sec stop-usec signalp)
171          (decode-timeout timeout)
172        (declare (type (or integer null) to-sec to-usec))
173        (flet ((maybe-update-timeout ()
174                 ;; If we return early, recompute the timeouts, possibly
175                 ;; signaling the deadline or returning with NIL to caller.
176                 (multiple-value-bind (sec usec)
177                     (decode-internal-time (get-internal-real-time))
178                   (setf to-sec (- stop-sec sec))
179                   (cond ((> usec stop-usec)
180                          (decf to-sec)
181                          (setf to-usec (- (+ stop-usec 1000000) usec)))
182                         (t
183                          (setf to-usec (- stop-usec usec)))))
184                 (when (or (minusp to-sec) (and (zerop to-sec) (not (plusp to-usec))))
185                   (cond (signalp
186                          (signal-deadline)
187                          (go :restart))
188                         (t
189                          (return-from wait-until-fd-usable nil))))))
190          (if (and serve-events
191                   ;; No timeout or non-zero timeout
192                   (or (not to-sec)
193                       (not (= 0 to-sec to-usec)))
194                   ;; Something to do while we wait
195                   (or *descriptor-handlers* *periodic-polling-function*))
196              ;; Loop around SUB-SERVE-EVENT till done.
197              (dx-let ((usable (list nil)))
198                (dx-flet ((usable! (fd)
199                                   (declare (ignore fd))
200                                   (setf (car usable) t)))
201                  (with-fd-handler (fd direction #'usable!)
202                    (loop
203                      (sub-serve-event to-sec to-usec signalp)
204                      (when (car usable)
205                        (return-from wait-until-fd-usable t))
206                      (when to-sec
207                        (maybe-update-timeout))))))
208              ;; If we don't have to serve events, just poll on the single FD instead.
209              (loop for to-msec = (if (and to-sec to-usec)
210                                      (+ (* 1000 to-sec) (truncate to-usec 1000))
211                                      -1)
212                    when (sb!unix:unix-simple-poll fd direction to-msec)
213                    do (return-from wait-until-fd-usable t)
214                    else
215                    do (when to-sec (maybe-update-timeout))))))))
216 \f
217 ;;; Wait for up to timeout seconds for an event to happen. Make sure all
218 ;;; pending events are processed before returning.
219 (defun serve-all-events (&optional timeout)
220   #!+sb-doc
221   "SERVE-ALL-EVENTS calls SERVE-EVENT with the specified timeout. If
222 SERVE-EVENT does something (returns T) it loops over SERVE-EVENT with a
223 timeout of 0 until there are no more events to serve. SERVE-ALL-EVENTS returns
224 T if SERVE-EVENT did something and NIL if not."
225   (do ((res nil)
226        (sval (serve-event timeout) (serve-event 0)))
227       ((null sval) res)
228     (setq res t)))
229
230 ;;; Serve a single set of events.
231 (defun serve-event (&optional timeout)
232   #!+sb-doc
233   "Receive pending events on all FD-STREAMS and dispatch to the appropriate
234 handler functions. If timeout is specified, server will wait the specified
235 time (in seconds) and then return, otherwise it will wait until something
236 happens. Server returns T if something happened and NIL otherwise. Timeout
237 0 means polling without waiting."
238   (multiple-value-bind (to-sec to-usec stop-sec stop-usec signalp)
239       (decode-timeout timeout)
240     (declare (ignore stop-sec stop-usec))
241     (sub-serve-event to-sec to-usec signalp)))
242
243 ;;; Takes timeout broken into seconds and microseconds, NIL timeout means
244 ;;; to wait as long as needed.
245 (defun sub-serve-event (to-sec to-usec deadlinep)
246   (or
247    (if *periodic-polling-function*
248        (multiple-value-bind (p-sec p-usec)
249            (decode-internal-time
250             (seconds-to-internal-time *periodic-polling-period*))
251          (if to-sec
252              (loop repeat (/ (+ to-sec (/ to-usec 1e6))
253                              *periodic-polling-period*)
254                    thereis (sub-sub-serve-event p-sec p-usec)
255                    do (funcall *periodic-polling-function*))
256              (loop thereis (sub-sub-serve-event p-sec p-usec)
257                    do (funcall *periodic-polling-function*))))
258        (sub-sub-serve-event to-sec to-usec))
259    (when deadlinep
260      (signal-deadline))))
261
262 ;;; Handles the work of the above, except for periodic polling. Returns
263 ;;; true if something of interest happened.
264 (defun sub-sub-serve-event (to-sec to-usec)
265   (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set))
266                         (write-fds (sb!alien:struct sb!unix:fd-set)))
267     (sb!unix:fd-zero read-fds)
268     (sb!unix:fd-zero write-fds)
269     (let ((count 0))
270       (declare (type index count))
271
272       ;; Initialize the fd-sets for UNIX-SELECT and return the active
273       ;; descriptor count.
274       (map-descriptor-handlers
275        (lambda (handler)
276          ;; FIXME: If HANDLER-ACTIVE ever is reinstanted, it needs
277          ;; to be checked here in addition to HANDLER-BOGUS
278          (unless (handler-bogus handler)
279            (let ((fd (handler-descriptor handler)))
280              (ecase (handler-direction handler)
281                (:input (sb!unix:fd-set fd read-fds))
282                (:output (sb!unix:fd-set fd write-fds)))
283              (when (> fd count)
284                (setf count fd))))))
285       (incf count)
286
287       ;; Next, wait for something to happen.
288       (multiple-value-bind (value err)
289           (sb!unix:unix-fast-select count
290                                     (sb!alien:addr read-fds)
291                                     (sb!alien:addr write-fds)
292                                     nil to-sec to-usec)
293         #!+win32
294         (declare (ignore err))
295         ;; Now see what it was (if anything)
296         (cond ((not value)
297                ;; Interrupted or one of the file descriptors is bad.
298                ;; FIXME: Check for other errnos. Why do we return true
299                ;; when interrupted?
300                #!-win32
301                (case err
302                  (#.sb!unix:ebadf
303                   (handler-descriptors-error))
304                  ((#.sb!unix:eintr #.sb!unix:eagain)
305                   t)
306                  (otherwise
307                   (with-simple-restart (continue "Ignore failure and continue.")
308                     (simple-perror "Unix system call select() failed"
309                                    :errno err))))
310                #!+win32
311                (handler-descriptors-error))
312               ((plusp value)
313                ;; Got something. Call file descriptor handlers
314                ;; according to the readable and writable masks
315                ;; returned by select.
316                (dolist (handler
317                         (select-descriptor-handlers
318                          (lambda (handler)
319                            (let ((fd (handler-descriptor handler)))
320                              (ecase (handler-direction handler)
321                                (:input (sb!unix:fd-isset fd read-fds))
322                                (:output (sb!unix:fd-isset fd write-fds)))))))
323                  (funcall (handler-function handler)
324                           (handler-descriptor handler)))
325                t))))))
326