Debian Codegraph @

src/kqueue.rs

raw symbols SCIP
1 //! Bindings to kqueue (macOS, iOS, tvOS, watchOS, visionOS, FreeBSD, NetBSD, OpenBSD, DragonFly BSD).
2
3 use std::collections::HashSet;
4 use std::io;
5 use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
6 use std::sync::RwLock;
7 use std::time::Instant;
8
9 use rustix::buffer::spare_capacity;
10 use rustix::event::{kqueue, Timespec};
11 use rustix::io::{fcntl_setfd, Errno, FdFlags};
12
13 use crate::{Event, PollMode};
14
15 /// Interface to kqueue.
16 #[derive(Debug)]
17 pub struct Poller {
18 /// File descriptor for the kqueue instance.
19 kqueue_fd: OwnedFd,
20
21 /// List of sources currently registered in this poller.
22 ///
23 /// This is used to make sure the same source is not registered twice.
24 sources: RwLock<HashSet<SourceId>>,
25
26 /// Notification pipe for waking up the poller.
27 ///
28 /// On platforms that support `EVFILT_USER`, this uses that to wake up the poller. Otherwise, it
29 /// uses a pipe.
30 notify: notify::Notify,
31 }
32
33 /// Identifier for a source.
34 #[doc(hidden)]
35 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
36 pub enum SourceId {
37 /// Registered file descriptor.
38 Fd(RawFd),
39
40 /// Signal.
41 Signal(std::os::raw::c_int),
42
43 /// Process ID.
44 Pid(rustix::process::Pid),
45
46 /// Timer ID.
47 Timer(usize),
48 }
49
50 impl Poller {
51 /// Creates a new poller.
52 pub fn new() -> io::Result<Poller> {
53 // Create a kqueue instance.
54 let kqueue_fd = kqueue::kqueue()?;
55 fcntl_setfd(&kqueue_fd, FdFlags::CLOEXEC)?;
56
57 let poller = Poller {
58 kqueue_fd,
59 sources: RwLock::new(HashSet::new()),
60 notify: notify::Notify::new()?,
61 };
62
63 // Register the notification pipe.
64 poller.notify.register(&poller)?;
65
66 #[cfg(feature = "tracing")]
67 tracing::trace!(
68 kqueue_fd = ?poller.kqueue_fd.as_raw_fd(),
69 "new"
70 );
71 Ok(poller)
72 }
73
74 /// Whether this poller supports level-triggered events.
75 pub fn supports_level(&self) -> bool {
76 true
77 }
78
79 /// Whether this poller supports edge-triggered events.
80 pub fn supports_edge(&self) -> bool {
81 true
82 }
83
84 /// Adds a new file descriptor.
85 ///
86 /// # Safety
87 ///
88 /// The file descriptor must be valid and it must last until it is deleted.
89 pub unsafe fn add(&self, fd: RawFd, ev: Event, mode: PollMode) -> io::Result<()> {
90 self.add_source(SourceId::Fd(fd))?;
91
92 // File descriptors don't need to be added explicitly, so just modify the interest.
93 self.modify(BorrowedFd::borrow_raw(fd), ev, mode)
94 }
95
96 /// Modifies an existing file descriptor.
97 pub fn modify(&self, fd: BorrowedFd<'_>, ev: Event, mode: PollMode) -> io::Result<()> {
98 #[cfg(feature = "tracing")]
99 let span = if !self.notify.has_fd(fd) {
100 let span = tracing::trace_span!(
101 "add",
102 kqueue_fd = ?self.kqueue_fd.as_raw_fd(),
103 ?fd,
104 ?ev,
105 );
106 Some(span)
107 } else {
108 None
109 };
110 #[cfg(feature = "tracing")]
111 let _enter = span.as_ref().map(|s| s.enter());
112
113 self.has_source(SourceId::Fd(fd.as_raw_fd()))?;
114
115 let mode_flags = mode_to_flags(mode);
116
117 let read_flags = if ev.readable {
118 kqueue::EventFlags::ADD | mode_flags
119 } else {
120 kqueue::EventFlags::DELETE
121 };
122 let write_flags = if ev.writable {
123 kqueue::EventFlags::ADD | mode_flags
124 } else {
125 kqueue::EventFlags::DELETE
126 };
127
128 // A list of changes for kqueue.
129 let changelist = [
130 kqueue::Event::new(
131 kqueue::EventFilter::Read(fd.as_raw_fd()),
132 read_flags | kqueue::EventFlags::RECEIPT,
133 ev.key as _,
134 ),
135 kqueue::Event::new(
136 kqueue::EventFilter::Write(fd.as_raw_fd()),
137 write_flags | kqueue::EventFlags::RECEIPT,
138 ev.key as _,
139 ),
140 ];
141
142 // Apply changes.
143 self.submit_changes(changelist)
144 }
145
146 /// Submit one or more changes to the kernel queue and check to see if they succeeded.
147 pub(crate) fn submit_changes<A>(&self, changelist: A) -> io::Result<()>
148 where
149 A: Copy + AsRef<[kqueue::Event]> + AsMut<[kqueue::Event]>,
150 {
151 let mut eventlist = Vec::with_capacity(changelist.as_ref().len());
152
153 // Apply changes.
154 {
155 let changelist = changelist.as_ref();
156
157 unsafe {
158 kqueue::kevent_timespec(
159 &self.kqueue_fd,
160 changelist,
161 spare_capacity(&mut eventlist),
162 None,
163 )?;
164 }
165 }
166
167 // Check for errors.
168 for &ev in &eventlist {
169 let data = ev.data();
170
171 // Explanation for ignoring EPIPE: https://github.com/tokio-rs/mio/issues/582
172 if (ev.flags().contains(kqueue::EventFlags::ERROR))
173 && data != 0
174 && data != Errno::NOENT.raw_os_error() as _
175 && data != Errno::PIPE.raw_os_error() as _
176 {
177 return Err(io::Error::from_raw_os_error(data as _));
178 }
179 }
180
181 Ok(())
182 }
183
184 /// Add a source to the sources set.
185 #[inline]
186 pub(crate) fn add_source(&self, source: SourceId) -> io::Result<()> {
187 if self
188 .sources
189 .write()
190 .unwrap_or_else(|e| e.into_inner())
191 .insert(source)
192 {
193 Ok(())
194 } else {
195 Err(io::Error::from(io::ErrorKind::AlreadyExists))
196 }
197 }
198
199 /// Tell if a source is currently inside the set.
200 #[inline]
201 pub(crate) fn has_source(&self, source: SourceId) -> io::Result<()> {
202 if self
203 .sources
204 .read()
205 .unwrap_or_else(|e| e.into_inner())
206 .contains(&source)
207 {
208 Ok(())
209 } else {
210 Err(io::Error::from(io::ErrorKind::NotFound))
211 }
212 }
213
214 /// Remove a source from the sources set.
215 #[inline]
216 pub(crate) fn remove_source(&self, source: SourceId) -> io::Result<()> {
217 if self
218 .sources
219 .write()
220 .unwrap_or_else(|e| e.into_inner())
221 .remove(&source)
222 {
223 Ok(())
224 } else {
225 Err(io::Error::from(io::ErrorKind::NotFound))
226 }
227 }
228
229 /// Deletes a file descriptor.
230 pub fn delete(&self, fd: BorrowedFd<'_>) -> io::Result<()> {
231 // Simply delete interest in the file descriptor.
232 self.modify(fd, Event::none(0), PollMode::Oneshot)?;
233
234 self.remove_source(SourceId::Fd(fd.as_raw_fd()))
235 }
236
237 /// Waits for I/O events with an optional deadline.
238 pub fn wait_deadline(&self, events: &mut Events, deadline: Option<Instant>) -> io::Result<()> {
239 #[cfg(feature = "tracing")]
240 let span = tracing::trace_span!(
241 "wait",
242 kqueue_fd = ?self.kqueue_fd.as_raw_fd(),
243 ?deadline,
244 );
245 #[cfg(feature = "tracing")]
246 let _enter = span.enter();
247
248 let timeout = deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
249
250 // Timeout for kevent. In case of overflow, use no timeout.
251 let timeout = match timeout {
252 Some(t) => Timespec::try_from(t).ok(),
253 None => None,
254 };
255
256 // Wait for I/O events.
257 let changelist = [];
258 let _res = unsafe {
259 kqueue::kevent_timespec(
260 &self.kqueue_fd,
261 &changelist,
262 spare_capacity(&mut events.list),
263 timeout.as_ref(),
264 )?
265 };
266
267 #[cfg(feature = "tracing")]
268 tracing::trace!(
269 kqueue_fd = ?self.kqueue_fd.as_raw_fd(),
270 res = ?_res,
271 "new events",
272 );
273
274 // Clear the notification (if received) and re-register interest in it.
275 self.notify.reregister(self)?;
276
277 Ok(())
278 }
279
280 /// Sends a notification to wake up the current or next `wait()` call.
281 pub fn notify(&self) -> io::Result<()> {
282 #[cfg(feature = "tracing")]
283 let span = tracing::trace_span!(
284 "notify",
285 kqueue_fd = ?self.kqueue_fd.as_raw_fd(),
286 );
287 #[cfg(feature = "tracing")]
288 let _enter = span.enter();
289
290 self.notify.notify(self).ok();
291 Ok(())
292 }
293 }
294
295 impl AsRawFd for Poller {
296 fn as_raw_fd(&self) -> RawFd {
297 self.kqueue_fd.as_raw_fd()
298 }
299 }
300
301 impl AsFd for Poller {
302 fn as_fd(&self) -> BorrowedFd<'_> {
303 self.kqueue_fd.as_fd()
304 }
305 }
306
307 impl Drop for Poller {
308 fn drop(&mut self) {
309 #[cfg(feature = "tracing")]
310 let span = tracing::trace_span!(
311 "drop",
312 kqueue_fd = ?self.kqueue_fd.as_raw_fd(),
313 );
314 #[cfg(feature = "tracing")]
315 let _enter = span.enter();
316
317 let _ = self.notify.deregister(self);
318 }
319 }
320
321 /// A list of reported I/O events.
322 pub struct Events {
323 list: Vec<kqueue::Event>,
324 }
325
326 unsafe impl Send for Events {}
327
328 impl Events {
329 /// Creates an empty list.
330 pub fn with_capacity(cap: usize) -> Events {
331 Events {
332 list: Vec::with_capacity(cap),
333 }
334 }
335
336 /// Iterates over I/O events.
337 pub fn iter(&self) -> impl Iterator<Item = Event> + '_ {
338 // On some platforms, closing the read end of a pipe wakes up writers, but the
339 // event is reported as EVFILT_READ with the EV_EOF flag.
340 //
341 // https://github.com/golang/go/commit/23aad448b1e3f7c3b4ba2af90120bde91ac865b4
342 self.list.iter().map(|ev| Event {
343 key: ev.udata() as usize,
344 readable: matches!(
345 ev.filter(),
346 kqueue::EventFilter::Read(..)
347 | kqueue::EventFilter::Vnode { .. }
348 | kqueue::EventFilter::Proc { .. }
349 | kqueue::EventFilter::Signal { .. }
350 | kqueue::EventFilter::Timer { .. }
351 ),
352 writable: matches!(ev.filter(), kqueue::EventFilter::Write(..))
353 || (matches!(ev.filter(), kqueue::EventFilter::Read(..))
354 && (ev.flags().intersects(kqueue::EventFlags::EOF))),
355 extra: EventExtra,
356 })
357 }
358
359 /// Clears the list.
360 pub fn clear(&mut self) {
361 self.list.clear();
362 }
363
364 /// Get the capacity of the list.
365 pub fn capacity(&self) -> usize {
366 self.list.capacity()
367 }
368 }
369
370 /// Extra information associated with an event.
371 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
372 pub struct EventExtra;
373
374 impl EventExtra {
375 /// Create a new, empty version of this struct.
376 #[inline]
377 pub const fn empty() -> EventExtra {
378 EventExtra
379 }
380
381 /// Set the interrupt flag.
382 #[inline]
383 pub fn set_hup(&mut self, _value: bool) {
384 // No-op.
385 }
386
387 /// Set the priority flag.
388 #[inline]
389 pub fn set_pri(&mut self, _value: bool) {
390 // No-op.
391 }
392
393 /// Is the interrupt flag set?
394 #[inline]
395 pub fn is_hup(&self) -> bool {
396 false
397 }
398
399 /// Is the priority flag set?
400 #[inline]
401 pub fn is_pri(&self) -> bool {
402 false
403 }
404
405 #[inline]
406 pub fn is_connect_failed(&self) -> Option<bool> {
407 None
408 }
409
410 #[inline]
411 pub fn is_err(&self) -> Option<bool> {
412 None
413 }
414 }
415
416 pub(crate) fn mode_to_flags(mode: PollMode) -> kqueue::EventFlags {
417 use kqueue::EventFlags as EV;
418
419 match mode {
420 PollMode::Oneshot => EV::ONESHOT,
421 PollMode::Level => EV::empty(),
422 PollMode::Edge => EV::CLEAR,
423 PollMode::EdgeOneshot => EV::ONESHOT | EV::CLEAR,
424 }
425 }
426
427 #[cfg(any(
428 target_os = "freebsd",
429 target_os = "dragonfly",
430 target_vendor = "apple",
431 ))]
432 mod notify {
433 use super::Poller;
434 use rustix::event::kqueue;
435 use std::io;
436 #[cfg(feature = "tracing")]
437 use std::os::unix::io::BorrowedFd;
438
439 /// A notification pipe.
440 ///
441 /// This implementation uses `EVFILT_USER` to avoid allocating a pipe.
442 #[derive(Debug)]
443 pub(super) struct Notify;
444
445 impl Notify {
446 /// Creates a new notification pipe.
447 pub(super) fn new() -> io::Result<Self> {
448 Ok(Self)
449 }
450
451 /// Registers this notification pipe in the `Poller`.
452 pub(super) fn register(&self, poller: &Poller) -> io::Result<()> {
453 // Register an EVFILT_USER event.
454 poller.submit_changes([kqueue::Event::new(
455 kqueue::EventFilter::User {
456 ident: 0,
457 flags: kqueue::UserFlags::empty(),
458 user_flags: kqueue::UserDefinedFlags::new(0),
459 },
460 kqueue::EventFlags::ADD | kqueue::EventFlags::RECEIPT | kqueue::EventFlags::CLEAR,
461 crate::NOTIFY_KEY as _,
462 )])
463 }
464
465 /// Reregister this notification pipe in the `Poller`.
466 pub(super) fn reregister(&self, _poller: &Poller) -> io::Result<()> {
467 // We don't need to do anything, it's already registered as EV_CLEAR.
468 Ok(())
469 }
470
471 /// Notifies the `Poller`.
472 pub(super) fn notify(&self, poller: &Poller) -> io::Result<()> {
473 // Trigger the EVFILT_USER event.
474 poller.submit_changes([kqueue::Event::new(
475 kqueue::EventFilter::User {
476 ident: 0,
477 flags: kqueue::UserFlags::TRIGGER,
478 user_flags: kqueue::UserDefinedFlags::new(0),
479 },
480 kqueue::EventFlags::ADD | kqueue::EventFlags::RECEIPT,
481 crate::NOTIFY_KEY as _,
482 )])?;
483
484 Ok(())
485 }
486
487 /// Deregisters this notification pipe from the `Poller`.
488 pub(super) fn deregister(&self, poller: &Poller) -> io::Result<()> {
489 // Deregister the EVFILT_USER event.
490 poller.submit_changes([kqueue::Event::new(
491 kqueue::EventFilter::User {
492 ident: 0,
493 flags: kqueue::UserFlags::empty(),
494 user_flags: kqueue::UserDefinedFlags::new(0),
495 },
496 kqueue::EventFlags::DELETE | kqueue::EventFlags::RECEIPT,
497 crate::NOTIFY_KEY as _,
498 )])
499 }
500
501 /// Whether this raw file descriptor is associated with this pipe.
502 #[cfg(feature = "tracing")]
503 pub(super) fn has_fd(&self, _fd: BorrowedFd<'_>) -> bool {
504 false
505 }
506 }
507 }
508
509 #[cfg(not(any(
510 target_os = "freebsd",
511 target_os = "dragonfly",
512 target_vendor = "apple",
513 )))]
514 mod notify {
515 use super::Poller;
516 use crate::{Event, PollMode, NOTIFY_KEY};
517 use std::io::{self, prelude::*};
518 #[cfg(feature = "tracing")]
519 use std::os::unix::io::BorrowedFd;
520 use std::os::unix::{
521 io::{AsFd, AsRawFd},
522 net::UnixStream,
523 };
524
525 /// A notification pipe.
526 ///
527 /// This implementation uses a pipe to send notifications.
528 #[derive(Debug)]
529 pub(super) struct Notify {
530 /// The read end of the pipe.
531 read_stream: UnixStream,
532
533 /// The write end of the pipe.
534 write_stream: UnixStream,
535 }
536
537 impl Notify {
538 /// Creates a new notification pipe.
539 pub(super) fn new() -> io::Result<Self> {
540 let (read_stream, write_stream) = UnixStream::pair()?;
541 read_stream.set_nonblocking(true)?;
542 write_stream.set_nonblocking(true)?;
543
544 Ok(Self {
545 read_stream,
546 write_stream,
547 })
548 }
549
550 /// Registers this notification pipe in the `Poller`.
551 pub(super) fn register(&self, poller: &Poller) -> io::Result<()> {
552 // Register the read end of this pipe.
553 unsafe {
554 poller.add(
555 self.read_stream.as_raw_fd(),
556 Event::readable(NOTIFY_KEY),
557 PollMode::Oneshot,
558 )
559 }
560 }
561
562 /// Reregister this notification pipe in the `Poller`.
563 pub(super) fn reregister(&self, poller: &Poller) -> io::Result<()> {
564 // Clear out the notification.
565 while (&self.read_stream).read(&mut [0; 64]).is_ok() {}
566
567 // Reregister the read end of this pipe.
568 poller.modify(
569 self.read_stream.as_fd(),
570 Event::readable(NOTIFY_KEY),
571 PollMode::Oneshot,
572 )
573 }
574
575 /// Notifies the `Poller`.
576 #[allow(clippy::unused_io_amount)]
577 pub(super) fn notify(&self, _poller: &Poller) -> io::Result<()> {
578 // Write to the write end of the pipe
579 (&self.write_stream).write(&[1])?;
580
581 Ok(())
582 }
583
584 /// Deregisters this notification pipe from the `Poller`.
585 pub(super) fn deregister(&self, poller: &Poller) -> io::Result<()> {
586 // Deregister the read end of the pipe.
587 poller.delete(self.read_stream.as_fd())
588 }
589
590 /// Whether this raw file descriptor is associated with this pipe.
591 #[cfg(feature = "tracing")]
592 pub(super) fn has_fd(&self, fd: BorrowedFd<'_>) -> bool {
593 self.read_stream.as_raw_fd() == fd.as_raw_fd()
594 }
595 }
596 }