Debian Codegraph @

third_party/rust/mio/src/sys/unix/waker/eventfd.rs

raw
1 use std::fs::File;
2 use std::io::{self, Read, Write};
3 #[cfg(not(target_os = "hermit"))]
4 use std::os::fd::{AsRawFd, FromRawFd, RawFd};
5 // TODO: once <https://github.com/rust-lang/rust/issues/126198> is fixed this
6 // can use `std::os::fd` and be merged with the above.
7 #[cfg(target_os = "hermit")]
8 use std::os::hermit::io::{AsRawFd, FromRawFd, RawFd};
9
10 use crate::sys::Selector;
11 use crate::{Interest, Token};
12
13 /// Waker backed by `eventfd`.
14 ///
15 /// `eventfd` is effectively an 64 bit counter. All writes must be of 8
16 /// bytes (64 bits) and are converted (native endian) into an 64 bit
17 /// unsigned integer and added to the count. Reads must also be 8 bytes and
18 /// reset the count to 0, returning the count.
19 #[derive(Debug)]
20 pub(crate) struct Waker {
21 fd: File,
22 }
23
24 impl Waker {
25 #[allow(dead_code)] // Not used by the `poll(2)` implementation.
26 pub(crate) fn new(selector: &Selector, token: Token) -> io::Result<Waker> {
27 let waker = Waker::new_unregistered()?;
28 selector.register(waker.fd.as_raw_fd(), token, Interest::READABLE)?;
29 Ok(waker)
30 }
31
32 pub(crate) fn new_unregistered() -> io::Result<Waker> {
33 #[cfg(not(target_os = "espidf"))]
34 let flags = libc::EFD_CLOEXEC | libc::EFD_NONBLOCK;
35 // ESP-IDF is EFD_NONBLOCK by default and errors if you try to pass this flag.
36 #[cfg(target_os = "espidf")]
37 let flags = 0;
38 let fd = syscall!(eventfd(0, flags))?;
39 let file = unsafe { File::from_raw_fd(fd) };
40 Ok(Waker { fd: file })
41 }
42
43 #[allow(clippy::unused_io_amount)] // Don't care about partial writes.
44 pub(crate) fn wake(&self) -> io::Result<()> {
45 let buf: [u8; 8] = 1u64.to_ne_bytes();
46 match (&self.fd).write(&buf) {
47 Ok(_) => Ok(()),
48 Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => {
49 // Writing only blocks if the counter is going to overflow.
50 // So we'll reset the counter to 0 and wake it again.
51 self.reset()?;
52 self.wake()
53 }
54 Err(err) => Err(err),
55 }
56 }
57
58 #[allow(dead_code)] // Only used by the `poll(2)` implementation.
59 pub(crate) fn ack_and_reset(&self) {
60 let _ = self.reset();
61 }
62
63 /// Reset the eventfd object, only need to call this if `wake` fails.
64 #[allow(clippy::unused_io_amount)] // Don't care about partial reads.
65 fn reset(&self) -> io::Result<()> {
66 let mut buf: [u8; 8] = 0u64.to_ne_bytes();
67 match (&self.fd).read(&mut buf) {
68 Ok(_) => Ok(()),
69 // If the `Waker` hasn't been awoken yet this will return a
70 // `WouldBlock` error which we can safely ignore.
71 Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Ok(()),
72 Err(err) => Err(err),
73 }
74 }
75 }
76
77 impl AsRawFd for Waker {
78 fn as_raw_fd(&self) -> RawFd {
79 self.fd.as_raw_fd()
80 }
81 }