Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an epoll::wait_uninit. #1309

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions src/backend/libc/event/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::backend::c;
#[cfg(any(linux_kernel, solarish, target_os = "redox"))]
use crate::backend::conv::ret;
use crate::backend::conv::ret_c_int;
#[cfg(feature = "alloc")]
#[cfg(any(linux_kernel, target_os = "illumos", target_os = "redox"))]
use crate::backend::conv::ret_u32;
#[cfg(solarish)]
Expand All @@ -27,7 +26,7 @@ use crate::utils::as_ptr;
#[cfg(any(
all(feature = "alloc", bsd),
solarish,
all(feature = "alloc", any(linux_kernel, target_os = "redox")),
all(any(linux_kernel, target_os = "redox")),
))]
use core::mem::MaybeUninit;
#[cfg(any(
Expand Down Expand Up @@ -526,7 +525,6 @@ pub(crate) fn epoll_del(epoll: BorrowedFd<'_>, source: BorrowedFd<'_>) -> io::Re
}

#[inline]
#[cfg(feature = "alloc")]
#[cfg(any(linux_kernel, target_os = "illumos", target_os = "redox"))]
pub(crate) fn epoll_wait(
epoll: BorrowedFd<'_>,
Expand Down
3 changes: 0 additions & 3 deletions src/backend/linux_raw/event/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
//! See the `rustix::backend` module documentation for details.
#![allow(unsafe_code, clippy::undocumented_unsafe_blocks)]

#[cfg(feature = "alloc")]
use crate::backend::c;
use crate::backend::conv::{
by_ref, c_int, c_uint, opt_ref, ret, ret_c_int, ret_error, ret_owned_fd, ret_usize, size_of,
Expand All @@ -15,7 +14,6 @@ use crate::event::{epoll, EventfdFlags, FdSetElement, PollFd, Timespec};
use crate::fd::{BorrowedFd, OwnedFd};
use crate::io;
use crate::utils::{as_mut_ptr, option_as_ptr};
#[cfg(feature = "alloc")]
use core::mem::MaybeUninit;
use core::ptr::null_mut;
use linux_raw_sys::general::{kernel_sigset_t, EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD};
Expand Down Expand Up @@ -176,7 +174,6 @@ pub(crate) fn epoll_del(epfd: BorrowedFd<'_>, fd: BorrowedFd<'_>) -> io::Result<
}
}

#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn epoll_wait(
epfd: BorrowedFd<'_>,
Expand Down
14 changes: 7 additions & 7 deletions src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@
use core::mem::MaybeUninit;
use core::slice;

/// Split an uninitialized byte slice into initialized and uninitialized parts.
/// Split an uninitialized slice into initialized and uninitialized parts.
///
/// # Safety
///
/// `init_len` must not be greater than `buf.len()`, and at least `init_len`
/// bytes must be initialized.
/// elements must be initialized.
#[inline]
pub(super) unsafe fn split_init(
buf: &mut [MaybeUninit<u8>],
pub(super) unsafe fn split_init<T>(
buf: &mut [MaybeUninit<T>],
init_len: usize,
) -> (&mut [u8], &mut [MaybeUninit<u8>]) {
) -> (&mut [T], &mut [MaybeUninit<T>]) {
debug_assert!(init_len <= buf.len());
let buf_ptr = buf.as_mut_ptr();
let uninit_len = buf.len() - init_len;
let init = slice::from_raw_parts_mut(buf_ptr.cast::<u8>(), init_len);
let init = slice::from_raw_parts_mut(buf_ptr.cast::<T>(), init_len);
let uninit = slice::from_raw_parts_mut(buf_ptr.add(init_len), uninit_len);
(init, uninit)
}
Expand Down Expand Up @@ -66,7 +66,7 @@ mod tests {
#[test]
fn test_split_init_empty() {
unsafe {
let (init, uninit) = split_init(&mut [], 0);
let (init, uninit) = split_init::<u8>(&mut [], 0);
assert!(init.is_empty());
assert!(uninit.is_empty());
}
Expand Down
26 changes: 26 additions & 0 deletions src/event/epoll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,14 @@
use super::epoll;
pub use crate::backend::event::epoll::*;
use crate::backend::event::syscalls;
use crate::buffer::split_init;
use crate::fd::{AsFd, OwnedFd};
use crate::io;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::ffi::c_void;
use core::hash::{Hash, Hasher};
use core::mem::MaybeUninit;

/// `epoll_create1(flags)`—Creates a new epoll object.
///
Expand Down Expand Up @@ -190,6 +192,9 @@ pub fn delete<EpollFd: AsFd, SourceFd: AsFd>(epoll: EpollFd, source: SourceFd) -
/// For each event of interest, an element is written to `events`. On
/// success, this returns the number of written elements.
///
/// This takes a `&mut [Event]` which Rust requires to contain initialized
/// memory. To use an uninitialized buffer, use [`wait_uninit`].
///
/// # References
/// - [Linux]
/// - [illumos]
Expand All @@ -215,6 +220,27 @@ pub fn wait<EpollFd: AsFd>(
Ok(())
}

/// `epoll_wait(self, events, timeout)`—Waits for registered events of
/// interest.
///
/// This is identical to [`wait`], except that it can write the events into
/// uninitialized memory. It returns the slice that was initialized by this
/// function and the slice that remains uninitialized.
#[doc(alias = "epoll_wait")]
#[inline]
pub fn wait_uninit<EpollFd: AsFd>(
epoll: EpollFd,
event_list: &mut [MaybeUninit<Event>],
timeout: crate::ffi::c_int,
) -> io::Result<(&mut [Event], &mut [MaybeUninit<Event>])> {
// SAFETY: We're calling `epoll_wait` via FFI and we know how it
// behaves.
unsafe {
let nfds = syscalls::epoll_wait(epoll.as_fd(), event_list, timeout)?;
Ok(split_init(event_list, nfds))
}
}

/// A record of an event that occurred.
#[repr(C)]
#[cfg_attr(all(not(libc), target_arch = "x86_64"), repr(packed))]
Expand Down
77 changes: 77 additions & 0 deletions tests/event/epoll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustix::net::{
};
use std::collections::HashMap;
use std::ffi::c_void;
use std::mem::MaybeUninit;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;

Expand Down Expand Up @@ -67,6 +68,62 @@ fn server(ready: Arc<(Mutex<u16>, Condvar)>) {
}
}

fn server_uninit(ready: Arc<(Mutex<u16>, Condvar)>) {
let listen_sock = socket(AddressFamily::INET, SocketType::STREAM, None).unwrap();
bind_v4(&listen_sock, &SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)).unwrap();
listen(&listen_sock, 1).unwrap();

let who = match getsockname(&listen_sock).unwrap() {
SocketAddrAny::V4(addr) => addr,
_ => panic!(),
};

{
let (lock, cvar) = &*ready;
let mut port = lock.lock().unwrap();
*port = who.port();
cvar.notify_all();
}

let epoll = epoll::create(epoll::CreateFlags::CLOEXEC).unwrap();

epoll::add(
&epoll,
&listen_sock,
epoll::EventData::new_u64(1),
epoll::EventFlags::IN,
)
.unwrap();

let mut next_data = epoll::EventData::new_u64(2);
let mut targets = HashMap::new();

let mut event_list = [MaybeUninit::uninit(); 4];
loop {
let (init, _) = epoll::wait_uninit(&epoll, &mut event_list, -1).unwrap();
for event in init {
let target = event.data;
if target.u64() == 1 {
let conn_sock = accept(&listen_sock).unwrap();
ioctl_fionbio(&conn_sock, true).unwrap();
epoll::add(
&epoll,
&conn_sock,
next_data,
epoll::EventFlags::OUT | epoll::EventFlags::ET,
)
.unwrap();
targets.insert(next_data, conn_sock);
next_data = epoll::EventData::new_u64(next_data.u64() + 1);
} else {
let target = targets.remove(&target).unwrap();
write(&target, b"hello\n").unwrap();
epoll::delete(&epoll, &target).unwrap();
}
}
}
}

fn client(ready: Arc<(Mutex<u16>, Condvar)>) {
let port = {
let (lock, cvar) = &*ready;
Expand Down Expand Up @@ -109,6 +166,26 @@ fn test_epoll() {
client.join().unwrap();
}

#[test]
fn test_epoll_uninit() {
let ready = Arc::new((Mutex::new(0_u16), Condvar::new()));
let ready_clone = Arc::clone(&ready);

let _server = thread::Builder::new()
.name("server".to_string())
.spawn(move || {
server_uninit(ready);
})
.unwrap();
let client = thread::Builder::new()
.name("client".to_string())
.spawn(move || {
client(ready_clone);
})
.unwrap();
client.join().unwrap();
}

#[test]
fn test_epoll_event_data() {
let d = epoll::EventData::new_u64(0);
Expand Down