rustix/event/
epoll.rs

1//! Linux `epoll` support.
2//!
3//! # Examples
4//!
5//! ```no_run
6//! # #[cfg(feature = "net")]
7//! # fn main() -> std::io::Result<()> {
8//! use rustix::buffer::spare_capacity;
9//! use rustix::event::epoll;
10//! use rustix::fd::AsFd;
11//! use rustix::io::{ioctl_fionbio, read, write};
12//! use rustix::net::{
13//!     accept, bind, listen, socket, AddressFamily, Ipv4Addr, SocketAddrV4, SocketType,
14//! };
15//! use std::collections::HashMap;
16//! use std::os::unix::io::AsRawFd;
17//!
18//! // Create a socket and listen on it.
19//! let listen_sock = socket(AddressFamily::INET, SocketType::STREAM, None)?;
20//! bind(&listen_sock, &SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))?;
21//! listen(&listen_sock, 1)?;
22//!
23//! // Create an epoll object. Using `Owning` here means the epoll object will
24//! // take ownership of the file descriptors registered with it.
25//! let epoll = epoll::create(epoll::CreateFlags::CLOEXEC)?;
26//!
27//! // Register the socket with the epoll object.
28//! epoll::add(
29//!     &epoll,
30//!     &listen_sock,
31//!     epoll::EventData::new_u64(1),
32//!     epoll::EventFlags::IN,
33//! )?;
34//!
35//! // Keep track of the sockets we've opened.
36//! let mut next_id = epoll::EventData::new_u64(2);
37//! let mut sockets = HashMap::new();
38//!
39//! // Process events.
40//! let mut event_list = Vec::with_capacity(4);
41//! loop {
42//!     epoll::wait(&epoll, spare_capacity(&mut event_list), None)?;
43//!     for event in event_list.drain(..) {
44//!         let target = event.data;
45//!         if target.u64() == 1 {
46//!             // Accept a new connection, set it to non-blocking, and
47//!             // register to be notified when it's ready to write to.
48//!             let conn_sock = accept(&listen_sock)?;
49//!             ioctl_fionbio(&conn_sock, true)?;
50//!             epoll::add(
51//!                 &epoll,
52//!                 &conn_sock,
53//!                 next_id,
54//!                 epoll::EventFlags::OUT | epoll::EventFlags::ET,
55//!             )?;
56//!
57//!             // Keep track of the socket.
58//!             sockets.insert(next_id, conn_sock);
59//!             next_id = epoll::EventData::new_u64(next_id.u64() + 1);
60//!         } else {
61//!             // Write a message to the stream and then unregister it.
62//!             let target = sockets.remove(&target).unwrap();
63//!             write(&target, b"hello\n")?;
64//!             let _ = epoll::delete(&epoll, &target)?;
65//!         }
66//!     }
67//! }
68//! # }
69//! # #[cfg(not(feature = "net"))]
70//! # fn main() {}
71//! ```
72
73#![allow(unsafe_code)]
74#![allow(unused_qualifications)]
75
76use super::epoll;
77pub use crate::backend::event::epoll::*;
78use crate::backend::event::syscalls;
79use crate::buffer::Buffer;
80use crate::fd::{AsFd, OwnedFd};
81use crate::io;
82use crate::timespec::Timespec;
83use core::ffi::c_void;
84use core::hash::{Hash, Hasher};
85
86/// `epoll_create1(flags)`—Creates a new epoll object.
87///
88/// Use the [`epoll::CreateFlags::CLOEXEC`] flag to prevent the resulting file
89/// descriptor from being implicitly passed across `exec` boundaries.
90///
91/// # References
92///  - [Linux]
93///  - [illumos]
94///
95/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_create.2.html
96/// [illumos]: https://www.illumos.org/man/3C/epoll_create
97#[inline]
98#[doc(alias = "epoll_create1")]
99pub fn create(flags: epoll::CreateFlags) -> io::Result<OwnedFd> {
100    syscalls::epoll_create(flags)
101}
102
103/// `epoll_ctl(self, EPOLL_CTL_ADD, data, event)`—Adds an element to an epoll
104/// object.
105///
106/// This registers interest in any of the events set in `event_flags` occurring
107/// on the file descriptor associated with `data`.
108///
109/// `close`ing a file descriptor does not necessarily unregister interest which
110/// can lead to spurious events being returned from [`epoll::wait`]. If a file
111/// descriptor is an `Arc<dyn SystemResource>`, then `epoll` can be thought to
112/// maintain a `Weak<dyn SystemResource>` to the file descriptor. Check the
113/// [faq] for details.
114///
115/// # References
116///  - [Linux]
117///  - [illumos]
118///
119/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
120/// [illumos]: https://www.illumos.org/man/3C/epoll_ctl
121/// [faq]: https://man7.org/linux/man-pages/man7/epoll.7.html#:~:text=Will%20closing%20a%20file%20descriptor%20cause%20it%20to%20be%20removed%20from%20all%0A%20%20%20%20%20%20%20%20%20%20epoll%20interest%20lists%3F
122#[doc(alias = "epoll_ctl")]
123#[inline]
124pub fn add<EpollFd: AsFd, SourceFd: AsFd>(
125    epoll: EpollFd,
126    source: SourceFd,
127    data: epoll::EventData,
128    event_flags: epoll::EventFlags,
129) -> io::Result<()> {
130    syscalls::epoll_add(
131        epoll.as_fd(),
132        source.as_fd(),
133        &Event {
134            flags: event_flags,
135            data,
136            #[cfg(all(libc, target_os = "redox"))]
137            _pad: 0,
138        },
139    )
140}
141
142/// `epoll_ctl(self, EPOLL_CTL_MOD, target, event)`—Modifies an element in a
143/// given epoll object.
144///
145/// This sets the events of interest with `target` to `events`.
146///
147/// # References
148///  - [Linux]
149///  - [illumos]
150///
151/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
152/// [illumos]: https://www.illumos.org/man/3C/epoll_ctl
153#[doc(alias = "epoll_ctl")]
154#[inline]
155pub fn modify<EpollFd: AsFd, SourceFd: AsFd>(
156    epoll: EpollFd,
157    source: SourceFd,
158    data: epoll::EventData,
159    event_flags: epoll::EventFlags,
160) -> io::Result<()> {
161    syscalls::epoll_mod(
162        epoll.as_fd(),
163        source.as_fd(),
164        &Event {
165            flags: event_flags,
166            data,
167            #[cfg(all(libc, target_os = "redox"))]
168            _pad: 0,
169        },
170    )
171}
172
173/// `epoll_ctl(self, EPOLL_CTL_DEL, target, NULL)`—Removes an element in a
174/// given epoll object.
175///
176/// # References
177///  - [Linux]
178///  - [illumos]
179///
180/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
181/// [illumos]: https://www.illumos.org/man/3C/epoll_ctl
182#[doc(alias = "epoll_ctl")]
183#[inline]
184pub fn delete<EpollFd: AsFd, SourceFd: AsFd>(epoll: EpollFd, source: SourceFd) -> io::Result<()> {
185    syscalls::epoll_del(epoll.as_fd(), source.as_fd())
186}
187
188/// `epoll_wait(self, events, timeout)`—Waits for registered events of
189/// interest.
190///
191/// For each event of interest, an element is written to `events`.
192///
193/// Linux versions older than 5.11 (those that don't support `epoll_pwait2`)
194/// don't support timeouts greater than `c_int::MAX` milliseconds; if an
195/// unsupported timeout is passed, this function fails with
196/// [`io::Errno::INVAL`]. Enable the "linux_5_11" feature to enable the full
197/// range of timeouts.
198///
199/// # References
200///  - [Linux]
201///  - [illumos]
202///
203/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_wait.2.html
204/// [illumos]: https://www.illumos.org/man/3C/epoll_wait
205#[doc(alias = "epoll_wait")]
206#[inline]
207pub fn wait<EpollFd: AsFd, Buf: Buffer<Event>>(
208    epoll: EpollFd,
209    mut event_list: Buf,
210    timeout: Option<&Timespec>,
211) -> io::Result<Buf::Output> {
212    // SAFETY: `epoll_wait` behaves.
213    let nfds = unsafe { syscalls::epoll_wait(epoll.as_fd(), event_list.parts_mut(), timeout)? };
214    // SAFETY: `epoll_wait` behaves.
215    unsafe { Ok(event_list.assume_init(nfds)) }
216}
217
218/// A record of an event that occurred.
219#[repr(C)]
220#[cfg_attr(all(not(libc), target_arch = "x86_64"), repr(packed))]
221#[cfg_attr(
222    all(
223        libc,
224        linux_kernel,
225        any(
226            all(
227                target_arch = "x86",
228                not(target_env = "musl"),
229                not(target_os = "android"),
230            ),
231            target_arch = "x86_64",
232        )
233    ),
234    repr(packed)
235)]
236#[cfg_attr(
237    all(solarish, any(target_arch = "x86", target_arch = "x86_64")),
238    repr(packed(4))
239)]
240#[derive(Copy, Clone, Eq, PartialEq, Hash)]
241pub struct Event {
242    /// Which specific event(s) occurred.
243    pub flags: EventFlags,
244    /// User data.
245    pub data: EventData,
246
247    #[cfg(all(libc, target_os = "redox"))]
248    _pad: u64,
249}
250
251/// Data associated with an [`epoll::Event`]. This can either be a 64-bit
252/// integer value or a pointer which preserves pointer provenance.
253#[repr(C)]
254#[derive(Copy, Clone)]
255pub union EventData {
256    /// A 64-bit integer value.
257    as_u64: u64,
258
259    /// A `*mut c_void` which preserves pointer provenance, extended to be
260    /// 64-bit so that if we read the value as a `u64` union field, we don't
261    /// get uninitialized memory.
262    sixty_four_bit_pointer: SixtyFourBitPointer,
263}
264
265impl EventData {
266    /// Construct a new value containing a `u64`.
267    #[inline]
268    pub const fn new_u64(value: u64) -> Self {
269        Self { as_u64: value }
270    }
271
272    /// Construct a new value containing a `*mut c_void`.
273    #[inline]
274    pub const fn new_ptr(value: *mut c_void) -> Self {
275        Self {
276            sixty_four_bit_pointer: SixtyFourBitPointer {
277                pointer: value,
278                #[cfg(target_pointer_width = "32")]
279                _padding: 0,
280            },
281        }
282    }
283
284    /// Return the value as a `u64`.
285    ///
286    /// If the stored value was a pointer, the pointer is zero-extended to a
287    /// `u64`.
288    #[inline]
289    pub fn u64(self) -> u64 {
290        unsafe { self.as_u64 }
291    }
292
293    /// Return the value as a `*mut c_void`.
294    ///
295    /// If the stored value was a `u64`, the least-significant bits of the
296    /// `u64` are returned as a pointer value.
297    #[inline]
298    pub fn ptr(self) -> *mut c_void {
299        unsafe { self.sixty_four_bit_pointer.pointer }
300    }
301}
302
303impl PartialEq for EventData {
304    #[inline]
305    fn eq(&self, other: &Self) -> bool {
306        self.u64() == other.u64()
307    }
308}
309
310impl Eq for EventData {}
311
312impl Hash for EventData {
313    #[inline]
314    fn hash<H: Hasher>(&self, state: &mut H) {
315        self.u64().hash(state)
316    }
317}
318
319#[repr(C)]
320#[derive(Copy, Clone)]
321struct SixtyFourBitPointer {
322    #[cfg(target_endian = "big")]
323    #[cfg(target_pointer_width = "32")]
324    _padding: u32,
325
326    pointer: *mut c_void,
327
328    #[cfg(target_endian = "little")]
329    #[cfg(target_pointer_width = "32")]
330    _padding: u32,
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use crate::backend::c;
337
338    #[test]
339    fn test_epoll_layouts() {
340        check_renamed_type!(Event, epoll_event);
341        check_renamed_struct_renamed_field!(Event, epoll_event, flags, events);
342        #[cfg(libc)]
343        check_renamed_struct_renamed_field!(Event, epoll_event, data, u64);
344        #[cfg(not(libc))]
345        check_renamed_struct_renamed_field!(Event, epoll_event, data, data);
346    }
347}