Re: [PATCH 6/6] rust: hrtimer: Add HrTimerCallback::expires()
From: Andreas Hindborg
Date: Tue Apr 08 2025 - 08:29:46 EST
"Lyude Paul" <lyude@xxxxxxxxxx> writes:
> This adds the ability to read the expiry time of the current timer from the
> HrTimerCallbackContext.
>
> Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
> ---
> rust/kernel/time/hrtimer.rs | 29 +++++++++++++++++++++++++++--
> 1 file changed, 27 insertions(+), 2 deletions(-)
>
> diff --git a/rust/kernel/time/hrtimer.rs b/rust/kernel/time/hrtimer.rs
> index d52cbb6cfc57f..e28b7895d8f37 100644
> --- a/rust/kernel/time/hrtimer.rs
> +++ b/rust/kernel/time/hrtimer.rs
> @@ -69,7 +69,7 @@
>
> use super::ClockId;
> use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque};
> -use core::{marker::PhantomData, ptr::NonNull};
> +use core::{marker::PhantomData, ptr::{NonNull, addr_of}};
>
> /// A timer backed by a C `struct hrtimer`.
> ///
> @@ -131,7 +131,7 @@ unsafe fn raw_get(this: *const Self) -> *mut bindings::hrtimer {
> // SAFETY: The field projection to `timer` does not go out of bounds,
> // because the caller of this function promises that `this` points to an
> // allocation of at least the size of `Self`.
> - unsafe { Opaque::raw_get(core::ptr::addr_of!((*this).timer)) }
> + unsafe { Opaque::raw_get(addr_of!((*this).timer)) }
> }
>
> /// Cancel an initialized and potentially running timer.
> @@ -163,6 +163,31 @@ pub(crate) unsafe fn raw_cancel(this: *const Self) -> bool {
> // handled on the C side.
> unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
> }
> +
> + /// Return the time expiry for the given timer pointer.
> + ///
> + /// This value should only be used as a snapshot, as the actual expiry time could change after
> + /// this function is called.
> + ///
> + /// # Safety
> + ///
> + /// `self_ptr` must point to a valid `Self`.
> + unsafe fn raw_expires(self_ptr: *const Self) -> Ktime {
> + // SAFETY: self_ptr points to an allocation of at least `HrTimer` size.
> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
> +
> + // SAFETY: There's no actual locking here, a racy read is fine and expected.
> + Ktime::from_raw(unsafe { core::ptr::read(addr_of!((*c_timer_ptr).node.expires)) })
>From what I have picked up about racy reads lately, this should probably
be a `read_once` when we get that. For now you should use
`core::ptr::read_volatile` with a `FIXME(read_volatile)`.
Best regards,
Andreas Hindborg