Ifdef-ize the hopscotch hash stuff for non-x86.
[sbcl.git] / src / code / serve-event.lisp
blob5dd1a5117d4a473b3a14b1e6c29b30db1936ddd3
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.
10 (in-package "SB!IMPL")
12 ;;;; file descriptor I/O noise
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 #!-os-provides-poll (mod #.sb!unix:fd-setsize)
21 #!+os-provides-poll (and fixnum unsigned-byte))
22 ;; T iff this handler is running.
24 ;; FIXME: unused. At some point this used to be set to T
25 ;; around the call to the handler-function, but that was commented
26 ;; out with the verbose explantion "Doesn't work -- ACK".
27 active
28 ;; Function to call.
29 (function nil :type function)
30 ;; T if this descriptor is bogus.
31 bogus)
33 (defstruct (pollfds (:constructor make-pollfds (list)))
34 (list)
35 ;; If using poll() we maintain, in addition to a list of HANDLER,
36 ;; an (ALIEN (* STRUCT POLLFD)) to avoid creating it repeatedly.
37 ;; The C array is created only when SUB-SUB-SERVE-EVENT needs it,
38 ;; not on each call to ADD/REMOVE-FD-HANDLER.
39 ;; If using select(), the C array is not used.
40 #!+os-provides-poll (fds) ;
41 ;; N-FDS is less than or equal to the length of the C array,
42 ;; which is created potentially oversized.
43 #!+os-provides-poll (n-fds)
44 ;; map from index in LIST to index into alien FDS
45 #!+os-provides-poll (map))
47 (defmethod print-object ((handler handler) stream)
48 (print-unreadable-object (handler stream :type t)
49 (format stream
50 "~A on ~:[~;BOGUS ~]descriptor ~W: ~S"
51 (handler-direction handler)
52 (handler-bogus handler)
53 (handler-descriptor handler)
54 (handler-function handler))))
56 (defvar *descriptor-handlers* nil
57 "List of all the currently active handlers for file descriptors")
59 (sb!xc:defmacro with-descriptor-handlers (&body forms)
60 ;; FD-STREAM functionality can add and remove descriptors on it's
61 ;; own, so getting an interrupt while modifying this and the
62 ;; starting to recursively modify it could lose...
63 `(without-interrupts ,@forms))
65 ;; Deallocating the pollfds is a no-op if not using poll()
66 #!-os-provides-poll (declaim (inline deallocate-pollfds))
68 ;; Free the cached C structures, if allocated.
69 ;; Must be called within the extent of WITH-DESCRIPTOR-HANDLERS.
70 (defun deallocate-pollfds ()
71 #!+os-provides-poll
72 (awhen *descriptor-handlers*
73 (when (pollfds-fds it)
74 (free-alien (pollfds-fds it)))
75 (setf (pollfds-fds it) nil
76 (pollfds-n-fds it) nil
77 (pollfds-map it) nil)))
79 (defun list-all-descriptor-handlers ()
80 (with-descriptor-handlers
81 (awhen *descriptor-handlers*
82 (copy-list (pollfds-list it)))))
84 ;; With the poll() interface it requires more care to maintain
85 ;; a correspondence betwen the Lisp and C representations.
86 #!-os-provides-poll
87 (defun select-descriptor-handlers (function)
88 (declare (function function))
89 (with-descriptor-handlers
90 (awhen *descriptor-handlers*
91 (remove-if-not function (pollfds-list it)))))
93 (defun map-descriptor-handlers (function)
94 (declare (function function))
95 (with-descriptor-handlers
96 (awhen *descriptor-handlers*
97 (dolist (handler (pollfds-list it))
98 (funcall function handler)))))
100 ;;; Add a new handler to *descriptor-handlers*.
101 (defun add-fd-handler (fd direction function)
102 "Arrange to call FUNCTION whenever FD is usable. DIRECTION should be
103 either :INPUT or :OUTPUT. The value returned should be passed to
104 SYSTEM:REMOVE-FD-HANDLER when it is no longer needed."
105 (unless (member direction '(:input :output))
106 ;; FIXME: should be TYPE-ERROR?
107 (error "Invalid direction ~S, must be either :INPUT or :OUTPUT" direction))
108 ;; lp#316068 - generate a more specific error than "X is not (MOD n)"
109 #!-os-provides-poll
110 (unless (<= 0 fd (1- sb!unix:fd-setsize))
111 (error "Cannot add an FD handler for ~D: not under FD_SETSIZE limit." fd))
112 (let ((handler (make-handler direction fd function)))
113 (with-descriptor-handlers
114 (deallocate-pollfds)
115 (let ((handlers *descriptor-handlers*))
116 (if (not handlers)
117 (setf *descriptor-handlers* (make-pollfds (list handler)))
118 (push handler (pollfds-list handlers)))))
119 handler))
121 (macrolet ((filter-handlers (newval-form)
122 `(with-descriptor-handlers
123 (deallocate-pollfds)
124 (let* ((holder *descriptor-handlers*)
125 (handlers (if holder (pollfds-list holder)))
126 (list ,newval-form))
127 ;; The case of "no handlers" is *DESCRIPTOR-HANDLERS* = NIL,
128 ;; like it starts as. So we set it back to NIL rather than
129 ;; an empty struct if no handlers remain.
130 (if list
131 ;; Since this macro is only for deletion of handlers,
132 ;; if LIST is not nil then HOLDER was too.
133 (setf (pollfds-list holder) list)
134 (setf *descriptor-handlers* nil))))))
136 ;;; Remove an old handler from *descriptor-handlers*.
137 (defun remove-fd-handler (handler)
138 "Removes HANDLER from the list of active handlers."
139 (filter-handlers (delete handler handlers)))
141 ;;; Search *descriptor-handlers* for any reference to fd, and nuke 'em.
142 (defun invalidate-descriptor (fd)
143 "Remove any handlers referring to FD. This should only be used when attempting
144 to recover from a detected inconsistency."
145 (filter-handlers (delete fd handlers :key #'handler-descriptor)))
147 ;;; Add the handler to *descriptor-handlers* for the duration of BODY.
148 ;;; Note: this makes the poll() interface not super efficient because
149 ;;; it discards the cached C array of (struct pollfd), as it must do
150 ;;; each time the list of Lisp HANDLER structs is touched.
151 (defmacro with-fd-handler ((fd direction function) &rest body)
152 "Establish a handler with SYSTEM:ADD-FD-HANDLER for the duration of BODY.
153 DIRECTION should be either :INPUT or :OUTPUT, FD is the file descriptor to
154 use, and FUNCTION is the function to call whenever FD is usable."
155 (let ((handler (gensym)))
156 `(let (,handler)
157 (unwind-protect
158 (progn
159 (setf ,handler (add-fd-handler ,fd ,direction ,function))
160 ,@body)
161 (when ,handler
162 (remove-fd-handler ,handler))))))
164 ;;; First, get a list and mark bad file descriptors. Then signal an error
165 ;;; offering a few restarts.
166 (defun handler-descriptors-error
167 #!+os-provides-poll (&optional (bogus-handlers nil handlers-supplied-p))
168 #!-os-provides-poll (&aux bogus-handlers handlers-supplied-p)
169 (if handlers-supplied-p
170 (dolist (handler bogus-handlers)
171 ;; no fstat() - the kernel deemed them bogus already
172 (setf (handler-bogus handler) t))
173 (dolist (handler (list-all-descriptor-handlers))
174 (unless (or (handler-bogus handler)
175 (sb!unix:unix-fstat (handler-descriptor handler)))
176 (setf (handler-bogus handler) t)
177 (push handler bogus-handlers))))
178 (when bogus-handlers
179 (restart-case (error "~S ~[have~;has a~:;have~] bad file descriptor~:P."
180 bogus-handlers (length bogus-handlers))
181 (remove-them ()
182 :report "Remove bogus handlers."
183 (filter-handlers (delete-if #'handler-bogus handlers)))
184 (retry-them ()
185 :report "Retry bogus handlers."
186 (dolist (handler bogus-handlers)
187 (setf (handler-bogus handler) nil)))
188 (continue ()
189 :report "Go on, leaving handlers marked as bogus.")))
190 nil))
193 ;;;; SERVE-ALL-EVENTS, SERVE-EVENT, and friends
195 ;;; When a *periodic-polling-function* is defined the server will not
196 ;;; block for more than the maximum event timeout and will call the
197 ;;; polling function if it does time out.
198 (declaim (type (or null symbol function) *periodic-polling-function*))
199 (defvar *periodic-polling-function* nil
200 "Either NIL, or a designator for a function callable without any
201 arguments. Called when the system has been waiting for input for
202 longer then *PERIODIC-POLLING-PERIOD* seconds. Shared between all
203 threads, unless locally bound. EXPERIMENTAL.")
204 (declaim (real *periodic-polling-period*))
205 (defvar *periodic-polling-period* 0
206 "A real number designating the number of seconds to wait for input
207 at maximum, before calling the *PERIODIC-POLLING-FUNCTION* \(if any.)
208 Shared between all threads, unless locally bound. EXPERIMENTAL.")
210 ;;; Wait until FD is usable for DIRECTION. The timeout given to serve-event is
211 ;;; recalculated each time through the loop so that WAIT-UNTIL-FD-USABLE will
212 ;;; timeout at the correct time irrespective of how many events are handled in
213 ;;; the meantime.
214 (defun wait-until-fd-usable (fd direction &optional timeout (serve-events t))
215 "Wait until FD is usable for DIRECTION. DIRECTION should be either :INPUT or
216 :OUTPUT. TIMEOUT, if supplied, is the number of seconds to wait before giving
217 up. Returns true once the FD is usable, NIL return indicates timeout.
219 If SERVE-EVENTS is true (the default), events on other FDs are served while
220 waiting."
221 (tagbody
222 :restart
223 (multiple-value-bind (to-sec to-usec stop-sec stop-usec signalp)
224 (decode-timeout timeout)
225 (declare (type (or integer null) to-sec to-usec))
226 (flet ((maybe-update-timeout ()
227 ;; If we return early, recompute the timeouts, possibly
228 ;; signaling the deadline or returning with NIL to caller.
229 (setf (values to-sec to-usec)
230 (relative-decoded-times stop-sec stop-usec))
231 (when (and (zerop to-sec) (not (plusp to-usec)))
232 (cond (signalp
233 (signal-deadline)
234 (go :restart))
236 (return-from wait-until-fd-usable nil))))))
237 (if (and serve-events
238 ;; No timeout or non-zero timeout
239 (or (not to-sec)
240 (not (= 0 to-sec to-usec)))
241 ;; Something to do while we wait
242 (or *descriptor-handlers* *periodic-polling-function*))
243 ;; Loop around SUB-SERVE-EVENT till done.
244 (dx-let ((usable (list nil)))
245 (dx-flet ((usable! (fd)
246 (declare (ignore fd))
247 (setf (car usable) t)))
248 (with-fd-handler (fd direction #'usable!)
249 (loop
250 (sub-serve-event to-sec to-usec signalp)
251 (when (car usable)
252 (return-from wait-until-fd-usable t))
253 (when to-sec
254 (maybe-update-timeout))))))
255 ;; If we don't have to serve events, just poll on the single FD instead.
256 (loop for to-msec = (if (and to-sec to-usec)
257 (+ (* 1000 to-sec) (truncate to-usec 1000))
259 when (or #!+win32 (eq direction :output)
260 #!+win32 (sb!win32:handle-listen fd)
261 #!-win32
262 (sb!unix:unix-simple-poll fd direction to-msec))
263 do (return-from wait-until-fd-usable t)
264 else
265 do (when to-sec (maybe-update-timeout))
266 #!+win32 (sb!thread:thread-yield)))))))
268 ;;; Wait for up to timeout seconds for an event to happen. Make sure all
269 ;;; pending events are processed before returning.
270 (defun serve-all-events (&optional timeout)
271 "SERVE-ALL-EVENTS calls SERVE-EVENT with the specified timeout. If
272 SERVE-EVENT does something (returns T) it loops over SERVE-EVENT with a
273 timeout of 0 until there are no more events to serve. SERVE-ALL-EVENTS returns
274 T if SERVE-EVENT did something and NIL if not."
275 (do ((res nil)
276 (sval (serve-event timeout) (serve-event 0)))
277 ((null sval) res)
278 (setq res t)))
280 ;;; Serve a single set of events.
281 (defun serve-event (&optional timeout)
282 "Receive pending events on all FD-STREAMS and dispatch to the appropriate
283 handler functions. If timeout is specified, server will wait the specified
284 time (in seconds) and then return, otherwise it will wait until something
285 happens. Server returns T if something happened and NIL otherwise. Timeout
286 0 means polling without waiting."
287 (multiple-value-bind (to-sec to-usec stop-sec stop-usec signalp)
288 (decode-timeout timeout)
289 (declare (ignore stop-sec stop-usec))
290 (sub-serve-event to-sec to-usec signalp)))
292 ;;; Takes timeout broken into seconds and microseconds, NIL timeout means
293 ;;; to wait as long as needed.
294 (defun sub-serve-event (to-sec to-usec deadlinep)
296 (if *periodic-polling-function*
297 (multiple-value-bind (p-sec p-usec)
298 (decode-internal-time
299 (seconds-to-internal-time *periodic-polling-period*))
300 (if to-sec
301 (loop repeat (/ (+ to-sec (/ to-usec 1e6))
302 *periodic-polling-period*)
303 thereis (sub-sub-serve-event p-sec p-usec)
304 do (funcall *periodic-polling-function*))
305 (loop thereis (sub-sub-serve-event p-sec p-usec)
306 do (funcall *periodic-polling-function*))))
307 (sub-sub-serve-event to-sec to-usec))
308 (when deadlinep
309 (signal-deadline))))
311 ;;; Handles the work of the above, except for periodic polling. Returns
312 ;;; true if something of interest happened.
313 #!-os-provides-poll
314 (defun sub-sub-serve-event (to-sec to-usec)
315 (with-alien ((read-fds (struct sb!unix:fd-set))
316 (write-fds (struct sb!unix:fd-set)))
317 (sb!unix:fd-zero read-fds)
318 (sb!unix:fd-zero write-fds)
319 (let ((count 0))
320 (declare (type index count))
322 ;; Initialize the fd-sets for UNIX-SELECT and return the active
323 ;; descriptor count.
324 (map-descriptor-handlers
325 (lambda (handler)
326 ;; FIXME: If HANDLER-ACTIVE ever is reinstanted, it needs
327 ;; to be checked here in addition to HANDLER-BOGUS
328 (unless (handler-bogus handler)
329 (let ((fd (handler-descriptor handler)))
330 (ecase (handler-direction handler)
331 (:input (sb!unix:fd-set fd read-fds))
332 (:output (sb!unix:fd-set fd write-fds)))
333 (when (> fd count)
334 (setf count fd))))))
335 (incf count)
337 ;; Next, wait for something to happen.
338 (multiple-value-bind (value err)
339 (sb!unix:unix-fast-select count
340 (addr read-fds)
341 (addr write-fds)
342 nil to-sec to-usec)
343 #!+win32
344 (declare (ignore err))
345 ;; Now see what it was (if anything)
346 (cond ((not value)
347 ;; Interrupted or one of the file descriptors is bad.
348 ;; FIXME: Check for other errnos. Why do we return true
349 ;; when interrupted?
350 #!-win32
351 (case err
352 (#.sb!unix:ebadf
353 (handler-descriptors-error))
354 ((#.sb!unix:eintr #.sb!unix:eagain)
356 (otherwise
357 (with-simple-restart (continue "Ignore failure and continue.")
358 (simple-perror "Unix system call select() failed"
359 :errno err))))
360 #!+win32
361 (handler-descriptors-error))
362 ((plusp value)
363 ;; Got something. Call file descriptor handlers
364 ;; according to the readable and writable masks
365 ;; returned by select.
366 (dolist (handler
367 (select-descriptor-handlers
368 (lambda (handler)
369 (let ((fd (handler-descriptor handler)))
370 (ecase (handler-direction handler)
371 (:input (sb!unix:fd-isset fd read-fds))
372 (:output (sb!unix:fd-isset fd write-fds)))))))
373 (with-simple-restart (remove-fd-handler "Remove ~S" handler)
374 (funcall (handler-function handler)
375 (handler-descriptor handler))
376 (go :next))
377 (remove-fd-handler handler)
378 :next)
379 t))))))
381 ;; Return an pointer to an array of (struct pollfd).
382 ;; This isn't done via WITH-ALIEN for 2 reasons:
383 ;; 1. WITH-ALIEN can't make variable-length arrays
384 ;; 2. it's slightly nontrivial to condense the :input and :output masks
385 ;; Making USE-SCRATCHPAD-P an optional argument is a KLUDGE, but it allows
386 ;; picking which method of file descriptor de-duplication is used,
387 ;; so that both can be exercised by tests.
388 #!+os-provides-poll
389 (defun compute-pollfds (handlers &optional
390 (n-handlers (length handlers))
391 (use-scratchpad-p (>= n-handlers 15)))
392 ;; Assuming that all fds in HANDLERS are unique and none are bogus,
393 ;; either of which could be untrue,
394 ;; allocate the maximum length C array we'd need.
395 ;; Since interrupts are disabled inside WITH-DESCRIPTOR-HANDLERS,
396 ;; and *DESCRIPTOR-HANDLERS* is per-thread, double traversal is ok.
397 (let* ((fds (make-alien (struct sb!unix:pollfd) n-handlers))
398 (map (make-array n-handlers :initial-element nil))
399 (n-fds 0)
400 (handler-index -1))
401 (labels ((flag-bit (handler)
402 (ecase (handler-direction handler)
403 (:input sb!unix:pollin)
404 (:output sb!unix:pollout)))
405 (set-flag (handler)
406 (let ((fd-index n-fds))
407 (incf n-fds)
408 (setf (slot (deref fds fd-index) 'sb!unix:fd)
409 (handler-descriptor handler)
410 (slot (deref fds fd-index) 'sb!unix:events)
411 (flag-bit handler))
412 fd-index))
413 (or-flag (index handler)
414 (setf (slot (deref fds index) 'sb!unix:events)
415 (logior (slot (deref fds index) 'sb!unix:events)
416 (flag-bit handler)))))
417 ;; Now compute unique non-bogus file descriptors.
418 (if use-scratchpad-p
419 ;; This is O(N), but wastes space if there are, say, 16 descriptors
420 ;; numbered 1 through 15 and then 1025.
421 (let ((scratchpad ; direct map from file descriptor to position in FDS
422 (make-array (1+ (loop for handler in handlers
423 maximize (handler-descriptor handler)))
424 :initial-element nil)))
425 (dolist (handler handlers)
426 (incf handler-index)
427 (unless (handler-bogus handler)
428 (let* ((fd (handler-descriptor handler))
429 (fd-index (svref scratchpad fd)))
430 (if fd-index
431 (or-flag fd-index handler)
432 (setf fd-index (set-flag handler)
433 (svref scratchpad fd) fd-index))
434 (setf (svref map handler-index) fd-index)))))
435 ;; This is O(N^2) but fast for small inputs.
436 (dolist (handler handlers)
437 (incf handler-index)
438 (unless (handler-bogus handler)
439 (let ((dup-of (position (handler-descriptor handler)
440 handlers :key (lambda (x)
441 (unless (handler-bogus x)
442 (handler-descriptor x)))
443 :end handler-index))
444 (fd-index nil))
445 (if dup-of ; fd already got an index into pollfds
446 (or-flag (setq fd-index (svref map dup-of)) handler)
447 (setq fd-index (set-flag handler)))
448 (setf (svref map handler-index) fd-index))))))
449 (values fds n-fds map)))
451 ;;; Handles the work of the above, except for periodic polling. Returns
452 ;;; true if something of interest happened.
453 #!+os-provides-poll
454 (defun sub-sub-serve-event (to-sec to-usec)
455 (let (list fds count map)
456 (with-descriptor-handlers
457 (let ((handlers *descriptor-handlers*))
458 (when handlers
459 (setq list (pollfds-list handlers)
460 fds (pollfds-fds handlers)
461 count (pollfds-n-fds handlers)
462 map (pollfds-map handlers))
463 (when (and list (not fds)) ; make the C array
464 (multiple-value-setq (fds count map) (compute-pollfds list))
465 (setf (pollfds-fds handlers) fds
466 (pollfds-n-fds handlers) count
467 (pollfds-map handlers) map)))))
468 ;; poll() wants the timeout in milliseconds.
469 (let ((to-millisec
470 (if (or (null to-sec) (null to-usec))
472 (ceiling (+ (* to-sec 1000000) to-usec) 1000))))
473 ;; Next, wait for something to happen.
474 (multiple-value-bind (value err)
475 (if list
476 (sb!unix:unix-poll fds count to-millisec)
477 ;; If invoked with no descriptors only for the effect of waiting
478 ;; until the timeout, make a valid pointer to a (struct pollfd).
479 (with-alien ((a (struct sb!unix:pollfd)))
480 (sb!unix:unix-poll a 0 to-millisec)))
481 ;; From here down is mostly the same as the code
482 ;; for #!-os-provides-poll.
484 ;; Now see what it was (if anything)
485 (cond ((not value)
486 ;; Interrupted or one of the file descriptors is bad.
487 ;; FIXME: Check for other errnos. Why do we return true
488 ;; when interrupted?
489 (case err
490 (#.sb!unix:ebadf
491 ;; poll() should never return EBADF, but I'm afraid that by
492 ;; removing this, someone will find a broken OS which does.
493 (handler-descriptors-error))
494 ((#.sb!unix:eintr #.sb!unix:eagain)
496 (otherwise
497 (with-simple-restart (continue "Ignore failure and continue.")
498 (simple-perror "Unix system call poll() failed"
499 :errno err)))))
500 ((plusp value)
501 ;; Got something. Scan the 'revents' fields of the pollfds
502 ;; to decide what to call.
503 ;; The #!-os-provides-poll code looks at *DESCRIPTOR-HANDLERS*
504 ;; again at this point, which seems wrong, but not terribly wrong
505 ;; because at worst there will be a a zero bit for a handler's
506 ;; descriptor. But I can't see how it would make sense here to
507 ;; look again because if anything changed, then the map of
508 ;; handler to index into the C array was necessarily clobbered.
509 (loop for handler in list
510 for fd-index across map
511 for revents = (slot (deref fds fd-index) 'sb!unix:revents)
512 when (logtest revents sb!unix:pollnval)
513 collect handler into bad
514 ;; James Knight says that if POLLERR is set, user code
515 ;; _should_ attempt to perform I/O to observe the error.
516 ;; So we trigger either handler direction.
517 else when (logtest revents
518 (ecase (handler-direction handler)
519 ;; POLLHUP implies read will not block
520 (:input (logior sb!unix:pollin
521 sb!unix:pollhup
522 sb!unix:pollerr))
523 (:output (logior sb!unix:pollout
524 sb!unix:pollerr))))
525 collect handler into good
526 finally
527 (return
528 (if bad
529 (handler-descriptors-error bad)
530 (dolist (handler good t)
531 (with-simple-restart (remove-fd-handler "Remove ~S" handler)
532 (funcall (handler-function handler)
533 (handler-descriptor handler))
534 (go :next))
535 (remove-fd-handler handler)
536 :next))))))))))