Debian Codegraph @

src/sources/ping/eventfd.rs

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1 //! Eventfd based implementation of the ping event source.
2 //!
3 //! # Implementation notes
4 //!
5 //! The eventfd is a much lighter signalling mechanism provided by the Linux
6 //! kernel. Rather than write an arbitrary sequence of bytes, it only has a
7 //! 64-bit counter.
8 //!
9 //! To avoid closing the eventfd early, we wrap it in a RAII-style closer
10 //! `CloseOnDrop` in `make_ping()`. When all the senders are dropped, another
11 //! wrapper `FlagOnDrop` handles signalling this to the event source, which is
12 //! the sole owner of the eventfd itself. The senders have weak references to
13 //! the eventfd, and if the source is dropped before the senders, they will
14 //! simply not do anything (except log a message).
15 //!
16 //! To differentiate between regular ping events and close ping events, we add 2
17 //! to the counter for regular events and 1 for close events. In the source we
18 //! can then check the LSB and if it's set, we know it was a close event. This
19 //! only works if a close event never fires more than once.
20
21 use std::{os::unix::io::RawFd, sync::Arc};
22 use std::os::fd::IntoRawFd;
23
24 use nix::sys::eventfd::{eventfd, EfdFlags};
25 use nix::unistd::{read, write};
26
27 use super::{CloseOnDrop, PingError};
28 use crate::{
29 generic::Generic, EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory,
30 };
31
32 // These are not bitfields! They are increments to add to the eventfd counter.
33 // Since the fd can only be closed once, we can effectively use the
34 // INCREMENT_CLOSE value as a bitmask when checking.
35 const INCREMENT_PING: u64 = 0x2;
36 const INCREMENT_CLOSE: u64 = 0x1;
37
38 #[inline]
39 pub fn make_ping() -> std::io::Result<(Ping, PingSource)> {
40 let read = eventfd(0, EfdFlags::EFD_CLOEXEC | EfdFlags::EFD_NONBLOCK)?;
41 let read = read.into_raw_fd();
42
43 // We only have one fd for the eventfd. If the sending end closes it when
44 // all copies are dropped, the receiving end will be closed as well. We need
45 // to make sure the fd is not closed until all holders of it have dropped
46 // it.
47
48 let fd_arc = Arc::new(CloseOnDrop(read));
49
50 let ping = Ping {
51 event: Arc::new(FlagOnDrop(Arc::clone(&fd_arc))),
52 };
53
54 let source = PingSource {
55 event: Generic::new(read, Interest::READ, Mode::Level),
56 _fd: fd_arc,
57 };
58
59 Ok((ping, source))
60 }
61
62 // Helper functions for the event source IO.
63
64 #[inline]
65 fn send_ping(fd: RawFd, count: u64) -> std::io::Result<()> {
66 assert!(count > 0);
67 match write(fd, &count.to_ne_bytes()) {
68 // The write succeeded, the ping will wake up the loop.
69 Ok(_) => Ok(()),
70
71 // The counter hit its cap, which means previous calls to write() will
72 // wake up the loop.
73 Err(nix::errno::Errno::EAGAIN) => Ok(()),
74
75 // Anything else is a real error.
76 Err(e) => Err(e.into()),
77 }
78 }
79
80 #[inline]
81 fn drain_ping(fd: RawFd) -> std::io::Result<u64> {
82 // The eventfd counter is effectively a u64.
83 const NBYTES: usize = 8;
84 let mut buf = [0u8; NBYTES];
85
86 match read(fd, &mut buf) {
87 // Reading from an eventfd should only ever produce 8 bytes. No looping
88 // is required.
89 Ok(NBYTES) => Ok(u64::from_ne_bytes(buf)),
90
91 Ok(_) => unreachable!(),
92
93 // Any other error can be propagated.
94 Err(e) => Err(e.into()),
95 }
96 }
97
98 // The event source is simply a generic source with one of the eventfds.
99 #[derive(Debug)]
100 pub struct PingSource {
101 event: Generic<RawFd>,
102
103 // This is held only to ensure that there is an owner of the fd that lives
104 // as long as the Generic source, so that the fd is not closed unexpectedly
105 // when all the senders are dropped.
106 _fd: Arc<CloseOnDrop>,
107 }
108
109 impl EventSource for PingSource {
110 type Event = ();
111 type Metadata = ();
112 type Ret = ();
113 type Error = PingError;
114
115 fn process_events<C>(
116 &mut self,
117 readiness: Readiness,
118 token: Token,
119 mut callback: C,
120 ) -> Result<PostAction, Self::Error>
121 where
122 C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
123 {
124 self.event
125 .process_events(readiness, token, |_, &mut fd| {
126 let counter = drain_ping(fd)?;
127
128 // If the LSB is set, it means we were closed. If anything else
129 // is also set, it means we were pinged. The two are not
130 // mutually exclusive.
131 let close = (counter & INCREMENT_CLOSE) != 0;
132 let ping = (counter & (u64::MAX - 1)) != 0;
133
134 if ping {
135 callback((), &mut ());
136 }
137
138 if close {
139 Ok(PostAction::Remove)
140 } else {
141 Ok(PostAction::Continue)
142 }
143 })
144 .map_err(|e| PingError(e.into()))
145 }
146
147 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
148 self.event.register(poll, token_factory)
149 }
150
151 fn reregister(
152 &mut self,
153 poll: &mut Poll,
154 token_factory: &mut TokenFactory,
155 ) -> crate::Result<()> {
156 self.event.reregister(poll, token_factory)
157 }
158
159 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
160 self.event.unregister(poll)
161 }
162 }
163
164 #[derive(Clone, Debug)]
165 pub struct Ping {
166 // This is an Arc because it's potentially shared with clones. The last one
167 // dropped needs to signal to the event source via the eventfd.
168 event: Arc<FlagOnDrop>,
169 }
170
171 impl Ping {
172 /// Send a ping to the `PingSource`.
173 pub fn ping(&self) {
174 if let Err(e) = send_ping(self.event.0 .0, INCREMENT_PING) {
175 log::warn!("[calloop] Failed to write a ping: {:?}", e);
176 }
177 }
178 }
179
180 /// This manages signalling to the PingSource when it's dropped. There should
181 /// only ever be one of these per PingSource.
182 #[derive(Debug)]
183 struct FlagOnDrop(Arc<CloseOnDrop>);
184
185 impl Drop for FlagOnDrop {
186 fn drop(&mut self) {
187 if let Err(e) = send_ping(self.0 .0, INCREMENT_CLOSE) {
188 log::warn!("[calloop] Failed to send close ping: {:?}", e);
189 }
190 }
191 }