Debian Codegraph @

src/sources/ping/eventfd.rs

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