oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! The timers of a poller: a queue kept in memory, the same on every
//! system, which the backend drives with *one* timer of the system's, armed
//! for the earliest deadline (a `timerfd`, an `EVFILT_TIMER`, a waitable
//! timer; on WASI, the timeout of the wait).
//!
//! That one timer belongs to the kernel, not to a thread that waits: it
//! fires whoever is waiting, and whoever collects it takes what is due out
//! of the queue, with the queue's lock held, and arms the timer for what
//! comes next. So an expiry is reported once, to one thread, and a timer
//! removed is not reported by a wait that looks at the queue afterwards.
//!
//! Times are nanoseconds on the clock `Clock::Monotonic` reads.

use alloc::collections::{BTreeMap, BTreeSet};

use super::{Timer, TimerStart};
use crate::{ErrorKind, Result};

/// A change to the timers of a poller.
#[derive(Clone, Copy)]
pub(crate) enum Op {
    /// A new timer.
    Insert(Timer),
    /// Another schedule for a timer that exists.
    Reset(Timer),
    /// The timer goes.
    Remove,
}

struct Entry {
    /// The deadline, and the place in the order of arming: what the timer
    /// has in the queue. `None` once a one-shot timer has fired.
    armed: Option<(u64, u64)>,
    /// Zero for a one-shot timer.
    interval: u64,
}

pub(crate) struct Timers {
    timers: BTreeMap<usize, Entry>,
    /// The armed timers by deadline, and for one deadline in the order they
    /// were armed: `(deadline, order, token)`.
    queue: BTreeSet<(u64, u64, usize)>,
    order: u64,
}

fn nanos(duration: core::time::Duration) -> u64 {
    // Beyond what 64 bits count (584 years): never.
    u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
}

impl Timers {
    pub(crate) const fn new() -> Self {
        Self {
            timers: BTreeMap::new(),
            queue: BTreeSet::new(),
            order: 0,
        }
    }

    /// The earliest deadline, which is what the system's timer is to be
    /// armed for.
    pub(crate) fn next(&self) -> Option<u64> {
        self.queue.first().map(|&(deadline, _, _)| deadline)
    }

    fn arm(&mut self, token: usize, timer: Timer, now: u64) -> Entry {
        let deadline = match timer.start {
            TimerStart::After(delay) => now.saturating_add(nanos(delay)),
            TimerStart::At(deadline) => nanos(deadline),
        };
        self.order += 1;
        self.queue.insert((deadline, self.order, token));
        Entry {
            armed: Some((deadline, self.order)),
            interval: timer.interval.map_or(0, nanos),
        }
    }

    fn disarm(&mut self, token: usize, entry: &Entry) {
        if let Some((deadline, order)) = entry.armed {
            self.queue.remove(&(deadline, order, token));
        }
    }

    fn change(&mut self, token: usize, op: Op, now: u64) -> Result<()> {
        match op {
            Op::Insert(timer) => {
                if self.timers.contains_key(&token) {
                    return Err(ErrorKind::AlreadyExists.into());
                }
                let entry = self.arm(token, timer, now);
                self.timers.insert(token, entry);
            }
            Op::Reset(timer) => {
                let Some(entry) = self.timers.remove(&token) else {
                    return Err(ErrorKind::NotFound.into());
                };
                self.disarm(token, &entry);
                let entry = self.arm(token, timer, now);
                self.timers.insert(token, entry);
            }
            Op::Remove => {
                let Some(entry) = self.timers.remove(&token) else {
                    return Err(ErrorKind::NotFound.into());
                };
                self.disarm(token, &entry);
            }
        }
        Ok(())
    }

    /// Makes a change, and has the system's timer armed by `arm` (given the
    /// earliest deadline, if there is one) when the change moved the
    /// earliest deadline. Called with the lock of the timers held.
    ///
    /// A timer that could not be armed for is not left in the queue.
    pub(crate) fn apply(
        &mut self,
        token: usize,
        op: Op,
        now: u64,
        arm: impl FnOnce(Option<u64>) -> Result<()>,
    ) -> Result<()> {
        let before = self.next();
        self.change(token, op, now)?;
        let after = self.next();
        if after == before {
            return Ok(());
        }
        let armed = arm(after);
        if armed.is_err() && !matches!(op, Op::Remove) {
            // Nothing would ever report it. (The system's timer is where it
            // was, for the earliest of the others, or earlier: at worst it
            // fires for nothing.)
            let _ = self.change(token, Op::Remove, now);
        }
        armed
    }

    /// Takes the timer that is due first out of the queue, if one is due at
    /// `now`, and returns its token and how many times it expired: more
    /// than once for a periodic timer that was not collected in time, which
    /// is then armed for its next deadline after `now`.
    fn pop(&mut self, now: u64) -> Option<(usize, u64)> {
        let &(deadline, order, token) = self.queue.first()?;
        if deadline > now {
            return None;
        }
        self.queue.remove(&(deadline, order, token));
        let entry = self.timers.get_mut(&token)?;
        if entry.interval == 0 {
            entry.armed = None;
            return Some((token, 1));
        }
        let missed = (now - deadline) / entry.interval;
        let next = missed
            .checked_add(1)
            .and_then(|periods| periods.checked_mul(entry.interval))
            .and_then(|ahead| deadline.checked_add(ahead))
            .unwrap_or(u64::MAX);
        self.order += 1;
        entry.armed = Some((next, self.order));
        self.queue.insert((next, self.order, token));
        Some((token, missed.saturating_add(1)))
    }

    /// Reports the timers due at `now`, earliest first, to `emit` (which is
    /// given the index of the event, the token and the count of
    /// expirations), `room` of them at most, and returns how many that was.
    /// What is due and was not reported stays in the queue: the caller arms
    /// the system's timer for [`next`](Self::next), which then fires at
    /// once.
    pub(crate) fn expire(
        &mut self,
        now: u64,
        room: usize,
        mut emit: impl FnMut(usize, usize, u64),
    ) -> usize {
        let mut count = 0;
        while count < room
            && let Some((token, expirations)) = self.pop(now)
        {
            emit(count, token, expirations);
            count += 1;
        }
        count
    }
}