8fd5321f8e5ea3f9a658b8a0d820c1633bd8d9d1
[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   (unless (<= 0 fd (1- sb!unix:fd-setsize))
76     (error "Cannot add an FD handler for ~D: not under FD_SETSIZE limit." fd))
77   (let ((handler (make-handler direction fd function)))
78     (with-descriptor-handlers
79       (push handler *descriptor-handlers*))
80     handler))
81
82 ;;; Remove an old handler from *descriptor-handlers*.
83 (defun remove-fd-handler (handler)
84   #!+sb-doc
85   "Removes HANDLER from the list of active handlers."
86   (with-descriptor-handlers
87     (setf *descriptor-handlers*
88           (delete handler *descriptor-handlers*))))
89
90 ;;; Search *descriptor-handlers* for any reference to fd, and nuke 'em.
91 (defun invalidate-descriptor (fd)
92   #!+sb-doc
93   "Remove any handers refering to fd. This should only be used when attempting
94   to recover from a detected inconsistancy."
95   (with-descriptor-handlers
96     (setf *descriptor-handlers*
97           (delete fd *descriptor-handlers*
98                   :key #'handler-descriptor))))
99
100 ;;; Add the handler to *descriptor-handlers* for the duration of BODY.
101 (defmacro with-fd-handler ((fd direction function) &rest body)
102   #!+sb-doc
103   "Establish a handler with SYSTEM:ADD-FD-HANDLER for the duration of BODY.
104    DIRECTION should be either :INPUT or :OUTPUT, FD is the file descriptor to
105    use, and FUNCTION is the function to call whenever FD is usable."
106   (let ((handler (gensym)))
107     `(let (,handler)
108        (unwind-protect
109            (progn
110              (setf ,handler (add-fd-handler ,fd ,direction ,function))
111              ,@body)
112          (when ,handler
113            (remove-fd-handler ,handler))))))
114
115 ;;; First, get a list and mark bad file descriptors. Then signal an error
116 ;;; offering a few restarts.
117 (defun handler-descriptors-error ()
118   (let ((bogus-handlers nil))
119     (dolist (handler (list-all-descriptor-handlers))
120       (unless (or (handler-bogus handler)
121                   (sb!unix:unix-fstat (handler-descriptor handler)))
122         (setf (handler-bogus handler) t)
123         (push handler bogus-handlers)))
124     (when bogus-handlers
125       (restart-case (error "~S ~[have~;has a~:;have~] bad file descriptor~:P."
126                            bogus-handlers (length bogus-handlers))
127         (remove-them ()
128           :report "Remove bogus handlers."
129           (with-descriptor-handlers
130             (setf *descriptor-handlers*
131                   (delete-if #'handler-bogus *descriptor-handlers*))))
132         (retry-them ()
133           :report "Retry bogus handlers."
134           (dolist (handler bogus-handlers)
135             (setf (handler-bogus handler) nil)))
136         (continue ()
137           :report "Go on, leaving handlers marked as bogus."))))
138   nil)
139
140 \f
141 ;;;; SERVE-ALL-EVENTS, SERVE-EVENT, and friends
142
143 ;;; When a *periodic-polling-function* is defined the server will not
144 ;;; block for more than the maximum event timeout and will call the
145 ;;; polling function if it does time out.
146 (declaim (type (or null symbol function) *periodic-polling-function*))
147 (defvar *periodic-polling-function* nil
148   "Either NIL, or a designator for a function callable without any
149 arguments. Called when the system has been waiting for input for
150 longer then *PERIODIC-POLLING-PERIOD* seconds. Shared between all
151 threads, unless locally bound. EXPERIMENTAL.")
152 (declaim (real *periodic-polling-period*))
153 (defvar *periodic-polling-period* 0
154   "A real number designating the number of seconds to wait for input
155 at maximum, before calling the *PERIODIC-POLLING-FUNCTION* \(if any.)
156 Shared between all threads, unless locally bound. EXPERIMENTAL.")
157
158 ;;; Wait until FD is usable for DIRECTION. The timeout given to serve-event is
159 ;;; recalculated each time through the loop so that WAIT-UNTIL-FD-USABLE will
160 ;;; timeout at the correct time irrespective of how many events are handled in
161 ;;; the meantime.
162 (defun wait-until-fd-usable (fd direction &optional timeout (serve-events t))
163   #!+sb-doc
164   "Wait until FD is usable for DIRECTION. DIRECTION should be either :INPUT or
165 :OUTPUT. TIMEOUT, if supplied, is the number of seconds to wait before giving
166 up. Returns true once the FD is usable, NIL return indicates timeout.
167
168 If SERVE-EVENTS is true (the default), events on other FDs are served while
169 waiting."
170   (tagbody
171    :restart
172      (multiple-value-bind (to-sec to-usec stop-sec stop-usec signalp)
173          (decode-timeout timeout)
174        (declare (type (or integer null) to-sec to-usec))
175        (flet ((maybe-update-timeout ()
176                 ;; If we return early, recompute the timeouts, possibly
177                 ;; signaling the deadline or returning with NIL to caller.
178                 (setf (values to-sec to-usec)
179                       (relative-decoded-times stop-sec stop-usec))
180                 (when (and (zerop to-sec) (not (plusp to-usec)))
181                   (cond (signalp
182                          (signal-deadline)
183                          (go :restart))
184                         (t
185                          (return-from wait-until-fd-usable nil))))))
186          (if (and serve-events
187                   ;; No timeout or non-zero timeout
188                   (or (not to-sec)
189                       (not (= 0 to-sec to-usec)))
190                   ;; Something to do while we wait
191                   (or *descriptor-handlers* *periodic-polling-function*))
192              ;; Loop around SUB-SERVE-EVENT till done.
193              (dx-let ((usable (list nil)))
194                (dx-flet ((usable! (fd)
195                                   (declare (ignore fd))
196                                   (setf (car usable) t)))
197                  (with-fd-handler (fd direction #'usable!)
198                    (loop
199                      (sub-serve-event to-sec to-usec signalp)
200                      (when (car usable)
201                        (return-from wait-until-fd-usable t))
202                      (when to-sec
203                        (maybe-update-timeout))))))
204              ;; If we don't have to serve events, just poll on the single FD instead.
205              (loop for to-msec = (if (and to-sec to-usec)
206                                      (+ (* 1000 to-sec) (truncate to-usec 1000))
207                                      -1)
208                    when (or #!+win32 (eq direction :output)
209                             #!+win32 (sb!win32:handle-listen
210                                       (sb!win32:get-osfhandle fd))
211                             #!-win32
212                             (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                    #!+win32 (sb!thread:thread-yield)))))))
217 \f
218 ;;; Wait for up to timeout seconds for an event to happen. Make sure all
219 ;;; pending events are processed before returning.
220 (defun serve-all-events (&optional timeout)
221   #!+sb-doc
222   "SERVE-ALL-EVENTS calls SERVE-EVENT with the specified timeout. If
223 SERVE-EVENT does something (returns T) it loops over SERVE-EVENT with a
224 timeout of 0 until there are no more events to serve. SERVE-ALL-EVENTS returns
225 T if SERVE-EVENT did something and NIL if not."
226   (do ((res nil)
227        (sval (serve-event timeout) (serve-event 0)))
228       ((null sval) res)
229     (setq res t)))
230
231 ;;; Serve a single set of events.
232 (defun serve-event (&optional timeout)
233   #!+sb-doc
234   "Receive pending events on all FD-STREAMS and dispatch to the appropriate
235 handler functions. If timeout is specified, server will wait the specified
236 time (in seconds) and then return, otherwise it will wait until something
237 happens. Server returns T if something happened and NIL otherwise. Timeout
238 0 means polling without waiting."
239   (multiple-value-bind (to-sec to-usec stop-sec stop-usec signalp)
240       (decode-timeout timeout)
241     (declare (ignore stop-sec stop-usec))
242     (sub-serve-event to-sec to-usec signalp)))
243
244 ;;; Takes timeout broken into seconds and microseconds, NIL timeout means
245 ;;; to wait as long as needed.
246 (defun sub-serve-event (to-sec to-usec deadlinep)
247   (or
248    (if *periodic-polling-function*
249        (multiple-value-bind (p-sec p-usec)
250            (decode-internal-time
251             (seconds-to-internal-time *periodic-polling-period*))
252          (if to-sec
253              (loop repeat (/ (+ to-sec (/ to-usec 1e6))
254                              *periodic-polling-period*)
255                    thereis (sub-sub-serve-event p-sec p-usec)
256                    do (funcall *periodic-polling-function*))
257              (loop thereis (sub-sub-serve-event p-sec p-usec)
258                    do (funcall *periodic-polling-function*))))
259        (sub-sub-serve-event to-sec to-usec))
260    (when deadlinep
261      (signal-deadline))))
262
263 ;;; Handles the work of the above, except for periodic polling. Returns
264 ;;; true if something of interest happened.
265 (defun sub-sub-serve-event (to-sec to-usec)
266   (sb!alien:with-alien ((read-fds (sb!alien:struct sb!unix:fd-set))
267                         (write-fds (sb!alien:struct sb!unix:fd-set)))
268     (sb!unix:fd-zero read-fds)
269     (sb!unix:fd-zero write-fds)
270     (let ((count 0))
271       (declare (type index count))
272
273       ;; Initialize the fd-sets for UNIX-SELECT and return the active
274       ;; descriptor count.
275       (map-descriptor-handlers
276        (lambda (handler)
277          ;; FIXME: If HANDLER-ACTIVE ever is reinstanted, it needs
278          ;; to be checked here in addition to HANDLER-BOGUS
279          (unless (handler-bogus handler)
280            (let ((fd (handler-descriptor handler)))
281              (ecase (handler-direction handler)
282                (:input (sb!unix:fd-set fd read-fds))
283                (:output (sb!unix:fd-set fd write-fds)))
284              (when (> fd count)
285                (setf count fd))))))
286       (incf count)
287
288       ;; Next, wait for something to happen.
289       (multiple-value-bind (value err)
290           (sb!unix:unix-fast-select count
291                                     (sb!alien:addr read-fds)
292                                     (sb!alien:addr write-fds)
293                                     nil to-sec to-usec)
294         #!+win32
295         (declare (ignore err))
296         ;; Now see what it was (if anything)
297         (cond ((not value)
298                ;; Interrupted or one of the file descriptors is bad.
299                ;; FIXME: Check for other errnos. Why do we return true
300                ;; when interrupted?
301                #!-win32
302                (case err
303                  (#.sb!unix:ebadf
304                   (handler-descriptors-error))
305                  ((#.sb!unix:eintr #.sb!unix:eagain)
306                   t)
307                  (otherwise
308                   (with-simple-restart (continue "Ignore failure and continue.")
309                     (simple-perror "Unix system call select() failed"
310                                    :errno err))))
311                #!+win32
312                (handler-descriptors-error))
313               ((plusp value)
314                ;; Got something. Call file descriptor handlers
315                ;; according to the readable and writable masks
316                ;; returned by select.
317                (dolist (handler
318                         (select-descriptor-handlers
319                          (lambda (handler)
320                            (let ((fd (handler-descriptor handler)))
321                              (ecase (handler-direction handler)
322                                (:input (sb!unix:fd-isset fd read-fds))
323                                (:output (sb!unix:fd-isset fd write-fds)))))))
324                  (with-simple-restart (remove-fd-handler "Remove ~S" handler)
325                    (funcall (handler-function handler)
326                             (handler-descriptor handler))
327                    (go :next))
328                  (remove-fd-handler handler)
329                  :next)
330                t))))))
331