Re: [PATCH v4 19/20] rust: time: add arch_timer_get_rate wrapper
From: Deborah Brouwer
Date: Mon Apr 27 2026 - 19:36:35 EST
On Mon, Apr 27, 2026 at 11:59:06AM +0300, Onur Özkan wrote:
> On Fri, 24 Apr 2026 16:39:13 -0700
> Deborah Brouwer <deborah.brouwer@xxxxxxxxxxxxx> wrote:
>
> > Provide a safe Rust wrapper for arch_timer_get_rate().
> >
> > The underlying C helper returns 0 when the ARM architectural timer
> > is not available or not yet initialized. Map this to Option<u32> to
> > make the absence of a valid rate explicit to Rust callers.
> >
> > This allows Rust drivers to query the system timer frequency and
> > select appropriate time sources when programming hardware timeouts.
> >
> > Signed-off-by: Deborah Brouwer <deborah.brouwer@xxxxxxxxxxxxx>
> > ---
> > rust/kernel/time.rs | 29 +++++++++++++++++++++++++++++
> > 1 file changed, 29 insertions(+)
> >
> > diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
> > index 6ea98dfcd027..03ce96450fc8 100644
> > --- a/rust/kernel/time.rs
> > +++ b/rust/kernel/time.rs
> > @@ -359,6 +359,35 @@ fn div(self, rhs: Self) -> Self::Output {
> > }
> > }
> >
> > +/// Returns the ARM architecture timer frequency in Hz, if available.
> > +///
> > +/// This function queries the system-wide ARM architecture timer frequency.
> > +/// The architecture timer provides a consistent time source across all CPU cores.
> > +///
> > +/// Returns `None` if:
> > +/// - The ARM architecture timer is not available (`CONFIG_ARM_ARCH_TIMER` not enabled)
> > +/// - The timer rate is zero (not initialized)
>
> Can we return distinct errors for these cases and return NonZero<u32> when the
> rate is valid?
I don’t think there is an easy way to distinguish between those cases from the C helper,
since both are represented by a return value of 0.
As far as I can see, callers only need to know whether a valid rate is available or not.
I agree that NonZeroU32 would better model the valid case, but I’m not sure it adds
enough benefit here to justify the extra complexity.
>
> > +///
> > +/// # Examples
> > +///
> > +/// ```
> > +/// use kernel::time::arch_timer_get_rate;
> > +///
> > +/// if let Some(rate) = arch_timer_get_rate() {
> > +/// // Use `rate`.
> > +/// }
> > +/// ```
> > +pub fn arch_timer_get_rate() -> Option<u32> {
> > + // SAFETY: The C API is available in all configs; when CONFIG_ARM_ARCH_TIMER
> > + // is disabled, the header provides a stub returning 0.
> > + let rate = unsafe { bindings::arch_timer_get_rate() };
> > + if rate == 0 {
> > + None
> > + } else {
> > + Some(rate)
> > + }
> > +}
> > +
> > impl Delta {
> > /// A span of time equal to zero.
> > pub const ZERO: Self = Self { nanos: 0 };
> >
> > --
> > 2.53.0
> >