Debian Codegraph @

src/sys/epoll.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 use std::os::unix::io::{AsRawFd, RawFd};
2
3 use super::{Interest, Mode, PollEvent, Readiness, Token};
4
5 use nix::sys::{
6 epoll::{
7 epoll_create1, epoll_ctl, epoll_wait, EpollCreateFlags, EpollEvent, EpollFlags, EpollOp,
8 },
9 time::TimeSpec,
10 timerfd::{ClockId, Expiration, TimerFd, TimerFlags, TimerSetTimeFlags},
11 };
12
13 pub struct Epoll {
14 epoll_fd: RawFd,
15 timer_fd: Option<TimerFd>,
16 }
17
18 const TIMER_DATA: u64 = u64::MAX;
19
20 fn make_flags(interest: Interest, mode: Mode) -> EpollFlags {
21 let mut flags = EpollFlags::empty();
22 if interest.readable {
23 flags |= EpollFlags::EPOLLIN;
24 }
25 if interest.writable {
26 flags |= EpollFlags::EPOLLOUT;
27 }
28 match mode {
29 Mode::Level => { /* This is the default */ }
30 Mode::Edge => flags |= EpollFlags::EPOLLET,
31 Mode::OneShot => flags |= EpollFlags::EPOLLONESHOT,
32 }
33 flags
34 }
35
36 fn flags_to_readiness(flags: EpollFlags) -> Readiness {
37 Readiness {
38 readable: flags.contains(EpollFlags::EPOLLIN),
39 writable: flags.contains(EpollFlags::EPOLLOUT),
40 error: flags.contains(EpollFlags::EPOLLERR),
41 }
42 }
43
44 impl Epoll {
45 pub(crate) fn new(high_precision: bool) -> crate::Result<Epoll> {
46 let epoll_fd = epoll_create1(EpollCreateFlags::EPOLL_CLOEXEC)?;
47 let mut timer_fd = None;
48 if high_precision {
49 // Prepare a timerfd for precise time tracking and register it to the event queue
50 // This timerfd allows for nanosecond precision in setting the timout up (though in practice
51 // we rather get ~10 microsecond precision), while epoll_wait() API only allows millisecond
52 // granularity
53 let timer = TimerFd::new(
54 ClockId::CLOCK_MONOTONIC,
55 TimerFlags::TFD_CLOEXEC | TimerFlags::TFD_NONBLOCK,
56 )?;
57 let mut timer_event = EpollEvent::new(EpollFlags::EPOLLIN, TIMER_DATA);
58 epoll_ctl(
59 epoll_fd,
60 EpollOp::EpollCtlAdd,
61 timer.as_raw_fd(),
62 &mut timer_event,
63 )?;
64 timer_fd = Some(timer);
65 }
66 Ok(Epoll { epoll_fd, timer_fd })
67 }
68
69 pub(crate) fn poll(
70 &mut self,
71 timeout: Option<std::time::Duration>,
72 ) -> crate::Result<Vec<PollEvent>> {
73 let mut buffer = [EpollEvent::empty(); 32];
74 if let Some(ref timer) = self.timer_fd {
75 if let Some(timeout) = timeout {
76 // Set up the precise timer
77 timer.set(
78 Expiration::OneShot(TimeSpec::from_duration(timeout)),
79 TimerSetTimeFlags::empty(),
80 )?;
81 }
82 }
83 // add 1 to the millisecond wait, to round up for timer tracking. If the high precision timer is set up
84 // it'll fire before that timeout
85 let timeout = timeout.map(|d| (d.as_millis() + 1) as isize).unwrap_or(-1);
86 let n_ready = epoll_wait(self.epoll_fd, &mut buffer, timeout)?;
87 let events = buffer
88 .iter()
89 .take(n_ready)
90 .flat_map(|event| {
91 if event.data() == TIMER_DATA {
92 // We woke up because the high-precision timer fired, we need to disarm it by reading its
93 // contents to ensure it will be ready for next time
94 // Timer is created in non-blocking mode, and should have already fired anyway, this
95 // cannot possibly block
96 let _ = self
97 .timer_fd
98 .as_ref()
99 .expect("Got an event from high-precision timer while it is not set up?!")
100 .wait();
101 // don't forward this event to downstream
102 None
103 } else {
104 // In C, the underlying data type is a union including a void
105 // pointer; in Rust's FFI bindings, it only exposes the u64. The
106 // round-trip conversion is valid however.
107 let token_ptr = event.data() as usize as *const Token;
108 Some(PollEvent {
109 readiness: flags_to_readiness(event.events()),
110 // Why this is safe: it points to memory boxed and owned by
111 // the parent Poller type.
112 token: unsafe { *token_ptr },
113 })
114 }
115 })
116 .collect();
117 if let Some(ref timer) = self.timer_fd {
118 // in all cases, disarm the timer
119 timer.unset()?;
120 // clear the timer in case it fired between epoll_wait and now, as timer is in
121 // non-blocking mode, this will return Err(WouldBlock) if it had not fired, so
122 // we ignore the error
123 let _ = timer.wait();
124 }
125 Ok(events)
126 }
127
128 pub fn register(
129 &mut self,
130 fd: RawFd,
131 interest: Interest,
132 mode: Mode,
133 token: *const Token,
134 ) -> crate::Result<()> {
135 let mut event = EpollEvent::new(make_flags(interest, mode), token as usize as u64);
136 epoll_ctl(self.epoll_fd, EpollOp::EpollCtlAdd, fd, &mut event).map_err(Into::into)
137 }
138
139 pub fn reregister(
140 &mut self,
141 fd: RawFd,
142 interest: Interest,
143 mode: Mode,
144 token: *const Token,
145 ) -> crate::Result<()> {
146 let mut event = EpollEvent::new(make_flags(interest, mode), token as usize as u64);
147 epoll_ctl(self.epoll_fd, EpollOp::EpollCtlMod, fd, &mut event).map_err(Into::into)
148 }
149
150 pub fn unregister(&mut self, fd: RawFd) -> crate::Result<()> {
151 epoll_ctl(self.epoll_fd, EpollOp::EpollCtlDel, fd, None).map_err(Into::into)
152 }
153 }
154
155 impl Drop for Epoll {
156 fn drop(&mut self) {
157 let _ = nix::unistd::close(self.epoll_fd);
158 }
159 }