Debian Codegraph @

src/sources/ping/iocp.rs

raw
1 //! IOCP-based implementation of the ping event source.
2 //!
3 //! The underlying `Poller` can be woken up at any time, using the `post` method
4 //! to send an arbitrary packet to the I/O completion port. The complication is
5 //! emulating a pipe.
6 //!
7 //! Since `Poller` is already wrapped in an `Arc`, we can clone it into some
8 //! synchronized inner state to send a pre-determined packet into it. Thankfully
9 //! calloop's use of the pipe is constrained enough that we can implement it using
10 //! a simple bool to keep track of whether or not it is notified.
11
12 use crate::sources::EventSource;
13
14 use polling::os::iocp::{CompletionPacket, PollerIocpExt};
15 use polling::Poller;
16 use tracing::{trace, warn};
17
18 use std::fmt;
19 use std::io;
20 use std::sync::{Arc, Mutex, TryLockError};
21
22 #[inline]
23 pub fn make_ping() -> io::Result<(Ping, PingSource)> {
24 let state = Arc::new(State {
25 counter: Mutex::new(Counter {
26 notified: false,
27 poll_state: None,
28 }),
29 });
30
31 Ok((
32 Ping {
33 state: state.clone(),
34 },
35 PingSource { state },
36 ))
37 }
38
39 /// The event to trigger.
40 #[derive(Clone)]
41 pub struct Ping {
42 state: Arc<State>,
43 }
44
45 impl fmt::Debug for Ping {
46 #[inline]
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 debug_ping(&self.state, "Ping", f)
49 }
50 }
51
52 /// The event source.
53 pub struct PingSource {
54 state: Arc<State>,
55 }
56
57 impl fmt::Debug for PingSource {
58 #[inline]
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 debug_ping(&self.state, "PingSource", f)
61 }
62 }
63
64 impl Ping {
65 /// Send a ping to the `PingSource`.
66 pub fn ping(&self) {
67 let mut counter = self.state.counter.lock().unwrap_or_else(|e| e.into_inner());
68
69 // Indicate that we are now notified.
70 counter.notified = true;
71
72 let poll_state = match &mut counter.poll_state {
73 Some(ps) => ps,
74 None => {
75 warn!("ping was not registered with the event loop");
76 return;
77 }
78 };
79
80 // If we aren't currently inserted in the loop, send our packet.
81 if let Err(e) = poll_state.notify() {
82 warn!("failed to post packet to IOCP: {e}");
83 }
84 }
85 }
86
87 impl Drop for Ping {
88 fn drop(&mut self) {
89 // If this is the last ping, wake up the source so it removes itself.
90 if Arc::strong_count(&self.state) <= 2 {
91 let mut counter = self.state.counter.lock().unwrap_or_else(|e| e.into_inner());
92 if let Some(poll_state) = &mut counter.poll_state {
93 if let Err(e) = poll_state.notify() {
94 warn!("failed to post packet to IOCP during drop: {e}");
95 }
96 }
97 }
98 }
99 }
100
101 impl EventSource for PingSource {
102 type Error = super::PingError;
103 type Event = ();
104 type Metadata = ();
105 type Ret = ();
106
107 fn process_events<F>(
108 &mut self,
109 _readiness: crate::Readiness,
110 token: crate::Token,
111 mut callback: F,
112 ) -> Result<crate::PostAction, Self::Error>
113 where
114 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
115 {
116 let mut counter = self.state.counter.lock().unwrap_or_else(|e| e.into_inner());
117
118 // If we aren't registered, break out.
119 let poll_state = match &mut counter.poll_state {
120 Some(ps) => ps,
121 None => {
122 // We were deregistered; indicate to the higher level loop.
123 return Ok(crate::PostAction::Disable);
124 }
125 };
126
127 // We are no longer inserted into the poller.
128 poll_state.inserted = false;
129
130 // Make sure this is our token.
131 let token: usize = token.inner.into();
132 if poll_state.packet.event().key != token {
133 warn!(
134 "token does not match; expected {:x}, got {:x}",
135 poll_state.packet.event().key,
136 token
137 );
138 return Ok(crate::PostAction::Continue);
139 }
140
141 // Tell if we are registered.
142 if counter.notified {
143 counter.notified = false;
144
145 // Call the callback.
146 callback((), &mut ());
147 }
148
149 // Stop looping if all of the Ping's have been dropped.
150 let action = if Arc::strong_count(&self.state) <= 1 {
151 crate::PostAction::Remove
152 } else {
153 crate::PostAction::Continue
154 };
155
156 Ok(action)
157 }
158
159 fn register(
160 &mut self,
161 poll: &mut crate::Poll,
162 token_factory: &mut crate::TokenFactory,
163 ) -> crate::Result<()> {
164 let token = token_factory.token();
165 let mut counter = self.state.counter.lock().unwrap_or_else(|e| e.into_inner());
166
167 // Make sure we haven't already been registered.
168 if counter.poll_state.is_some() {
169 return Err(io::Error::from(io::ErrorKind::AlreadyExists).into());
170 }
171
172 // Create the event to send.
173 let packet = {
174 let token = token.inner.into();
175 let event = polling::Event::readable(token);
176 CompletionPacket::new(event)
177 };
178
179 // Create the poll state.
180 let poll_state = PollState::new(poll.poller(), packet, counter.notified)?;
181
182 // Substitute it into our poll state.
183 counter.poll_state = Some(poll_state);
184 Ok(())
185 }
186
187 fn reregister(
188 &mut self,
189 poll: &mut crate::Poll,
190 token_factory: &mut crate::TokenFactory,
191 ) -> crate::Result<()> {
192 let token = token_factory.token();
193 let mut counter = self.state.counter.lock().unwrap_or_else(|e| e.into_inner());
194
195 // Make sure that the poller has been registered.
196 let poll_state = match &mut counter.poll_state {
197 Some(ps) => ps,
198 None => return Err(io::Error::from(io::ErrorKind::NotFound).into()),
199 };
200
201 // If it's a different poller, throw an error.
202 if !Arc::ptr_eq(&poll_state.poller, poll.poller()) {
203 return Err(io::Error::new(
204 io::ErrorKind::NotFound,
205 "attempted to reregister() a PingSource with a different poller",
206 )
207 .into());
208 }
209
210 // Change the token if needed.
211 let token = token.inner.into();
212 let event = polling::Event::readable(token);
213
214 if event.key != poll_state.packet.event().key {
215 poll_state.packet = CompletionPacket::new(event);
216
217 if poll_state.inserted {
218 poll_state.inserted = false;
219 poll_state.notify()?;
220 }
221 }
222
223 Ok(())
224 }
225
226 fn unregister(&mut self, _poll: &mut crate::Poll) -> crate::Result<()> {
227 let mut counter = self.state.counter.lock().unwrap_or_else(|e| e.into_inner());
228
229 // Remove our current registration.
230 if counter.poll_state.take().is_none() {
231 trace!("unregistered a source that wasn't registered");
232 }
233 Ok(())
234 }
235 }
236
237 /// Inner state of the pipe.
238 struct State {
239 /// The counter used to keep track of our state.
240 counter: Mutex<Counter>,
241 }
242
243 /// Inner counter of the pipe.
244 struct Counter {
245 /// Are we notified?
246 notified: bool,
247
248 /// The `Poller`-related state.
249 ///
250 /// This is `None` if we aren't inserted into the `Poller` yet.
251 poll_state: Option<PollState>,
252 }
253
254 /// The `Poller` combined with some associated state.
255 struct PollState {
256 /// The `Poller` that we are registered in.
257 poller: Arc<Poller>,
258
259 /// Are we inserted into the poller?
260 inserted: bool,
261
262 /// The completion packet to send.
263 packet: CompletionPacket,
264 }
265
266 impl PollState {
267 /// Create a new `PollState` based on the `Poller` and the `packet`.
268 ///
269 /// If `notified` is `true`, a packet is inserted into the poller.
270 fn new(poller: &Arc<Poller>, packet: CompletionPacket, notified: bool) -> io::Result<Self> {
271 let mut poll_state = Self {
272 poller: poller.clone(),
273 packet,
274 inserted: false,
275 };
276
277 if notified {
278 poll_state.notify()?;
279 }
280
281 Ok(poll_state)
282 }
283
284 /// Notify the poller.
285 fn notify(&mut self) -> io::Result<()> {
286 if !self.inserted {
287 self.poller.post(self.packet.clone())?;
288 self.inserted = true;
289 }
290
291 Ok(())
292 }
293 }
294
295 #[inline]
296 fn debug_ping(state: &State, name: &str, f: &mut fmt::Formatter) -> fmt::Result {
297 let counter = match state.counter.try_lock() {
298 Ok(counter) => counter,
299 Err(TryLockError::WouldBlock) => {
300 return f
301 .debug_tuple("Ping")
302 .field(&format_args!("<locked>"))
303 .finish()
304 }
305 Err(TryLockError::Poisoned(_)) => {
306 return f
307 .debug_tuple("Ping")
308 .field(&format_args!("<poisoned>"))
309 .finish()
310 }
311 };
312
313 let mut s = f.debug_struct(name);
314 s.field("notified", &counter.notified);
315
316 // Tell if we are registered.
317 match &counter.poll_state {
318 Some(poll_state) => {
319 s.field("packet", poll_state.packet.event());
320 s.field("inserted", &poll_state.inserted);
321 }
322
323 None => {
324 s.field("packet", &format_args!("<not registered>"));
325 }
326 }
327
328 s.finish()
329 }