Debian Codegraph @

src/sources/ping/eventfd.rs

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