Debian Codegraph @

src/iocp/mod.rs

raw symbols SCIP
1 //! Bindings to Windows I/O Completion Ports.
2 //!
3 //! I/O Completion Ports is a completion-based API rather than a polling-based API, like
4 //! epoll or kqueue. Therefore, we have to adapt the IOCP API to the crate's API.
5 //!
6 //! WinSock is powered by the Auxiliary Function Driver (AFD) subsystem, which can be
7 //! accessed directly by using unstable `ntdll` functions. AFD exposes features that are not
8 //! available through the normal WinSock interface, such as IOCTL_AFD_POLL. This function is
9 //! similar to the exposed `WSAPoll` method. However, once the targeted socket is "ready",
10 //! a completion packet is queued to an I/O completion port.
11 //!
12 //! We take advantage of IOCTL_AFD_POLL to "translate" this crate's polling-based API
13 //! to the one Windows expects. When a device is added to the `Poller`, an IOCTL_AFD_POLL
14 //! operation is started and queued to the IOCP. To modify a currently registered device
15 //! (e.g. with `modify()` or `delete()`), the ongoing POLL is cancelled and then restarted
16 //! with new parameters. When the POLL eventually completes, the packet is posted to the IOCP.
17 //! From here it's a simple matter of using `GetQueuedCompletionStatusEx` to read the packets
18 //! from the IOCP and react accordingly. Notifying the poller is trivial, because we can
19 //! simply post a packet to the IOCP to wake it up.
20 //!
21 //! The main disadvantage of this strategy is that it relies on unstable Windows APIs.
22 //! However, as `libuv` (the backing I/O library for Node.JS) relies on the same unstable
23 //! AFD strategy, it is unlikely to be broken without plenty of advanced warning.
24 //!
25 //! Previously, this crate used the `wepoll` library for polling. `wepoll` uses a similar
26 //! AFD-based strategy for polling.
27
28 mod afd;
29 mod port;
30
31 use afd::{base_socket, Afd, AfdPollInfo, AfdPollMask, HasAfdInfo, IoStatusBlock};
32 use port::{IoCompletionPort, OverlappedEntry};
33
34 use windows_sys::Win32::Foundation::{ERROR_INVALID_HANDLE, ERROR_IO_PENDING, STATUS_CANCELLED};
35 use windows_sys::Win32::System::Threading::{
36 RegisterWaitForSingleObject, UnregisterWait, INFINITE, WT_EXECUTELONGFUNCTION,
37 WT_EXECUTEONLYONCE,
38 };
39
40 use crate::{Event, PollMode};
41
42 use concurrent_queue::ConcurrentQueue;
43 use pin_project_lite::pin_project;
44
45 use std::cell::UnsafeCell;
46 use std::collections::hash_map::{Entry, HashMap};
47 use std::ffi::c_void;
48 use std::fmt;
49 use std::io;
50 use std::marker::PhantomPinned;
51 use std::mem::{forget, MaybeUninit};
52 use std::os::windows::io::{
53 AsHandle, AsRawHandle, AsRawSocket, BorrowedHandle, BorrowedSocket, RawHandle, RawSocket,
54 };
55 use std::pin::Pin;
56 use std::sync::atomic::{AtomicBool, Ordering};
57 use std::sync::{Arc, Mutex, MutexGuard, RwLock, Weak};
58 use std::time::{Duration, Instant};
59
60 /// Macro to lock and ignore lock poisoning.
61 macro_rules! lock {
62 ($lock_result:expr) => {{
63 $lock_result.unwrap_or_else(|e| e.into_inner())
64 }};
65 }
66
67 /// Interface to I/O completion ports.
68 #[derive(Debug)]
69 pub(super) struct Poller {
70 /// The I/O completion port.
71 port: Arc<IoCompletionPort<Packet>>,
72
73 /// List of currently active AFD instances.
74 ///
75 /// AFD acts as the actual source of the socket events. It's essentially running `WSAPoll` on
76 /// the sockets and then posting the events to the IOCP.
77 ///
78 /// AFD instances can be keyed to an unlimited number of sockets. However, each AFD instance
79 /// polls their sockets linearly. Therefore, it is best to limit the number of sockets each AFD
80 /// instance is responsible for. The limit of 32 is chosen because that's what `wepoll` uses.
81 ///
82 /// Weak references are kept here so that the AFD handle is automatically dropped when the last
83 /// associated socket is dropped.
84 afd: Mutex<Vec<Weak<Afd<Packet>>>>,
85
86 /// The state of the sources registered with this poller.
87 ///
88 /// Each source is keyed by its raw socket ID.
89 sources: RwLock<HashMap<RawSocket, Packet>>,
90
91 /// The state of the waitable handles registered with this poller.
92 waitables: RwLock<HashMap<RawHandle, Packet>>,
93
94 /// Sockets with pending updates.
95 ///
96 /// This list contains packets with sockets that need to have their AFD state adjusted by
97 /// calling the `update()` function on them. It's best to queue up packets as they need to
98 /// be updated and then run all of the updates before we start waiting on the IOCP, rather than
99 /// updating them as we come. If we're waiting on the IOCP updates should be run immediately.
100 pending_updates: ConcurrentQueue<Packet>,
101
102 /// Are we currently polling?
103 ///
104 /// This indicates whether or not we are blocking on the IOCP, and is used to determine
105 /// whether pending updates should be run immediately or queued.
106 polling: AtomicBool,
107
108 /// The packet used to notify the poller.
109 ///
110 /// This is a special-case packet that is used to wake up the poller when it is waiting.
111 notifier: Packet,
112 }
113
114 unsafe impl Send for Poller {}
115 unsafe impl Sync for Poller {}
116
117 impl Poller {
118 /// Creates a new poller.
119 pub(super) fn new() -> io::Result<Self> {
120 // Make sure AFD is able to be used.
121 if let Err(e) = afd::NtdllImports::force_load() {
122 return Err(io::Error::new(
123 io::ErrorKind::Unsupported,
124 AfdError::new("failed to initialize unstable Windows functions", e),
125 ));
126 }
127
128 // Create and destroy a single AFD to test if we support it.
129 Afd::<Packet>::new().map_err(|e| {
130 io::Error::new(
131 io::ErrorKind::Unsupported,
132 AfdError::new("failed to initialize \\Device\\Afd", e),
133 )
134 })?;
135
136 let port = IoCompletionPort::new(0)?;
137 #[cfg(feature = "tracing")]
138 tracing::trace!(handle = ?port, "new");
139
140 Ok(Poller {
141 #[allow(clippy::arc_with_non_send_sync)]
142 port: Arc::new(port),
143 afd: Mutex::new(vec![]),
144 sources: RwLock::new(HashMap::new()),
145 waitables: RwLock::new(HashMap::new()),
146 pending_updates: ConcurrentQueue::bounded(1024),
147 polling: AtomicBool::new(false),
148 notifier: Arc::pin(
149 PacketInner::Wakeup {
150 _pinned: PhantomPinned,
151 }
152 .into(),
153 ),
154 })
155 }
156
157 /// Whether this poller supports level-triggered events.
158 pub(super) fn supports_level(&self) -> bool {
159 true
160 }
161
162 /// Whether this poller supports edge-triggered events.
163 pub(super) fn supports_edge(&self) -> bool {
164 false
165 }
166
167 /// Add a new source to the poller.
168 ///
169 /// # Safety
170 ///
171 /// The socket must be a valid socket and must last until it is deleted.
172 pub(super) unsafe fn add(
173 &self,
174 socket: RawSocket,
175 interest: Event,
176 mode: PollMode,
177 ) -> io::Result<()> {
178 #[cfg(feature = "tracing")]
179 let span = tracing::trace_span!(
180 "add",
181 handle = ?self.port,
182 sock = ?socket,
183 ev = ?interest,
184 );
185 #[cfg(feature = "tracing")]
186 let _enter = span.enter();
187
188 // We don't support edge-triggered events.
189 if matches!(mode, PollMode::Edge | PollMode::EdgeOneshot) {
190 return Err(io::Error::new(
191 io::ErrorKind::InvalidInput,
192 "edge-triggered events are not supported",
193 ));
194 }
195
196 // Create a new packet.
197 let socket_state = {
198 // Create a new socket state and assign an AFD handle to it.
199 let state = SocketState {
200 socket,
201 base_socket: base_socket(socket)?,
202 interest,
203 interest_error: true,
204 afd: self.afd_handle()?,
205 mode,
206 waiting_on_delete: false,
207 status: SocketStatus::Idle,
208 };
209
210 // We wrap this socket state in a Packet so the IOCP can use it.
211 Arc::pin(IoStatusBlock::from(PacketInner::Socket {
212 packet: UnsafeCell::new(AfdPollInfo::default()),
213 socket: Mutex::new(state),
214 }))
215 };
216
217 // Keep track of the source in the poller.
218 {
219 let mut sources = lock!(self.sources.write());
220
221 match sources.entry(socket) {
222 Entry::Vacant(v) => {
223 v.insert(Pin::<Arc<_>>::clone(&socket_state));
224 }
225
226 Entry::Occupied(_) => {
227 return Err(io::Error::from(io::ErrorKind::AlreadyExists));
228 }
229 }
230 }
231
232 // Update the packet.
233 self.update_packet(socket_state)
234 }
235
236 /// Update a source in the poller.
237 pub(super) fn modify(
238 &self,
239 socket: BorrowedSocket<'_>,
240 interest: Event,
241 mode: PollMode,
242 ) -> io::Result<()> {
243 #[cfg(feature = "tracing")]
244 let span = tracing::trace_span!(
245 "modify",
246 handle = ?self.port,
247 sock = ?socket,
248 ev = ?interest,
249 );
250 #[cfg(feature = "tracing")]
251 let _enter = span.enter();
252
253 // We don't support edge-triggered events.
254 if matches!(mode, PollMode::Edge | PollMode::EdgeOneshot) {
255 return Err(io::Error::new(
256 io::ErrorKind::InvalidInput,
257 "edge-triggered events are not supported",
258 ));
259 }
260
261 // Get a reference to the source.
262 let source = {
263 let sources = lock!(self.sources.read());
264
265 sources
266 .get(&socket.as_raw_socket())
267 .cloned()
268 .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?
269 };
270
271 // Set the new event.
272 if source.as_ref().set_events(interest, mode) {
273 // The packet needs to be updated.
274 self.update_packet(source)?;
275 }
276
277 Ok(())
278 }
279
280 /// Delete a source from the poller.
281 pub(super) fn delete(&self, socket: BorrowedSocket<'_>) -> io::Result<()> {
282 #[cfg(feature = "tracing")]
283 let span = tracing::trace_span!(
284 "remove",
285 handle = ?self.port,
286 sock = ?socket,
287 );
288 #[cfg(feature = "tracing")]
289 let _enter = span.enter();
290
291 // Remove the source from our associative map.
292 let source = {
293 let mut sources = lock!(self.sources.write());
294
295 match sources.remove(&socket.as_raw_socket()) {
296 Some(s) => s,
297 None => {
298 // If the source has already been removed, then we can just return.
299 return Ok(());
300 }
301 }
302 };
303
304 // Indicate to the source that it is being deleted.
305 // This cancels any ongoing AFD_IOCTL_POLL operations.
306 source.begin_delete()
307 }
308
309 /// Add a new waitable to the poller.
310 pub(super) fn add_waitable(
311 &self,
312 handle: RawHandle,
313 interest: Event,
314 mode: PollMode,
315 ) -> io::Result<()> {
316 #[cfg(feature = "tracing")]
317 tracing::trace!(
318 "add_waitable: handle={:?}, waitable={:p}, ev={:?}",
319 self.port,
320 handle,
321 interest
322 );
323
324 // We don't support edge-triggered events.
325 if matches!(mode, PollMode::Edge | PollMode::EdgeOneshot) {
326 return Err(io::Error::new(
327 io::ErrorKind::InvalidInput,
328 "edge-triggered events are not supported",
329 ));
330 }
331
332 // Create a new packet.
333 let handle_state = {
334 let state = WaitableState {
335 handle,
336 port: Arc::downgrade(&self.port),
337 interest,
338 mode,
339 status: WaitableStatus::Idle,
340 };
341
342 Arc::pin(IoStatusBlock::from(PacketInner::Waitable {
343 handle: Mutex::new(state),
344 }))
345 };
346
347 // Keep track of the source in the poller.
348 {
349 let mut sources = lock!(self.waitables.write());
350
351 match sources.entry(handle) {
352 Entry::Vacant(v) => {
353 v.insert(Pin::<Arc<_>>::clone(&handle_state));
354 }
355
356 Entry::Occupied(_) => {
357 return Err(io::Error::from(io::ErrorKind::AlreadyExists));
358 }
359 }
360 }
361
362 // Update the packet.
363 self.update_packet(handle_state)
364 }
365
366 /// Update a waitable in the poller.
367 pub(crate) fn modify_waitable(
368 &self,
369 waitable: RawHandle,
370 interest: Event,
371 mode: PollMode,
372 ) -> io::Result<()> {
373 #[cfg(feature = "tracing")]
374 tracing::trace!(
375 "modify_waitable: handle={:?}, waitable={:p}, ev={:?}",
376 self.port,
377 waitable,
378 interest
379 );
380
381 // We don't support edge-triggered events.
382 if matches!(mode, PollMode::Edge | PollMode::EdgeOneshot) {
383 return Err(io::Error::new(
384 io::ErrorKind::InvalidInput,
385 "edge-triggered events are not supported",
386 ));
387 }
388
389 // Get a reference to the source.
390 let source = {
391 let sources = lock!(self.waitables.read());
392
393 sources
394 .get(&waitable)
395 .cloned()
396 .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?
397 };
398
399 // Set the new event.
400 if source.as_ref().set_events(interest, mode) {
401 self.update_packet(source)?;
402 }
403
404 Ok(())
405 }
406
407 /// Delete a waitable from the poller.
408 pub(super) fn remove_waitable(&self, waitable: RawHandle) -> io::Result<()> {
409 #[cfg(feature = "tracing")]
410 tracing::trace!("remove: handle={:?}, waitable={:p}", self.port, waitable);
411
412 // Get a reference to the source.
413 let source = {
414 let mut sources = lock!(self.waitables.write());
415
416 match sources.remove(&waitable) {
417 Some(s) => s,
418 None => {
419 // If the source has already been removed, then we can just return.
420 return Ok(());
421 }
422 }
423 };
424
425 // Indicate to the source that it is being deleted.
426 // This cancels any ongoing AFD_IOCTL_POLL operations.
427 source.begin_delete()
428 }
429
430 /// Wait for events.
431 pub(super) fn wait_deadline(
432 &self,
433 events: &mut Events,
434 deadline: Option<Instant>,
435 ) -> io::Result<()> {
436 #[cfg(feature = "tracing")]
437 let span = tracing::trace_span!(
438 "wait",
439 handle = ?self.port,
440 ?deadline,
441 );
442 #[cfg(feature = "tracing")]
443 let _enter = span.enter();
444
445 let mut notified = false;
446
447 loop {
448 let mut new_events = 0;
449
450 // Indicate that we are now polling.
451 let was_polling = self.polling.swap(true, Ordering::SeqCst);
452 debug_assert!(!was_polling);
453
454 // Even if we panic, we want to make sure we indicate that polling has stopped.
455 let guard = CallOnDrop(|| {
456 let was_polling = self.polling.swap(false, Ordering::SeqCst);
457 debug_assert!(was_polling);
458 });
459
460 // Process every entry in the queue before we start polling.
461 self.drain_update_queue(false)?;
462
463 // Get the time to wait for.
464 let timeout = deadline.map(|t| t.saturating_duration_since(Instant::now()));
465
466 // Wait for I/O events.
467 let _len = self.port.wait(&mut events.completions, timeout)?;
468 #[cfg(feature = "tracing")]
469 tracing::trace!(
470 handle = ?self.port,
471 res = ?_len,
472 "new events");
473
474 // We are no longer polling.
475 drop(guard);
476
477 // Process all of the events.
478 for entry in events.completions.drain(..) {
479 let packet = entry.into_packet();
480
481 // Feed the event into the packet.
482 match packet.feed_event(self)? {
483 FeedEventResult::NoEvent => {}
484 FeedEventResult::Event(event) => {
485 events.packets.push(event);
486 new_events += 1;
487 }
488 FeedEventResult::Notified => {
489 notified = true;
490 }
491 }
492 }
493
494 // Break if there was a notification or at least one event, or if deadline is reached.
495 let timeout_is_empty = timeout.is_some_and(|t| t.is_zero());
496 if notified || new_events > 0 || timeout_is_empty {
497 break;
498 }
499
500 #[cfg(feature = "tracing")]
501 tracing::trace!("wait: no events found, re-entering polling loop");
502 }
503
504 Ok(())
505 }
506
507 /// Notify this poller.
508 pub(super) fn notify(&self) -> io::Result<()> {
509 // Push the notify packet into the IOCP.
510 self.port.post(0, 0, self.notifier.clone())
511 }
512
513 /// Push an IOCP packet into the queue.
514 pub(super) fn post(&self, packet: CompletionPacket) -> io::Result<()> {
515 self.port.post(0, 0, packet.0)
516 }
517
518 /// Run an update on a packet.
519 fn update_packet(&self, mut packet: Packet) -> io::Result<()> {
520 loop {
521 // If we are currently polling, we need to update the packet immediately.
522 if self.polling.load(Ordering::Acquire) {
523 packet.update()?;
524 return Ok(());
525 }
526
527 // Try to queue the update.
528 match self.pending_updates.push(packet) {
529 Ok(()) => return Ok(()),
530 Err(p) => packet = p.into_inner(),
531 }
532
533 // If we failed to queue the update, we need to drain the queue first.
534 self.drain_update_queue(true)?;
535
536 // Loop back and try again.
537 }
538 }
539
540 /// Drain the update queue.
541 fn drain_update_queue(&self, limit: bool) -> io::Result<()> {
542 // Determine how many packets to process.
543 let max = if limit {
544 // Only drain the queue's capacity, since this could in theory run forever.
545 self.pending_updates.capacity().unwrap()
546 } else {
547 // Less of a concern if we're draining the queue prior to a poll operation.
548 usize::MAX
549 };
550
551 self.pending_updates
552 .try_iter()
553 .take(max)
554 .try_for_each(|packet| packet.update())
555 }
556
557 /// Get a handle to the AFD reference.
558 ///
559 /// This finds an AFD handle with less than 32 associated sockets, or creates a new one if
560 /// one does not exist.
561 fn afd_handle(&self) -> io::Result<Arc<Afd<Packet>>> {
562 const AFD_MAX_SIZE: usize = 32;
563
564 // Crawl the list and see if there are any existing AFD instances that we can use.
565 // While we're here, remove any unused AFD pointers.
566 let mut afd_handles = lock!(self.afd.lock());
567 let mut i = 0;
568 while i < afd_handles.len() {
569 // Get the reference count of the AFD instance.
570 let refcount = Weak::strong_count(&afd_handles[i]);
571
572 match refcount {
573 0 => {
574 // Prune the AFD pointer if it has no references.
575 afd_handles.swap_remove(i);
576 }
577
578 refcount if refcount >= AFD_MAX_SIZE => {
579 // Skip this one, since it is already at the maximum size.
580 i += 1;
581 }
582
583 _ => {
584 // We can use this AFD instance.
585 match afd_handles[i].upgrade() {
586 Some(afd) => return Ok(afd),
587 None => {
588 // The last socket dropped the AFD before we could acquire it.
589 // Prune the AFD pointer and continue.
590 afd_handles.swap_remove(i);
591 }
592 }
593 }
594 }
595 }
596
597 // No available handles, create a new AFD instance.
598 #[allow(clippy::arc_with_non_send_sync)]
599 let afd = Arc::new(Afd::new()?);
600
601 // Register the AFD instance with the I/O completion port.
602 self.port.register(&*afd, true)?;
603
604 // Insert a weak pointer to the AFD instance into the list for other sockets.
605 afd_handles.push(Arc::downgrade(&afd));
606
607 Ok(afd)
608 }
609 }
610
611 impl AsRawHandle for Poller {
612 fn as_raw_handle(&self) -> RawHandle {
613 self.port.as_raw_handle()
614 }
615 }
616
617 impl AsHandle for Poller {
618 fn as_handle(&self) -> BorrowedHandle<'_> {
619 unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
620 }
621 }
622
623 /// The container for events.
624 pub(super) struct Events {
625 /// List of IOCP packets.
626 packets: Vec<Event>,
627
628 /// Buffer for completion packets.
629 completions: Vec<OverlappedEntry<Packet>>,
630 }
631
632 unsafe impl Send for Events {}
633
634 impl Events {
635 /// Creates an empty list of events.
636 pub fn with_capacity(cap: usize) -> Events {
637 Events {
638 packets: Vec::with_capacity(cap),
639 completions: Vec::with_capacity(cap),
640 }
641 }
642
643 /// Iterate over I/O events.
644 pub fn iter(&self) -> impl Iterator<Item = Event> + '_ {
645 self.packets.iter().copied()
646 }
647
648 /// Clear the list of events.
649 pub fn clear(&mut self) {
650 self.packets.clear();
651 }
652
653 /// The capacity of the list of events.
654 pub fn capacity(&self) -> usize {
655 self.packets.capacity()
656 }
657 }
658
659 /// Extra information about an event.
660 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
661 pub struct EventExtra {
662 /// Flags associated with this event.
663 flags: AfdPollMask,
664 }
665
666 impl EventExtra {
667 /// Create a new, empty version of this struct.
668 #[inline]
669 pub const fn empty() -> EventExtra {
670 EventExtra {
671 flags: AfdPollMask::empty(),
672 }
673 }
674
675 /// Is this a HUP event?
676 #[inline]
677 pub fn is_hup(&self) -> bool {
678 self.flags.intersects(AfdPollMask::ABORT)
679 }
680
681 /// Is this a PRI event?
682 #[inline]
683 pub fn is_pri(&self) -> bool {
684 self.flags.intersects(AfdPollMask::RECEIVE_EXPEDITED)
685 }
686
687 /// Set up a listener for HUP events.
688 #[inline]
689 pub fn set_hup(&mut self, active: bool) {
690 self.flags.set(AfdPollMask::ABORT, active);
691 }
692
693 /// Set up a listener for PRI events.
694 #[inline]
695 pub fn set_pri(&mut self, active: bool) {
696 self.flags.set(AfdPollMask::RECEIVE_EXPEDITED, active);
697 }
698
699 /// Check if TCP connect failed. Deprecated.
700 #[inline]
701 pub fn is_connect_failed(&self) -> Option<bool> {
702 Some(self.flags.intersects(AfdPollMask::CONNECT_FAIL))
703 }
704
705 /// Check if TCP connect failed.
706 #[inline]
707 pub fn is_err(&self) -> Option<bool> {
708 Some(self.flags.intersects(AfdPollMask::CONNECT_FAIL))
709 }
710 }
711
712 /// A packet used to wake up the poller with an event.
713 #[derive(Debug, Clone)]
714 pub struct CompletionPacket(Packet);
715
716 impl CompletionPacket {
717 /// Create a new completion packet with a custom event.
718 pub fn new(event: Event) -> Self {
719 Self(Arc::pin(IoStatusBlock::from(PacketInner::Custom { event })))
720 }
721
722 /// Get the event associated with this packet.
723 pub fn event(&self) -> &Event {
724 let data = self.0.as_ref().data().project_ref();
725
726 match data {
727 PacketInnerProj::Custom { event } => event,
728 _ => unreachable!(),
729 }
730 }
731 }
732
733 /// The type of our completion packet.
734 ///
735 /// It needs to be pinned, since it contains data that is expected by IOCP not to be moved.
736 type Packet = Pin<Arc<PacketUnwrapped>>;
737 type PacketUnwrapped = IoStatusBlock<PacketInner>;
738
739 pin_project! {
740 /// The inner type of the packet.
741 #[project_ref = PacketInnerProj]
742 #[project = PacketInnerProjMut]
743 enum PacketInner {
744 // A packet for a socket.
745 Socket {
746 // The AFD packet state.
747 #[pin]
748 packet: UnsafeCell<AfdPollInfo>,
749
750 // The socket state.
751 socket: Mutex<SocketState>
752 },
753
754 /// A packet for a waitable handle.
755 Waitable {
756 handle: Mutex<WaitableState>
757 },
758
759 /// A custom event sent by the user.
760 Custom {
761 event: Event,
762 },
763
764 // A packet used to wake up the poller.
765 Wakeup { #[pin] _pinned: PhantomPinned },
766 }
767 }
768
769 unsafe impl Send for PacketInner {}
770 unsafe impl Sync for PacketInner {}
771
772 impl fmt::Debug for PacketInner {
773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
774 match self {
775 Self::Wakeup { .. } => f.write_str("Wakeup { .. }"),
776 Self::Custom { event } => f.debug_struct("Custom").field("event", event).finish(),
777 Self::Socket { socket, .. } => f
778 .debug_struct("Socket")
779 .field("packet", &"..")
780 .field("socket", socket)
781 .finish(),
782 Self::Waitable { handle } => {
783 f.debug_struct("Waitable").field("handle", handle).finish()
784 }
785 }
786 }
787 }
788
789 impl HasAfdInfo for PacketInner {
790 fn afd_info(self: Pin<&Self>) -> Pin<&UnsafeCell<AfdPollInfo>> {
791 match self.project_ref() {
792 PacketInnerProj::Socket { packet, .. } => packet,
793 _ => unreachable!(),
794 }
795 }
796 }
797
798 impl PacketUnwrapped {
799 /// Set the new events that this socket is waiting on.
800 ///
801 /// Returns `true` if we need to be updated.
802 fn set_events(self: Pin<&Self>, interest: Event, mode: PollMode) -> bool {
803 match self.data().project_ref() {
804 PacketInnerProj::Socket { socket, .. } => {
805 let mut socket = lock!(socket.lock());
806 socket.interest = interest;
807 socket.mode = mode;
808 socket.interest_error = true;
809
810 // If there was a change, indicate that we need an update.
811 match socket.status {
812 SocketStatus::Polling { flags } => {
813 let our_flags = event_to_afd_mask(socket.interest, socket.interest_error);
814 our_flags != flags
815 }
816 _ => true,
817 }
818 }
819 PacketInnerProj::Waitable { handle } => {
820 let mut handle = lock!(handle.lock());
821
822 // Set the new interest.
823 handle.interest = interest;
824 handle.mode = mode;
825
826 // Update if there is no ongoing wait.
827 handle.status.is_idle()
828 }
829 _ => true,
830 }
831 }
832
833 /// Update the socket and install the new status in AFD.
834 ///
835 /// This function does one of the following:
836 ///
837 /// - Nothing, if the packet is waiting on being dropped anyways.
838 /// - Cancels the ongoing poll, if we want to poll for different events than we are currently
839 /// polling for.
840 /// - Starts a new AFD_POLL operation, if we are not currently polling.
841 fn update(self: Pin<Arc<Self>>) -> io::Result<()> {
842 let mut socket = match self.as_ref().data().project_ref() {
843 PacketInnerProj::Socket { socket, .. } => lock!(socket.lock()),
844 PacketInnerProj::Waitable { handle } => {
845 let mut handle = lock!(handle.lock());
846
847 // If there is no interests, or if we have been cancelled, we don't need to update.
848 if !handle.interest.readable && !handle.interest.writable {
849 return Ok(());
850 }
851
852 // If we are idle, we need to update.
853 if !handle.status.is_idle() {
854 return Ok(());
855 }
856
857 // Start a new wait.
858 let packet = self.clone();
859 let wait_handle = WaitHandle::new(
860 handle.handle,
861 move || {
862 let mut handle = match packet.as_ref().data().project_ref() {
863 PacketInnerProj::Waitable { handle } => lock!(handle.lock()),
864 _ => unreachable!(),
865 };
866
867 // Try to get the IOCP.
868 let iocp = match handle.port.upgrade() {
869 Some(iocp) => iocp,
870 None => return,
871 };
872
873 // Set us back into the idle state.
874 handle.status = WaitableStatus::Idle;
875
876 // Push this packet.
877 drop(handle);
878 if let Err(_e) = iocp.post(0, 0, packet) {
879 #[cfg(feature = "tracing")]
880 tracing::error!("failed to post completion packet: {}", _e);
881 }
882 },
883 None,
884 false,
885 )?;
886
887 // Set the new status.
888 handle.status = WaitableStatus::Waiting(wait_handle);
889
890 return Ok(());
891 }
892 _ => return Err(io::Error::new(io::ErrorKind::Other, "invalid socket state")),
893 };
894
895 // If we are waiting on a delete, just return, dropping the packet.
896 if socket.waiting_on_delete {
897 return Ok(());
898 }
899
900 // Check the current status.
901 match socket.status {
902 SocketStatus::Polling { flags } => {
903 // If we need to poll for events aside from what we are currently polling, we need
904 // to update the packet. Cancel the ongoing poll.
905 let our_flags = event_to_afd_mask(socket.interest, socket.interest_error);
906 if our_flags != flags {
907 return self.cancel(socket);
908 }
909
910 // All events that we are currently waiting on are accounted for.
911 Ok(())
912 }
913
914 SocketStatus::Cancelled => {
915 // The ongoing operation was cancelled, and we're still waiting for it to return.
916 // For now, wait until the top-level loop calls feed_event().
917 Ok(())
918 }
919
920 SocketStatus::Idle => {
921 // Start a new poll.
922 let mask = event_to_afd_mask(socket.interest, socket.interest_error);
923 let result = socket.afd.poll(self.clone(), socket.base_socket, mask);
924
925 match result {
926 Ok(()) => {}
927
928 Err(err)
929 if err.raw_os_error() == Some(ERROR_IO_PENDING as i32)
930 || err.kind() == io::ErrorKind::WouldBlock =>
931 {
932 // The operation is pending.
933 }
934
935 Err(err) if err.raw_os_error() == Some(ERROR_INVALID_HANDLE as i32) => {
936 // The socket was closed. We need to delete it.
937 // This should happen after we drop it here.
938 }
939
940 Err(err) => return Err(err),
941 }
942
943 // We are now polling for the current events.
944 socket.status = SocketStatus::Polling { flags: mask };
945
946 Ok(())
947 }
948 }
949 }
950
951 /// This socket state was notified; see if we need to update it.
952 ///
953 /// This indicates that this packet was indicated as "ready" by the IOCP and needs to be
954 /// processed.
955 fn feed_event(self: Pin<Arc<Self>>, poller: &Poller) -> io::Result<FeedEventResult> {
956 let inner = self.as_ref().data().project_ref();
957
958 let (afd_info, socket) = match inner {
959 PacketInnerProj::Socket { packet, socket } => (packet, socket),
960 PacketInnerProj::Custom { event } => {
961 // This is a custom event.
962 return Ok(FeedEventResult::Event(*event));
963 }
964 PacketInnerProj::Wakeup { .. } => {
965 // The poller was notified.
966 return Ok(FeedEventResult::Notified);
967 }
968 PacketInnerProj::Waitable { handle } => {
969 let mut handle = lock!(handle.lock());
970 let event = handle.interest;
971
972 // Clear the events if we are in one-shot mode.
973 if matches!(handle.mode, PollMode::Oneshot) {
974 handle.interest = Event::none(handle.interest.key);
975 }
976
977 // Submit for an update.
978 drop(handle);
979 poller.update_packet(self)?;
980
981 return Ok(FeedEventResult::Event(event));
982 }
983 };
984
985 let mut socket_state = lock!(socket.lock());
986 let mut event = Event::none(socket_state.interest.key);
987
988 // Put ourselves into the idle state.
989 socket_state.status = SocketStatus::Idle;
990
991 // If we are waiting to be deleted, just return and let the drop handler do their thing.
992 if socket_state.waiting_on_delete {
993 return Ok(FeedEventResult::NoEvent);
994 }
995
996 unsafe {
997 // SAFETY: The packet is not in transit.
998 let iosb = &mut *self.as_ref().iosb().get();
999
1000 // Check the status.
1001 match iosb.Anonymous.Status {
1002 STATUS_CANCELLED => {
1003 // Poll request was cancelled.
1004 }
1005
1006 status if status < 0 => {
1007 // There was an error, so we signal both ends.
1008 event.readable = true;
1009 event.writable = true;
1010 }
1011
1012 _ => {
1013 // Check in on the AFD data.
1014 let afd_data = &*afd_info.get();
1015
1016 // There was at least one event.
1017 if afd_data.handle_count() >= 1 {
1018 let events = afd_data.events();
1019
1020 // If we closed the socket, remove it from being polled.
1021 if events.intersects(AfdPollMask::LOCAL_CLOSE) {
1022 let source = lock!(poller.sources.write())
1023 .remove(&socket_state.socket)
1024 .unwrap();
1025 return source.begin_delete().map(|()| FeedEventResult::NoEvent);
1026 }
1027
1028 // Report socket-related events.
1029 let (readable, writable) = afd_mask_to_event(events);
1030 event.readable = readable;
1031 event.writable = writable;
1032 event.extra.flags = events;
1033 }
1034 }
1035 }
1036 }
1037
1038 // Filter out events that the user didn't ask for.
1039 event.readable &= socket_state.interest.readable;
1040 event.writable &= socket_state.interest.writable;
1041
1042 // If this event doesn't have anything that interests us, don't return or
1043 // update the oneshot state.
1044 let return_value = if event.readable
1045 || event.writable
1046 || event
1047 .extra
1048 .flags
1049 .intersects(socket_state.interest.extra.flags)
1050 {
1051 // If we are in oneshot mode, remove the interest.
1052 if matches!(socket_state.mode, PollMode::Oneshot) {
1053 socket_state.interest = Event::none(socket_state.interest.key);
1054 socket_state.interest_error = false;
1055 }
1056
1057 FeedEventResult::Event(event)
1058 } else {
1059 FeedEventResult::NoEvent
1060 };
1061
1062 // Put ourselves in the update queue.
1063 drop(socket_state);
1064 poller.update_packet(self)?;
1065
1066 // Return the event.
1067 Ok(return_value)
1068 }
1069
1070 /// Begin deleting this socket.
1071 fn begin_delete(self: Pin<Arc<Self>>) -> io::Result<()> {
1072 // If we aren't already being deleted, start deleting.
1073 let mut socket = match self.as_ref().data().project_ref() {
1074 PacketInnerProj::Socket { socket, .. } => lock!(socket.lock()),
1075 PacketInnerProj::Waitable { handle } => {
1076 let mut handle = lock!(handle.lock());
1077
1078 // Set the status to be cancelled. This drops the wait handle and prevents
1079 // any further updates.
1080 handle.status = WaitableStatus::Cancelled;
1081
1082 return Ok(());
1083 }
1084 _ => panic!("can't delete packet that doesn't belong to a socket"),
1085 };
1086 if !socket.waiting_on_delete {
1087 socket.waiting_on_delete = true;
1088
1089 if matches!(socket.status, SocketStatus::Polling { .. }) {
1090 // Cancel the ongoing poll.
1091 self.cancel(socket)?;
1092 }
1093 }
1094
1095 // Either drop it now or wait for it to be dropped later.
1096 Ok(())
1097 }
1098
1099 fn cancel(self: &Pin<Arc<Self>>, mut socket: MutexGuard<'_, SocketState>) -> io::Result<()> {
1100 assert!(matches!(socket.status, SocketStatus::Polling { .. }));
1101
1102 // Send the cancel request.
1103 unsafe {
1104 socket.afd.cancel(self)?;
1105 }
1106
1107 // Move state to cancelled.
1108 socket.status = SocketStatus::Cancelled;
1109
1110 Ok(())
1111 }
1112 }
1113
1114 /// Per-socket state.
1115 #[derive(Debug)]
1116 struct SocketState {
1117 /// The raw socket handle.
1118 socket: RawSocket,
1119
1120 /// The base socket handle.
1121 base_socket: RawSocket,
1122
1123 /// The event that this socket is currently waiting on.
1124 interest: Event,
1125
1126 /// Whether to listen for error events.
1127 interest_error: bool,
1128
1129 /// The current poll mode.
1130 mode: PollMode,
1131
1132 /// The AFD instance that this socket is registered with.
1133 afd: Arc<Afd<Packet>>,
1134
1135 /// Whether this socket is waiting to be deleted.
1136 waiting_on_delete: bool,
1137
1138 /// The current status of the socket.
1139 status: SocketStatus,
1140 }
1141
1142 /// The mode that a socket can be in.
1143 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1144 enum SocketStatus {
1145 /// We are currently not polling.
1146 Idle,
1147
1148 /// We are currently polling these events.
1149 Polling {
1150 /// The flags we are currently polling for.
1151 flags: AfdPollMask,
1152 },
1153
1154 /// The last poll operation was cancelled, and we're waiting for it to
1155 /// complete.
1156 Cancelled,
1157 }
1158
1159 /// Per-waitable handle state.
1160 #[derive(Debug)]
1161 struct WaitableState {
1162 /// The handle that this state is for.
1163 handle: RawHandle,
1164
1165 /// The IO completion port that this handle is registered with.
1166 port: Weak<IoCompletionPort<Packet>>,
1167
1168 /// The event that this handle will report.
1169 interest: Event,
1170
1171 /// The current poll mode.
1172 mode: PollMode,
1173
1174 /// The status of this waitable.
1175 status: WaitableStatus,
1176 }
1177
1178 #[derive(Debug)]
1179 enum WaitableStatus {
1180 /// We are not polling.
1181 Idle,
1182
1183 /// We are waiting on this handle to become signaled.
1184 Waiting(#[allow(dead_code)] WaitHandle),
1185
1186 /// This handle has been cancelled.
1187 Cancelled,
1188 }
1189
1190 impl WaitableStatus {
1191 fn is_idle(&self) -> bool {
1192 matches!(self, WaitableStatus::Idle)
1193 }
1194 }
1195
1196 /// The result of calling `feed_event`.
1197 #[derive(Debug)]
1198 enum FeedEventResult {
1199 /// No event was yielded.
1200 NoEvent,
1201
1202 /// An event was yielded.
1203 Event(Event),
1204
1205 /// The poller has been notified.
1206 Notified,
1207 }
1208
1209 /// A handle for an ongoing wait operation.
1210 #[derive(Debug)]
1211 struct WaitHandle(RawHandle);
1212
1213 impl Drop for WaitHandle {
1214 fn drop(&mut self) {
1215 unsafe {
1216 UnregisterWait(self.0 as _);
1217 }
1218 }
1219 }
1220
1221 impl WaitHandle {
1222 /// Wait for a waitable handle to become signaled.
1223 fn new<F>(
1224 handle: RawHandle,
1225 callback: F,
1226 timeout: Option<Duration>,
1227 long_wait: bool,
1228 ) -> io::Result<Self>
1229 where
1230 F: FnOnce() + Send + Sync + 'static,
1231 {
1232 // Make sure a panic in the callback doesn't propagate to the OS.
1233 struct AbortOnDrop;
1234
1235 impl Drop for AbortOnDrop {
1236 fn drop(&mut self) {
1237 std::process::abort();
1238 }
1239 }
1240
1241 unsafe extern "system" fn wait_callback<F: FnOnce() + Send + Sync + 'static>(
1242 context: *mut c_void,
1243 _timer_fired: bool,
1244 ) {
1245 let _guard = AbortOnDrop;
1246 let callback = Box::from_raw(context as *mut F);
1247 callback();
1248
1249 // We executed without panicking, so don't abort.
1250 forget(_guard);
1251 }
1252
1253 let mut wait_handle = MaybeUninit::<RawHandle>::uninit();
1254
1255 let mut flags = WT_EXECUTEONLYONCE;
1256 if long_wait {
1257 flags |= WT_EXECUTELONGFUNCTION;
1258 }
1259
1260 let res = unsafe {
1261 RegisterWaitForSingleObject(
1262 wait_handle.as_mut_ptr().cast::<_>(),
1263 handle as _,
1264 Some(wait_callback::<F>),
1265 Box::into_raw(Box::new(callback)) as _,
1266 timeout.map_or(INFINITE, dur2timeout),
1267 flags,
1268 )
1269 };
1270
1271 if res == 0 {
1272 return Err(io::Error::last_os_error());
1273 }
1274
1275 let wait_handle = unsafe { wait_handle.assume_init() };
1276 Ok(Self(wait_handle))
1277 }
1278 }
1279
1280 /// Translate an event to the mask expected by AFD.
1281 #[inline]
1282 fn event_to_afd_mask(event: Event, error: bool) -> afd::AfdPollMask {
1283 event_properties_to_afd_mask(event.readable, event.writable, error) | event.extra.flags
1284 }
1285
1286 /// Translate an event to the mask expected by AFD.
1287 #[inline]
1288 fn event_properties_to_afd_mask(readable: bool, writable: bool, error: bool) -> afd::AfdPollMask {
1289 use afd::AfdPollMask as AfdPoll;
1290
1291 let mut mask = AfdPoll::empty();
1292
1293 if error || readable || writable {
1294 mask |= AfdPoll::ABORT | AfdPoll::CONNECT_FAIL;
1295 }
1296
1297 if readable {
1298 mask |=
1299 AfdPoll::RECEIVE | AfdPoll::ACCEPT | AfdPoll::DISCONNECT | AfdPoll::RECEIVE_EXPEDITED;
1300 }
1301
1302 if writable {
1303 mask |= AfdPoll::SEND;
1304 }
1305
1306 mask
1307 }
1308
1309 /// Convert the mask reported by AFD to an event.
1310 #[inline]
1311 fn afd_mask_to_event(mask: afd::AfdPollMask) -> (bool, bool) {
1312 use afd::AfdPollMask as AfdPoll;
1313
1314 let mut readable = false;
1315 let mut writable = false;
1316
1317 if mask.intersects(
1318 AfdPoll::RECEIVE | AfdPoll::ACCEPT | AfdPoll::DISCONNECT | AfdPoll::RECEIVE_EXPEDITED,
1319 ) {
1320 readable = true;
1321 }
1322
1323 if mask.intersects(AfdPoll::SEND) {
1324 writable = true;
1325 }
1326
1327 if mask.intersects(AfdPoll::ABORT | AfdPoll::CONNECT_FAIL) {
1328 readable = true;
1329 writable = true;
1330 }
1331
1332 (readable, writable)
1333 }
1334
1335 // Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs
1336 fn dur2timeout(dur: Duration) -> u32 {
1337 // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
1338 // timeouts in windows APIs are typically u32 milliseconds. To translate, we
1339 // have two pieces to take care of:
1340 //
1341 // * Nanosecond precision is rounded up
1342 // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
1343 // (never time out).
1344 dur.as_secs()
1345 .checked_mul(1000)
1346 .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000))
1347 .and_then(|ms| {
1348 if dur.subsec_nanos() % 1_000_000 > 0 {
1349 ms.checked_add(1)
1350 } else {
1351 Some(ms)
1352 }
1353 })
1354 .and_then(|x| u32::try_from(x).ok())
1355 .unwrap_or(INFINITE)
1356 }
1357
1358 /// An error type that wraps around failing to open AFD.
1359 struct AfdError {
1360 /// String description of what happened.
1361 description: &'static str,
1362
1363 /// The underlying system error.
1364 system: io::Error,
1365 }
1366
1367 impl AfdError {
1368 #[inline]
1369 fn new(description: &'static str, system: io::Error) -> Self {
1370 Self {
1371 description,
1372 system,
1373 }
1374 }
1375 }
1376
1377 impl fmt::Debug for AfdError {
1378 #[inline]
1379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1380 f.debug_struct("AfdError")
1381 .field("description", &self.description)
1382 .field("system", &self.system)
1383 .field("note", &"probably caused by old Windows or Wine")
1384 .finish()
1385 }
1386 }
1387
1388 impl fmt::Display for AfdError {
1389 #[inline]
1390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1391 write!(
1392 f,
1393 "{}: {}\nThis error is usually caused by running on old Windows or Wine",
1394 self.description, &self.system
1395 )
1396 }
1397 }
1398
1399 impl std::error::Error for AfdError {
1400 #[inline]
1401 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1402 Some(&self.system)
1403 }
1404 }
1405
1406 struct CallOnDrop<F: FnMut()>(F);
1407
1408 impl<F: FnMut()> Drop for CallOnDrop<F> {
1409 fn drop(&mut self) {
1410 (self.0)();
1411 }
1412 }