use core::time::Duration;
use crate::event::{Interest, Readiness};
use crate::sys::{RawHandle, cvt, errno};
use crate::time::Clock;
use crate::{Error, ErrorKind, Result};
const CLOCK_MONOTONIC: u32 = 1;
const EVENTTYPE_CLOCK: u8 = 0;
const EVENTTYPE_FD_READ: u8 = 1;
const EVENTTYPE_FD_WRITE: u8 = 2;
const EVENT_HANGUP: u16 = 1;
const TIMEOUT: u64 = u64::MAX;
const MAX_WAIT: u64 = (u32::MAX as u64) * 1_000_000_000;
const INLINE: usize = 64;
#[repr(C)]
#[derive(Clone, Copy)]
struct Subscription {
userdata: u64,
tag: u8,
padding: [u8; 7],
id: u32,
timeout: u64,
precision: u64,
flags: u16,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Event {
userdata: u64,
error: u16,
kind: u8,
nbytes: u64,
flags: u16,
}
const _: () = {
assert!(size_of::<Subscription>() == 48);
assert!(core::mem::offset_of!(Subscription, id) == 16);
assert!(core::mem::offset_of!(Subscription, timeout) == 24);
assert!(size_of::<Event>() == 32);
assert!(core::mem::offset_of!(Event, kind) == 10);
assert!(core::mem::offset_of!(Event, flags) == 24);
};
impl Subscription {
const EMPTY: Self = Self {
userdata: 0,
tag: 0,
padding: [0; 7],
id: 0,
timeout: 0,
precision: 0,
flags: 0,
};
}
impl Event {
const EMPTY: Self = Self {
userdata: 0,
error: 0,
kind: 0,
nbytes: 0,
flags: 0,
};
}
#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
fn poll_oneoff(
subscriptions: *const Subscription,
events: *mut Event,
count: usize,
stored: *mut usize,
) -> i32;
}
#[derive(Clone, Copy)]
pub(crate) struct PollFd {
fd: RawHandle,
interest: Interest,
readiness: Readiness,
}
impl PollFd {
pub(crate) fn new(fd: RawHandle, interest: Interest) -> Self {
Self {
fd,
interest,
readiness: Readiness::empty(),
}
}
pub(crate) fn raw(&self) -> RawHandle {
self.fd
}
pub(crate) fn interest(&self) -> Interest {
self.interest
}
pub(crate) fn readiness(&self) -> Readiness {
self.readiness
}
pub(crate) fn clear(&mut self) {
self.readiness = Readiness::empty();
}
}
fn monotonic() -> Result<u64> {
let now = crate::sys::time::clock(Clock::Monotonic)?;
Ok(u64::try_from(now.as_nanos()).unwrap_or(u64::MAX))
}
pub(crate) fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> Result<usize> {
let needed = fds
.iter()
.map(|fd| fd.interest.bits().count_ones() as usize)
.sum::<usize>()
+ usize::from(timeout.is_some());
if needed <= INLINE {
let mut subscriptions = [Subscription::EMPTY; INLINE];
let mut events = [Event::EMPTY; INLINE];
return poll_with(
fds,
timeout,
&mut subscriptions[..needed],
&mut events[..needed],
);
}
#[cfg(feature = "alloc")]
{
let mut subscriptions = alloc::vec![Subscription::EMPTY; needed];
let mut events = alloc::vec![Event::EMPTY; needed];
poll_with(fds, timeout, &mut subscriptions, &mut events)
}
#[cfg(not(feature = "alloc"))]
Err(ErrorKind::Unsupported.into())
}
fn poll_with(
fds: &mut [PollFd],
timeout: Option<Duration>,
subscriptions: &mut [Subscription],
events: &mut [Event],
) -> Result<usize> {
let deadline = match timeout {
Some(timeout) => {
let nanos = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX);
Some(monotonic()?.saturating_add(nanos))
}
None => None,
};
loop {
let mut count = 0;
for (index, fd) in fds.iter_mut().enumerate() {
fd.clear();
for (interest, tag) in [
(Interest::READABLE, EVENTTYPE_FD_READ),
(Interest::WRITABLE, EVENTTYPE_FD_WRITE),
] {
if fd.interest.contains(interest) {
subscriptions[count] = Subscription {
userdata: index as u64,
tag,
id: fd.fd as u32,
..Subscription::EMPTY
};
count += 1;
}
}
}
if let Some(deadline) = deadline {
subscriptions[count] = Subscription {
userdata: TIMEOUT,
tag: EVENTTYPE_CLOCK,
id: CLOCK_MONOTONIC,
timeout: deadline.saturating_sub(monotonic()?).min(MAX_WAIT),
..Subscription::EMPTY
};
count += 1;
}
if count == 0 {
return Err(ErrorKind::InvalidInput.into());
}
let mut stored = 0;
cvt(unsafe {
poll_oneoff(
subscriptions.as_ptr(),
events.as_mut_ptr(),
count,
&raw mut stored,
)
})?;
for event in &events[..stored.min(count)] {
if event.userdata == TIMEOUT {
if event.error != 0 {
return Err(Error::from_raw_os_error(event.error.into()));
}
continue;
}
let Some(fd) = fds.get_mut(event.userdata as usize) else {
continue;
};
if event.error != 0 {
fd.readiness |= if i32::from(event.error) == errno::EBADF {
Readiness::INVALID
} else {
Readiness::ERROR
};
continue;
}
match event.kind {
EVENTTYPE_FD_READ => fd.readiness |= Readiness::READABLE,
EVENTTYPE_FD_WRITE => fd.readiness |= Readiness::WRITABLE,
_ => {}
}
if event.flags & EVENT_HANGUP != 0 {
fd.readiness |= Readiness::HANGUP;
}
}
let ready = fds.iter().filter(|fd| !fd.readiness.is_empty()).count();
if ready > 0 {
return Ok(ready);
}
if let Some(deadline) = deadline
&& monotonic()? >= deadline
{
return Ok(0);
}
}
}
#[cfg(feature = "alloc")]
pub(crate) use poller::{Poller, RawEvent};
#[cfg(feature = "alloc")]
mod poller {
use alloc::vec::Vec;
use core::time::Duration;
use super::PollFd;
use crate::event::lock::Lock;
use crate::event::timers::{Op, Timers};
use crate::event::{Interest, ModeKind, Readiness};
use crate::sys::RawHandle;
use crate::{ErrorKind, Result};
#[derive(Clone, Copy)]
pub(crate) struct RawEvent {
token: usize,
readiness: Readiness,
wake: bool,
expirations: u64,
}
impl RawEvent {
pub(crate) const EMPTY: Self = Self {
token: 0,
readiness: Readiness::empty(),
wake: false,
expirations: 0,
};
pub(crate) fn is_timer(&self) -> bool {
self.expirations != 0
}
pub(crate) fn expirations(&self) -> u64 {
self.expirations
}
pub(crate) fn token(&self) -> usize {
self.token
}
pub(crate) fn is_wake(&self) -> bool {
self.wake
}
pub(crate) fn readiness(&self) -> Readiness {
self.readiness
}
}
struct Registration {
fd: RawHandle,
token: usize,
interest: Interest,
oneshot: bool,
armed: bool,
}
struct State {
registrations: Vec<Registration>,
woken: bool,
timers: Timers,
next: usize,
}
pub(crate) struct Poller(Lock<State>);
impl Poller {
pub(crate) fn new() -> Result<Self> {
Ok(Self(Lock::new(State {
registrations: Vec::new(),
woken: false,
timers: Timers::new(),
next: 0,
})))
}
pub(crate) fn register(
&self,
fd: RawHandle,
token: usize,
interest: Interest,
mode: ModeKind,
) -> Result<()> {
let mut state = self.0.lock();
if state.registrations.iter().any(|r| r.fd == fd) {
return Err(ErrorKind::AlreadyExists.into());
}
state
.registrations
.try_reserve(1)
.map_err(|_| ErrorKind::OutOfMemory)?;
state.registrations.push(Registration {
fd,
token,
interest,
oneshot: matches!(mode, ModeKind::OneShot),
armed: true,
});
Ok(())
}
pub(crate) fn modify(
&self,
fd: RawHandle,
token: usize,
interest: Interest,
mode: ModeKind,
) -> Result<()> {
let mut state = self.0.lock();
let Some(registration) = state.registrations.iter_mut().find(|r| r.fd == fd) else {
return Err(ErrorKind::NotFound.into());
};
registration.token = token;
registration.interest = interest;
registration.oneshot = matches!(mode, ModeKind::OneShot);
registration.armed = true;
Ok(())
}
pub(crate) fn deregister(&self, fd: RawHandle) -> Result<()> {
let mut state = self.0.lock();
let Some(index) = state.registrations.iter().position(|r| r.fd == fd) else {
return Err(ErrorKind::NotFound.into());
};
state.registrations.remove(index);
Ok(())
}
pub(crate) fn register_signals(
&self,
signals: &crate::sys::process::signal::Signals,
_token: usize,
) -> Result<()> {
match *signals {}
}
pub(crate) fn deregister_signals(
&self,
signals: &crate::sys::process::signal::Signals,
) -> Result<()> {
match *signals {}
}
pub(crate) fn register_child(
&self,
child: &crate::sys::process::Child,
_collected: bool,
_token: usize,
) -> Result<()> {
match *child {}
}
pub(crate) fn deregister_child(&self, child: &crate::sys::process::Child) -> Result<()> {
match *child {}
}
pub(crate) fn timer(&self, token: usize, op: Op) -> Result<()> {
let mut state = self.0.lock();
let now = super::monotonic()?;
state.timers.apply(token, op, now, |_| Ok(()))
}
pub(crate) fn wait(
&self,
events: &mut [RawEvent],
timeout: Option<Duration>,
) -> Result<usize> {
let mut state = self.0.lock();
let deadline = match timeout {
Some(timeout) => {
let nanos = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX);
Some(super::monotonic()?.saturating_add(nanos))
}
None => None,
};
loop {
let count = self.wait_once(&mut state, events, deadline)?;
if count > 0 {
return Ok(count);
}
if let Some(deadline) = deadline
&& super::monotonic()? >= deadline
{
return Ok(0);
}
}
}
fn wait_once(
&self,
state: &mut State,
events: &mut [RawEvent],
deadline: Option<u64>,
) -> Result<usize> {
let mut count = 0;
if state.woken {
state.woken = false;
events[0] = RawEvent {
wake: true,
..RawEvent::EMPTY
};
count = 1;
}
let total = state.registrations.len();
let start = if state.next < total { state.next } else { 0 };
let order = (start..total).chain(0..start);
let armed: Vec<usize> = order
.filter(|&index| state.registrations[index].armed)
.collect();
let mut fds: Vec<PollFd> = armed
.iter()
.map(|&index| {
let registration = &state.registrations[index];
PollFd::new(registration.fd, registration.interest)
})
.collect();
let until = match (deadline, state.timers.next()) {
(Some(deadline), Some(timer)) => Some(deadline.min(timer)),
(deadline, timer) => deadline.or(timer),
};
let timeout = if count > 0 {
Some(Duration::ZERO)
} else {
match until {
Some(until) => Some(Duration::from_nanos(
until.saturating_sub(super::monotonic()?),
)),
None => None,
}
};
if fds.is_empty() && timeout.is_none() {
return Err(ErrorKind::Deadlock.into());
}
if count == events.len() {
return Ok(count);
}
match super::poll(&mut fds, timeout) {
Ok(_) => {}
Err(_) if count > 0 => return Ok(count),
Err(err) => return Err(err),
}
for (fd, &index) in fds.iter().zip(&armed) {
let mut readiness = fd.readiness();
if readiness.is_empty() {
continue;
}
if count == events.len() {
state.next = index;
break;
}
if readiness.contains(Readiness::INVALID) {
readiness = (readiness - Readiness::INVALID) | Readiness::ERROR;
}
let registration = &mut state.registrations[index];
events[count] = RawEvent {
token: registration.token,
readiness,
wake: false,
expirations: 0,
};
count += 1;
if registration.oneshot {
registration.armed = false;
}
}
if state.timers.next().is_some() && count < events.len() {
let now = match super::monotonic() {
Ok(now) => now,
Err(_) if count > 0 => return Ok(count),
Err(err) => return Err(err),
};
let room = &mut events[count..];
count += state
.timers
.expire(now, room.len(), |index, token, expirations| {
room[index] = RawEvent {
token,
expirations,
..RawEvent::EMPTY
};
});
}
Ok(count)
}
pub(crate) fn wake(&self) -> Result<()> {
self.0.lock().woken = true;
Ok(())
}
}
}