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;
83#[cfg(target_pointer_width = "32")]
84use crate::types::Padding;
85use core::ffi::c_void;
86use core::hash::{Hash, Hasher};
87
88/// `epoll_create1(flags)`—Creates a new epoll object.
89///
90/// Use the [`epoll::CreateFlags::CLOEXEC`] flag to prevent the resulting file
91/// descriptor from being implicitly passed across `exec` boundaries.
92///
93/// # References
94/// - [Linux]
95/// - [illumos]
96///
97/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_create.2.html
98/// [illumos]: https://www.illumos.org/man/3C/epoll_create
99#[inline]
100#[doc(alias = "epoll_create1")]
101pub fn create(flags: epoll::CreateFlags) -> io::Result<OwnedFd> {
102 syscalls::epoll_create(flags)
103}
104
105/// `epoll_ctl(self, EPOLL_CTL_ADD, data, event)`—Adds an element to an epoll
106/// object.
107///
108/// This registers interest in any of the events set in `event_flags` occurring
109/// on the file descriptor associated with `data`.
110///
111/// `close`ing a file descriptor does not necessarily unregister interest which
112/// can lead to spurious events being returned from [`epoll::wait`]. If a file
113/// descriptor is an `Arc<dyn SystemResource>`, then `epoll` can be thought to
114/// maintain a `Weak<dyn SystemResource>` to the file descriptor. Check the
115/// [faq] for details.
116///
117/// # References
118/// - [Linux]
119/// - [illumos]
120///
121/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
122/// [illumos]: https://www.illumos.org/man/3C/epoll_ctl
123/// [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
124#[doc(alias = "epoll_ctl")]
125#[inline]
126pub fn add<EpollFd: AsFd, SourceFd: AsFd>(
127 epoll: EpollFd,
128 source: SourceFd,
129 data: epoll::EventData,
130 event_flags: epoll::EventFlags,
131) -> io::Result<()> {
132 syscalls::epoll_add(
133 epoll.as_fd(),
134 source.as_fd(),
135 &Event {
136 flags: event_flags,
137 data,
138 #[cfg(all(libc, target_os = "redox"))]
139 _pad: 0,
140 },
141 )
142}
143
144/// `epoll_ctl(self, EPOLL_CTL_MOD, target, event)`—Modifies an element in a
145/// given epoll object.
146///
147/// This sets the events of interest with `target` to `events`.
148///
149/// # References
150/// - [Linux]
151/// - [illumos]
152///
153/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
154/// [illumos]: https://www.illumos.org/man/3C/epoll_ctl
155#[doc(alias = "epoll_ctl")]
156#[inline]
157pub fn modify<EpollFd: AsFd, SourceFd: AsFd>(
158 epoll: EpollFd,
159 source: SourceFd,
160 data: epoll::EventData,
161 event_flags: epoll::EventFlags,
162) -> io::Result<()> {
163 syscalls::epoll_mod(
164 epoll.as_fd(),
165 source.as_fd(),
166 &Event {
167 flags: event_flags,
168 data,
169 #[cfg(all(libc, target_os = "redox"))]
170 _pad: 0,
171 },
172 )
173}
174
175/// `epoll_ctl(self, EPOLL_CTL_DEL, target, NULL)`—Removes an element in a
176/// given epoll object.
177///
178/// # References
179/// - [Linux]
180/// - [illumos]
181///
182/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
183/// [illumos]: https://www.illumos.org/man/3C/epoll_ctl
184#[doc(alias = "epoll_ctl")]
185#[inline]
186pub fn delete<EpollFd: AsFd, SourceFd: AsFd>(epoll: EpollFd, source: SourceFd) -> io::Result<()> {
187 syscalls::epoll_del(epoll.as_fd(), source.as_fd())
188}
189
190/// `epoll_wait(self, events, timeout)`—Waits for registered events of
191/// interest.
192///
193/// For each event of interest, an element is written to `events`.
194///
195/// Linux versions older than 5.11 (those that don't support `epoll_pwait2`)
196/// don't support timeouts greater than `c_int::MAX` milliseconds; if an
197/// unsupported timeout is passed, this function fails with
198/// [`io::Errno::INVAL`]. Enable the "linux_5_11" feature to enable the full
199/// range of timeouts.
200///
201/// # References
202/// - [Linux]
203/// - [illumos]
204///
205/// [Linux]: https://man7.org/linux/man-pages/man2/epoll_wait.2.html
206/// [illumos]: https://www.illumos.org/man/3C/epoll_wait
207#[doc(alias = "epoll_wait")]
208#[inline]
209pub fn wait<EpollFd: AsFd, Buf: Buffer<Event>>(
210 epoll: EpollFd,
211 mut event_list: Buf,
212 timeout: Option<&Timespec>,
213) -> io::Result<Buf::Output> {
214 // SAFETY: `epoll_wait` behaves.
215 let nfds = unsafe { syscalls::epoll_wait(epoll.as_fd(), event_list.parts_mut(), timeout)? };
216 // SAFETY: `epoll_wait` behaves.
217 unsafe { Ok(event_list.assume_init(nfds)) }
218}
219
220/// A record of an event that occurred.
221#[repr(C)]
222#[cfg_attr(all(not(libc), target_arch = "x86_64"), repr(packed))]
223#[cfg_attr(
224 all(
225 libc,
226 linux_kernel,
227 any(
228 all(
229 target_arch = "x86",
230 not(target_env = "musl"),
231 not(target_os = "android"),
232 ),
233 target_arch = "x86_64",
234 )
235 ),
236 repr(packed)
237)]
238#[cfg_attr(
239 all(solarish, any(target_arch = "x86", target_arch = "x86_64")),
240 repr(packed(4))
241)]
242#[derive(Copy, Clone, Eq, PartialEq, Hash)]
243pub struct Event {
244 /// Which specific event(s) occurred.
245 pub flags: EventFlags,
246 /// User data.
247 pub data: EventData,
248
249 #[cfg(all(libc, target_os = "redox"))]
250 _pad: u64,
251}
252
253/// Data associated with an [`epoll::Event`]. This can either be a 64-bit
254/// integer value or a pointer which preserves pointer provenance.
255#[repr(C)]
256#[derive(Copy, Clone)]
257pub union EventData {
258 /// A 64-bit integer value.
259 as_u64: u64,
260
261 /// A `*mut c_void` which preserves pointer provenance, extended to be
262 /// 64-bit so that if we read the value as a `u64` union field, we don't
263 /// get uninitialized memory.
264 sixty_four_bit_pointer: SixtyFourBitPointer,
265}
266
267impl EventData {
268 /// Construct a new value containing a `u64`.
269 #[inline]
270 pub const fn new_u64(value: u64) -> Self {
271 Self { as_u64: value }
272 }
273
274 /// Construct a new value containing a `*mut c_void`.
275 #[inline]
276 pub const fn new_ptr(value: *mut c_void) -> Self {
277 Self {
278 sixty_four_bit_pointer: SixtyFourBitPointer {
279 pointer: value,
280 #[cfg(target_pointer_width = "32")]
281 _padding: Padding::new(0),
282 },
283 }
284 }
285
286 /// Return the value as a `u64`.
287 ///
288 /// If the stored value was a pointer, the pointer is zero-extended to a
289 /// `u64`.
290 #[inline]
291 pub fn u64(self) -> u64 {
292 unsafe { self.as_u64 }
293 }
294
295 /// Return the value as a `*mut c_void`.
296 ///
297 /// If the stored value was a `u64`, the least-significant bits of the
298 /// `u64` are returned as a pointer value.
299 #[inline]
300 pub fn ptr(self) -> *mut c_void {
301 unsafe { self.sixty_four_bit_pointer.pointer }
302 }
303}
304
305impl PartialEq for EventData {
306 #[inline]
307 fn eq(&self, other: &Self) -> bool {
308 self.u64() == other.u64()
309 }
310}
311
312impl Eq for EventData {}
313
314impl Hash for EventData {
315 #[inline]
316 fn hash<H: Hasher>(&self, state: &mut H) {
317 self.u64().hash(state)
318 }
319}
320
321#[repr(C)]
322#[derive(Copy, Clone)]
323struct SixtyFourBitPointer {
324 #[cfg(target_endian = "big")]
325 #[cfg(target_pointer_width = "32")]
326 _padding: Padding<u32>,
327
328 pointer: *mut c_void,
329
330 #[cfg(target_endian = "little")]
331 #[cfg(target_pointer_width = "32")]
332 _padding: Padding<u32>,
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use crate::backend::c;
339
340 #[test]
341 fn test_epoll_layouts() {
342 check_renamed_type!(Event, epoll_event);
343 check_renamed_struct_renamed_field!(Event, epoll_event, flags, events);
344 #[cfg(libc)]
345 check_renamed_struct_renamed_field!(Event, epoll_event, data, u64);
346 #[cfg(not(libc))]
347 check_renamed_struct_renamed_field!(Event, epoll_event, data, data);
348 }
349}