1 ;;;; This software is part of the SBCL system. See the README file for
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.
10 (in-package "SB!IMPL")
12 ;;;; file descriptor I/O noise
15 (:constructor make-handler (direction descriptor function))
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.
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".
28 (function nil :type function)
29 ;; T if this descriptor is bogus.
32 (def!method print-object ((handler handler) stream)
33 (print-unreadable-object (handler stream :type t)
35 "~A on ~:[~;BOGUS ~]descriptor ~W: ~S"
36 (handler-direction handler)
37 (handler-bogus handler)
38 (handler-descriptor handler)
39 (handler-function handler))))
41 (defvar *descriptor-handlers* nil
43 "List of all the currently active handlers for file descriptors")
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))
51 (defun list-all-descriptor-handlers ()
52 (with-descriptor-handlers
53 (copy-list *descriptor-handlers*)))
55 (defun select-descriptor-handlers (function)
56 (declare (function function))
57 (with-descriptor-handlers
58 (remove-if-not function *descriptor-handlers*)))
60 (defun map-descriptor-handlers (function)
61 (declare (function function))
62 (with-descriptor-handlers
63 (dolist (handler *descriptor-handlers*)
64 (funcall function handler))))
66 ;;; Add a new handler to *descriptor-handlers*.
67 (defun add-fd-handler (fd direction function)
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*))
82 ;;; Remove an old handler from *descriptor-handlers*.
83 (defun remove-fd-handler (handler)
85 "Removes HANDLER from the list of active handlers."
86 (with-descriptor-handlers
87 (setf *descriptor-handlers*
88 (delete handler *descriptor-handlers*))))
90 ;;; Search *descriptor-handlers* for any reference to fd, and nuke 'em.
91 (defun invalidate-descriptor (fd)
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))))
100 ;;; Add the handler to *descriptor-handlers* for the duration of BODY.
101 (defmacro with-fd-handler ((fd direction function) &rest body)
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)))
110 (setf ,handler (add-fd-handler ,fd ,direction ,function))
113 (remove-fd-handler ,handler))))))
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)))
125 (restart-case (error "~S ~[have~;has a~:;have~] bad file descriptor~:P."
126 bogus-handlers (length bogus-handlers))
128 :report "Remove bogus handlers."
129 (with-descriptor-handlers
130 (setf *descriptor-handlers*
131 (delete-if #'handler-bogus *descriptor-handlers*))))
133 :report "Retry bogus handlers."
134 (dolist (handler bogus-handlers)
135 (setf (handler-bogus handler) nil)))
137 :report "Go on, leaving handlers marked as bogus."))))
141 ;;;; SERVE-ALL-EVENTS, SERVE-EVENT, and friends
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.")
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
162 (defun wait-until-fd-usable (fd direction &optional timeout (serve-events t))
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.
168 If SERVE-EVENTS is true (the default), events on other FDs are served while
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)))
185 (return-from wait-until-fd-usable nil))))))
186 (if (and serve-events
187 ;; No timeout or non-zero timeout
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!)
199 (sub-serve-event to-sec to-usec signalp)
201 (return-from wait-until-fd-usable t))
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))
208 when (or #!+win32 (eq direction :output)
209 #!+win32 (sb!win32:handle-listen
210 (sb!win32:get-osfhandle fd))
212 (sb!unix:unix-simple-poll fd direction to-msec))
213 do (return-from wait-until-fd-usable t)
215 do (when to-sec (maybe-update-timeout))
216 #!+win32 (sb!thread:thread-yield)))))))
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)
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."
227 (sval (serve-event timeout) (serve-event 0)))
231 ;;; Serve a single set of events.
232 (defun serve-event (&optional timeout)
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)))
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)
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*))
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))
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)
271 (declare (type index count))
273 ;; Initialize the fd-sets for UNIX-SELECT and return the active
275 (map-descriptor-handlers
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)))
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)
295 (declare (ignore err))
296 ;; Now see what it was (if anything)
298 ;; Interrupted or one of the file descriptors is bad.
299 ;; FIXME: Check for other errnos. Why do we return true
304 (handler-descriptors-error))
305 ((#.sb!unix:eintr #.sb!unix:eagain)
308 (with-simple-restart (continue "Ignore failure and continue.")
309 (simple-perror "Unix system call select() failed"
312 (handler-descriptors-error))
314 ;; Got something. Call file descriptor handlers
315 ;; according to the readable and writable masks
316 ;; returned by select.
318 (select-descriptor-handlers
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))
328 (remove-fd-handler handler)