This patch adds support for intrusive use of the hrtimer system. For now,
only one timer can be embedded in a Rust struct.
The hrtimer Rust API is based on the intrusive style pattern introduced by
the Rust workqueue API.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
kernel/time/Kconfig | 13 ++
rust/kernel/time.rs | 3 +
rust/kernel/time/hrtimer.rs | 347 ++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 363 insertions(+)
diff --git a/kernel/time/Kconfig b/kernel/time/Kconfig
index b0b97a60aaa6..7726e14ca3e2 100644
--- a/kernel/time/Kconfig
+++ b/kernel/time/Kconfig
@@ -211,3 +211,16 @@ config CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
endmenu
endif
+
+config RUST_HRTIMER
+ bool "Enable Rust hrtimer API"
+ depends on RUST
+ default y
+ help
+ This option allows exclusion of the Rust hrtimer API from the build.
+ This allows testing out changes to the C API without having to update
+ the Rust abstractions during initial development.
+
+ Say Y if you wish to build the Rust hrtimer API.
+
+ Say N if you wish to exclude the Rust hrtimer API from the build.
diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index 379c0f5772e5..e928b1340ee3 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -8,6 +8,9 @@
//! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h).
//! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h).
+#[cfg(CONFIG_RUST_HRTIMER)]
+pub mod hrtimer;
+
/// The number of nanoseconds per millisecond.
pub const NSEC_PER_MSEC: i64 = bindings::NSEC_PER_MSEC as i64;
diff --git a/rust/kernel/time/hrtimer.rs b/rust/kernel/time/hrtimer.rs
new file mode 100644
index 000000000000..fe20405d8bfe
--- /dev/null
+++ b/rust/kernel/time/hrtimer.rs
@@ -0,0 +1,347 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Intrusive high resolution timers.
+//!
+//! Allows running timer callbacks without doing allocations at the time of
+//! starting the timer. For now, only one timer per type is allowed.
+//!
+//! # Vocabulary
+//!
+//! States:
+//!
+//! - Stopped: initialized but not started, or cancelled, or not restarted.
+//! - Started: initialized and started or restarted.
+//! - Running: executing the callback.
+//!
+//! Operations:
+//!
+//! * Start
+//! * Cancel
+//! * Restart
+//!
+//! Events:
+//!
+//! * Expire
+//!
+//! ## State Diagram
+//!
+//! ```text
+//! Return NoRestart
+//! +---------------------------------------------------------------------+
+//! | |
+//! | |
+//! | |
+//! | Return Restart |
+//! | +------------------------+ |
+//! | | | |
+//! | | | |
+//! v v | |
+//! +-----------------+ Start +------------------+ +--------+-----+--+
+//! | +---------------->| | | |
+//! Init | | | | Expire | |
+//! --------->| Stopped | | Started +---------->| Running |
+//! | | Cancel | | | |
+//! | |<----------------+ | | |
+//! +-----------------+ +---------------+--+ +-----------------+
+//! ^ |
+//! | |
+//! +---------+
+//! Restart
+//! ```
+//!
+//!
+//! A timer is initialized in the **stopped** state. A stopped timer can be
+//! **started** by the `start` operation, with an **expiry** time. After the
+//! `start` operation, the timer is in the **started** state. When the timer
+//! **expires**, the timer enters the **running** state and the handler is
+//! executed. After the handler has finished executing, the timer may enter the
+//! **started* or **stopped** state, depending on the return value of the
+//! handler. A running timer can be **canceled** by the `cancel` operation. A
+//! timer that is cancelled enters the **stopped** state.
+//!
+//! A `cancel` or `restart` operation on a timer in the **running** state takes
+//! effect after the handler has finished executing and the timer has transitioned
+//! out of the **running** state.
+//!
+//! A `restart` operation on a timer in the **stopped** state is equivalent to a
+//! `start` operation.
+
+use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque};
+use core::marker::PhantomData;
+
+/// A timer backed by a C `struct hrtimer`.
+///
+/// # Invariants
+///
+/// * `self.timer` is initialized by `bindings::hrtimer_setup`.
+#[pin_data]
+#[repr(C)]
+pub struct HrTimer<T> {
+ #[pin]
+ timer: Opaque<bindings::hrtimer>,
+ _t: PhantomData<T>,
+}
+
+// SAFETY: Ownership of an `HrTimer` can be moved to other threads and
+// used/dropped from there.
+unsafe impl<T> Send for HrTimer<T> {}
+
+// SAFETY: Timer operations are locked on C side, so it is safe to operate on a
+// timer from multiple threads
+unsafe impl<T> Sync for HrTimer<T> {}
+
+impl<T> HrTimer<T> {
+ /// Return an initializer for a new timer instance.
+ pub fn new() -> impl PinInit<Self>
+ where
+ T: HrTimerCallback,
+ {
+ pin_init!(Self {
+ // INVARIANTS: We initialize `timer` with `hrtimer_setup` below.
+ timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
+ // SAFETY: By design of `pin_init!`, `place` is a pointer to a
+ // live allocation. hrtimer_setup will initialize `place` and
+ // does not require `place` to be initialized prior to the call.
+ unsafe {
+ bindings::hrtimer_setup(
+ place,
+ Some(T::Pointer::run),
+ bindings::CLOCK_MONOTONIC as i32,
+ bindings::hrtimer_mode_HRTIMER_MODE_REL,
+ );
+ }
+ }),
+ _t: PhantomData,
+ })
+ }
+
+ /// Get a pointer to the contained `bindings::hrtimer`.
+ ///
+ /// This function do not create any references.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must point to a live allocation of at least the size of `Self`.
+ unsafe fn raw_get(ptr: *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 `ptr` points to an
+ // allocation of at least the size of `Self`.
+ unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) }
+ }
+
+ /// Cancel an initialized and potentially running timer.
+ ///
+ /// If the timer handler is running, this will block until the handler is
+ /// finished.
+ ///
+ /// Users of the `HrTimer` API would not usually call this method directly.
+ /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
+ /// returned when the timer was started.
+ ///
+ /// This function does not create any references.
+ ///
+ /// # Safety
+ ///
+ /// `self_ptr` must point to a valid `Self`.
+ #[allow(dead_code)]
+ pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
+ // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
+ let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
+
+ // If the handler is running, this will wait for the handler to finish
+ // before returning.
+ // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
+ // handled on C side.
+ unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
+ }
+}
+
+/// Implemented by pointer types that point to structs that embed a [`HrTimer`].
+///
+/// Target (pointee) must be [`Sync`] because timer callbacks happen in another
+/// thread of execution (hard or soft interrupt context).
+///
+/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
+/// the timer. Note that it is OK to call the start function repeatedly, and
+/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
+/// exist. A timer can be manipulated through any of the handles, and a handle
+/// may represent a cancelled timer.
+pub trait HrTimerPointer: Sync + Sized {
+ /// A handle representing a started or restarted timer.
+ ///
+ /// If the timer is running or if the timer callback is executing when the
+ /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
+ /// until the timer is stopped and the callback has completed.
+ ///
+ /// Note: When implementing this trait, consider that it is not unsafe to
+ /// leak the handle.
+ type TimerHandle: HrTimerHandle;
+
+ /// Start the timer with expiry after `expires` time units. If the timer was
+ /// already running, it is restarted with the new expiry time.
+ fn start(self, expires: Ktime) -> Self::TimerHandle;
+}
+
+/// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
+/// function to call.
+// This is split from `HrTimerPointer` to make it easier to specify trait bounds.
+pub trait RawHrTimerCallback {
+ /// This type is passed to [`HrTimerCallback::run`]. It may be a borrow of
+ /// [`Self::CallbackTarget`], or it may be `Self::CallbackTarget` if the
+ /// implementation can guarantee correct access (exclusive or shared
+ /// depending on the type) to the target during timer handler execution.
+ type CallbackTarget<'a>;
+
+ /// Callback to be called from C when timer fires.
+ ///
+ /// # Safety
+ ///
+ /// Only to be called by C code in `hrtimer` subsystem. `ptr` must point to
+ /// the `bindings::hrtimer` structure that was used to start the timer.
+ unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
+}
+
+/// Implemented by structs that can be the target of a timer callback.
+pub trait HrTimerCallback {
+ /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
+ /// the timer expires.
+ type Pointer<'a>: RawHrTimerCallback;
+
+ /// Called by the timer logic when the timer fires.
+ fn run(this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>)
+ where
+ Self: Sized;
+}
+
+/// A handle representing a potentially running timer.
+///
+/// More than one handle representing the same timer might exist.
+///
+/// # Safety
+///
+/// When dropped, the timer represented by this handle must be cancelled, if it
+/// is running. If the timer handler is running when the handle is dropped, the
+/// drop method must wait for the handler to finish before returning.
+///
+/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
+/// the drop implementation for `Self.`
+pub unsafe trait HrTimerHandle {
+ /// Cancel the timer, if it is running. If the timer handler is running, block
+ /// till the handler has finished.
+ fn cancel(&mut self) -> bool;
+}
+
+/// Implemented by structs that contain timer nodes.
+///
+/// Clients of the timer API would usually safely implement this trait by using
+/// the [`crate::impl_has_hr_timer`] macro.
+///
+/// # Safety
+///
+/// Implementers of this trait must ensure that the implementer has a [`HrTimer`]
+/// field at the offset specified by `OFFSET` and that all trait methods are
+/// implemented according to their documentation.
+///
+/// [`impl_has_timer`]: crate::impl_has_timer
+pub unsafe trait HasHrTimer<T> {
+ /// Offset of the [`HrTimer`] field within `Self`
+ const OFFSET: usize;
+
+ /// Return a pointer to the [`HrTimer`] within `Self`.
+ ///
+ /// This function does not create any references.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must point to a valid struct of type `Self`.
+ unsafe fn raw_get_timer(ptr: *const Self) -> *const HrTimer<T> {
+ // SAFETY: By the safety requirement of this trait, the trait
+ // implementor will have a `HrTimer` field at the specified offset.
+ unsafe { ptr.cast::<u8>().add(Self::OFFSET).cast::<HrTimer<T>>() }
+ }
+
+ /// Return a pointer to the struct that is embedding the [`HrTimer`] pointed
+ /// to by `ptr`.
+ ///
+ /// This function does not create any references.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must point to a [`HrTimer<T>`] field in a struct of type `Self`.
+ unsafe fn timer_container_of(ptr: *mut HrTimer<T>) -> *mut Self
+ where
+ Self: Sized,
+ {
+ // SAFETY: By the safety requirement of this function and the `HasHrTimer`
+ // trait, the following expression will yield a pointer to the `Self`
+ // containing the timer addressed by `ptr`.
+ unsafe { ptr.cast::<u8>().sub(Self::OFFSET).cast::<Self>() }
+ }
+
+ /// Get pointer to embedded `bindings::hrtimer` struct.
+ ///
+ /// This function does not create any references.
+ ///
+ /// # Safety
+ ///
+ /// `self_ptr` must point to a valid `Self`.
+ unsafe fn c_timer_ptr(self_ptr: *const Self) -> *const bindings::hrtimer {
+ // SAFETY: `self_ptr` is a valid pointer to a `Self`.
+ let timer_ptr = unsafe { Self::raw_get_timer(self_ptr) };
+
+ // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
+ unsafe { HrTimer::raw_get(timer_ptr) }
+ }
+
+ /// Start the timer contained in the `Self` pointed to by `self_ptr`. If
+ /// it is already running it is removed and inserted.
+ ///
+ /// # Safety
+ ///
+ /// - `self_ptr` must point to a valid `Self`.
+ /// - Caller must ensure that `self` lives until the timer fires or is
+ /// canceled.
+ unsafe fn start(self_ptr: *const Self, expires: Ktime) {
+ // SAFETY: By function safety requirement, `self_ptr`is a valid `Self`.
+ unsafe {
+ bindings::hrtimer_start_range_ns(
+ Self::c_timer_ptr(self_ptr).cast_mut(),
+ expires.to_ns(),
+ 0,
+ bindings::hrtimer_mode_HRTIMER_MODE_REL,
+ );
+ }
+ }
+}
+
+/// Use to implement the [`HasHrTimer<T>`] trait.
+///
+/// See [`module`] documentation for an example.
+///
+/// [`module`]: crate::time::hrtimer
+#[macro_export]
+macro_rules! impl_has_hr_timer {
+ (
+ impl$({$($generics:tt)*})?
+ HasHrTimer<$timer_type:ty>
+ for $self:ty
+ { self.$field:ident }
+ $($rest:tt)*
+ ) => {
+ // SAFETY: This implementation of `raw_get_timer` only compiles if the
+ // field has the right type.
+ unsafe impl$(<$($generics)*>)? $crate::time::hrtimer::HasHrTimer<$timer_type> for $self {
+ const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize;
+
+ #[inline]
+ unsafe fn raw_get_timer(ptr: *const Self) ->
+ *const $crate::time::hrtimer::HrTimer<$timer_type>
+ {
+ // SAFETY: The caller promises that the pointer is not dangling.
+ unsafe {
+ ::core::ptr::addr_of!((*ptr).$field)
+ }
+ }
+ }
+ }
+}
--
2.47.0
On Mon, Feb 24 2025 at 13:03, Andreas Hindborg wrote:
> This patch adds support for intrusive use of the hrtimer system. For
> now,
git grep 'This patch' Documentation/process/
> only one timer can be embedded in a Rust struct.
>
> +//! ## State Diagram
> +//!
> +//! ```text
> +//! Return NoRestart
> +//! +---------------------------------------------------------------------+
> +//! | |
> +//! | |
> +//! | |
> +//! | Return Restart |
> +//! | +------------------------+ |
> +//! | | | |
> +//! | | | |
> +//! v v | |
> +//! +-----------------+ Start +------------------+ +--------+-----+--+
> +//! | +---------------->| | | |
> +//! Init | | | | Expire | |
> +//! --------->| Stopped | | Started +---------->| Running |
> +//! | | Cancel | | | |
> +//! | |<----------------+ | | |
> +//! +-----------------+ +---------------+--+ +-----------------+
> +//! ^ |
> +//! | |
> +//! +---------+
> +//! Restart
> +//! ```
> +//!
> +//!
> +//! A timer is initialized in the **stopped** state. A stopped timer can be
> +//! **started** by the `start` operation, with an **expiry** time. After the
> +//! `start` operation, the timer is in the **started** state. When the timer
> +//! **expires**, the timer enters the **running** state and the handler is
> +//! executed. After the handler has finished executing, the timer may enter the
> +//! **started* or **stopped** state, depending on the return value of the
> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
> +//! timer that is cancelled enters the **stopped** state.
> +//!
> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
> +//! effect after the handler has finished executing and the timer has transitioned
> +//! out of the **running** state.
> +//!
> +//! A `restart` operation on a timer in the **stopped** state is equivalent to a
> +//! `start` operation.
Nice explanation!
> + /// Cancel an initialized and potentially running timer.
> + ///
> + /// If the timer handler is running, this will block until the handler is
> + /// finished.
> + ///
> + /// Users of the `HrTimer` API would not usually call this method directly.
> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
> + /// returned when the timer was started.
> + ///
> + /// This function does not create any references.
> + ///
> + /// # Safety
> + ///
> + /// `self_ptr` must point to a valid `Self`.
> + #[allow(dead_code)]
> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
> +
> + // If the handler is running, this will wait for the handler to finish
> + // before returning.
> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
> + // handled on C side.
You might want to be more explicit about the provided synchronization.
The hrtimer core only guarantees that operations on the hrtimer object
are strictly serialized. But it does not provide any guarantee about
external concurrency. The following case cannot be handled by the core:
T0 T1
cancel() start()
lock()
.... lock() <- contended
dequeue()
unlock()
enqueue()
unlock()
So there is no guarantee for T0 that the timer is actually canceled in
this case. The hrtimer core can do nothing about this, that's a problem
of the call sites.
We've implemented timer_shutdown() for the timer wheel timers, which
prevents that the timer can be started after shutdown() succeeds. It
might be a good thing to implement this for hrtimers as well.
Thanks,
tglx
"Thomas Gleixner" <tglx@linutronix.de> writes:
> On Mon, Feb 24 2025 at 13:03, Andreas Hindborg wrote:
>> This patch adds support for intrusive use of the hrtimer system. For
>> now,
>
> git grep 'This patch' Documentation/process/
I was made aware and have change the mood to imperative for next spin.
>
>> only one timer can be embedded in a Rust struct.
>>
>> +//! ## State Diagram
>> +//!
>> +//! ```text
>> +//! Return NoRestart
>> +//! +---------------------------------------------------------------------+
>> +//! | |
>> +//! | |
>> +//! | |
>> +//! | Return Restart |
>> +//! | +------------------------+ |
>> +//! | | | |
>> +//! | | | |
>> +//! v v | |
>> +//! +-----------------+ Start +------------------+ +--------+-----+--+
>> +//! | +---------------->| | | |
>> +//! Init | | | | Expire | |
>> +//! --------->| Stopped | | Started +---------->| Running |
>> +//! | | Cancel | | | |
>> +//! | |<----------------+ | | |
>> +//! +-----------------+ +---------------+--+ +-----------------+
>> +//! ^ |
>> +//! | |
>> +//! +---------+
>> +//! Restart
>> +//! ```
>> +//!
>> +//!
>> +//! A timer is initialized in the **stopped** state. A stopped timer can be
>> +//! **started** by the `start` operation, with an **expiry** time. After the
>> +//! `start` operation, the timer is in the **started** state. When the timer
>> +//! **expires**, the timer enters the **running** state and the handler is
>> +//! executed. After the handler has finished executing, the timer may enter the
>> +//! **started* or **stopped** state, depending on the return value of the
>> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
>> +//! timer that is cancelled enters the **stopped** state.
>> +//!
>> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
>> +//! effect after the handler has finished executing and the timer has transitioned
>> +//! out of the **running** state.
>> +//!
>> +//! A `restart` operation on a timer in the **stopped** state is equivalent to a
>> +//! `start` operation.
>
> Nice explanation!
Thanks.
>
>> + /// Cancel an initialized and potentially running timer.
>> + ///
>> + /// If the timer handler is running, this will block until the handler is
>> + /// finished.
>> + ///
>> + /// Users of the `HrTimer` API would not usually call this method directly.
>> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
>> + /// returned when the timer was started.
>> + ///
>> + /// This function does not create any references.
>> + ///
>> + /// # Safety
>> + ///
>> + /// `self_ptr` must point to a valid `Self`.
>> + #[allow(dead_code)]
>> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
>> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
>> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
>> +
>> + // If the handler is running, this will wait for the handler to finish
>> + // before returning.
>> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
>> + // handled on C side.
>
> You might want to be more explicit about the provided synchronization.
> The hrtimer core only guarantees that operations on the hrtimer object
> are strictly serialized. But it does not provide any guarantee about
> external concurrency. The following case cannot be handled by the core:
>
> T0 T1
> cancel() start()
> lock()
> .... lock() <- contended
> dequeue()
> unlock()
> enqueue()
> unlock()
>
> So there is no guarantee for T0 that the timer is actually canceled in
> this case. The hrtimer core can do nothing about this, that's a problem
> of the call sites.
Right, this was also my understanding. I can add a note about this race.
> We've implemented timer_shutdown() for the timer wheel timers, which
> prevents that the timer can be started after shutdown() succeeds. It
> might be a good thing to implement this for hrtimers as well.
Sounds like that would be useful.
Best regards,
Andreas Hindborg
… > This patch adds support for … See also: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/process/submitting-patches.rst?h=v6.14-rc4#n94 Regards, Markus
"Markus Elfring" <Markus.Elfring@web.de> writes: > … >> This patch adds support for … > > See also: > https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/process/submitting-patches.rst?h=v6.14-rc4#n94 Thanks for pointing this out, I'll change the wording for next spin. Best regards, Andreas Hindborg
Hi Andreas, mostly grammar and prose clarity comments below.
I still think HasHrTimer::OFFSET is less clear and more fragile than
just generating compiler-checked implementations in the macro (you're
already generating OFFSET and one method implementation rather than
generating 2 method implementations).
On Mon, Feb 24, 2025 at 7:06 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>
> This patch adds support for intrusive use of the hrtimer system. For now,
> only one timer can be embedded in a Rust struct.
>
> The hrtimer Rust API is based on the intrusive style pattern introduced by
> the Rust workqueue API.
>
> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
> ---
> kernel/time/Kconfig | 13 ++
> rust/kernel/time.rs | 3 +
> rust/kernel/time/hrtimer.rs | 347 ++++++++++++++++++++++++++++++++++++++++++++
> 3 files changed, 363 insertions(+)
>
> diff --git a/kernel/time/Kconfig b/kernel/time/Kconfig
> index b0b97a60aaa6..7726e14ca3e2 100644
> --- a/kernel/time/Kconfig
> +++ b/kernel/time/Kconfig
> @@ -211,3 +211,16 @@ config CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
>
> endmenu
> endif
> +
> +config RUST_HRTIMER
> + bool "Enable Rust hrtimer API"
> + depends on RUST
> + default y
> + help
> + This option allows exclusion of the Rust hrtimer API from the build.
> + This allows testing out changes to the C API without having to update
> + the Rust abstractions during initial development.
> +
> + Say Y if you wish to build the Rust hrtimer API.
> +
> + Say N if you wish to exclude the Rust hrtimer API from the build.
> diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
> index 379c0f5772e5..e928b1340ee3 100644
> --- a/rust/kernel/time.rs
> +++ b/rust/kernel/time.rs
> @@ -8,6 +8,9 @@
> //! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h).
> //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h).
>
> +#[cfg(CONFIG_RUST_HRTIMER)]
> +pub mod hrtimer;
> +
> /// The number of nanoseconds per millisecond.
> pub const NSEC_PER_MSEC: i64 = bindings::NSEC_PER_MSEC as i64;
>
> diff --git a/rust/kernel/time/hrtimer.rs b/rust/kernel/time/hrtimer.rs
> new file mode 100644
> index 000000000000..fe20405d8bfe
> --- /dev/null
> +++ b/rust/kernel/time/hrtimer.rs
> @@ -0,0 +1,347 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! Intrusive high resolution timers.
> +//!
> +//! Allows running timer callbacks without doing allocations at the time of
> +//! starting the timer. For now, only one timer per type is allowed.
> +//!
> +//! # Vocabulary
> +//!
> +//! States:
> +//!
> +//! - Stopped: initialized but not started, or cancelled, or not restarted.
> +//! - Started: initialized and started or restarted.
> +//! - Running: executing the callback.
> +//!
> +//! Operations:
> +//!
> +//! * Start
> +//! * Cancel
> +//! * Restart
> +//!
> +//! Events:
> +//!
> +//! * Expire
> +//!
> +//! ## State Diagram
> +//!
> +//! ```text
> +//! Return NoRestart
> +//! +---------------------------------------------------------------------+
> +//! | |
> +//! | |
> +//! | |
> +//! | Return Restart |
> +//! | +------------------------+ |
> +//! | | | |
> +//! | | | |
> +//! v v | |
> +//! +-----------------+ Start +------------------+ +--------+-----+--+
> +//! | +---------------->| | | |
> +//! Init | | | | Expire | |
> +//! --------->| Stopped | | Started +---------->| Running |
> +//! | | Cancel | | | |
> +//! | |<----------------+ | | |
> +//! +-----------------+ +---------------+--+ +-----------------+
> +//! ^ |
> +//! | |
> +//! +---------+
> +//! Restart
> +//! ```
> +//!
> +//!
> +//! A timer is initialized in the **stopped** state. A stopped timer can be
> +//! **started** by the `start` operation, with an **expiry** time. After the
> +//! `start` operation, the timer is in the **started** state. When the timer
> +//! **expires**, the timer enters the **running** state and the handler is
> +//! executed. After the handler has finished executing, the timer may enter the
> +//! **started* or **stopped** state, depending on the return value of the
> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
> +//! timer that is cancelled enters the **stopped** state.
This is a bit confusing because it sounds like you're describing a
*started* timer. After reading the next paragraph I think this wording
applies to both *started* and *running*, but it isn't unambiguous.
> +//!
> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
> +//! effect after the handler has finished executing and the timer has transitioned
> +//! out of the **running** state.
There's no external restart, right? I think this wording is confused
by the unification of cancel and restart under operations, though they
are not isomorphic. Restart (as I understand it) can only happen from
the handler, and cancel can only happen via a call to hrtimer_cancel.
It's also a bit strange that start isn't mentioned whenever cancel and
restart are mentioned.
> +//!
> +//! A `restart` operation on a timer in the **stopped** state is equivalent to a
> +//! `start` operation.
> +
> +use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque};
> +use core::marker::PhantomData;
> +
> +/// A timer backed by a C `struct hrtimer`.
> +///
> +/// # Invariants
> +///
> +/// * `self.timer` is initialized by `bindings::hrtimer_setup`.
> +#[pin_data]
> +#[repr(C)]
> +pub struct HrTimer<T> {
> + #[pin]
> + timer: Opaque<bindings::hrtimer>,
> + _t: PhantomData<T>,
> +}
> +
> +// SAFETY: Ownership of an `HrTimer` can be moved to other threads and
> +// used/dropped from there.
> +unsafe impl<T> Send for HrTimer<T> {}
> +
> +// SAFETY: Timer operations are locked on C side, so it is safe to operate on a
> +// timer from multiple threads
nit: missing article ("the" C side) and missing period.
> +unsafe impl<T> Sync for HrTimer<T> {}
> +
> +impl<T> HrTimer<T> {
> + /// Return an initializer for a new timer instance.
> + pub fn new() -> impl PinInit<Self>
> + where
> + T: HrTimerCallback,
> + {
> + pin_init!(Self {
> + // INVARIANTS: We initialize `timer` with `hrtimer_setup` below.
Why plural INVARIANTS?
> + timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
> + // SAFETY: By design of `pin_init!`, `place` is a pointer to a
> + // live allocation. hrtimer_setup will initialize `place` and
> + // does not require `place` to be initialized prior to the call.
> + unsafe {
> + bindings::hrtimer_setup(
> + place,
> + Some(T::Pointer::run),
> + bindings::CLOCK_MONOTONIC as i32,
> + bindings::hrtimer_mode_HRTIMER_MODE_REL,
> + );
> + }
> + }),
> + _t: PhantomData,
> + })
> + }
> +
> + /// Get a pointer to the contained `bindings::hrtimer`.
> + ///
> + /// This function do not create any references.
s/do/does/
But maybe this should use the same wording from Opaque::raw_get?
/// This function is useful to get access to the value without
creating intermediate
/// references.
If so, consider also naming the argument "this" for consistency. Same
for other methods below.
> + ///
> + /// # Safety
> + ///
> + /// `ptr` must point to a live allocation of at least the size of `Self`.
> + unsafe fn raw_get(ptr: *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 `ptr` points to an
> + // allocation of at least the size of `Self`.
> + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) }
> + }
> +
> + /// Cancel an initialized and potentially running timer.
> + ///
> + /// If the timer handler is running, this will block until the handler is
> + /// finished.
nit: s/is finished/returns/ and maybe clarify the ordering, namely
that the timer is definitely in a stopped state after this returns.
> + ///
> + /// Users of the `HrTimer` API would not usually call this method directly.
> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
> + /// returned when the timer was started.
> + ///
> + /// This function does not create any references.
> + ///
> + /// # Safety
> + ///
> + /// `self_ptr` must point to a valid `Self`.
Why use different phrasing here than on raw_get? The parameter name is
also different. Would be nice to be consistent.
> + #[allow(dead_code)]
> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
> +
> + // If the handler is running, this will wait for the handler to finish
> + // before returning.
> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
> + // handled on C side.
missing article here.
> + unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
> + }
> +}
> +
> +/// Implemented by pointer types that point to structs that embed a [`HrTimer`].
> +///
> +/// Target (pointee) must be [`Sync`] because timer callbacks happen in another
> +/// thread of execution (hard or soft interrupt context).
Is this explaining the bound on the trait, or something that exists
outside the type system? If it's the former, isn't the Sync bound on
the trait going to apply to the pointer rather than the pointee?
> +///
> +/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
> +/// the timer. Note that it is OK to call the start function repeatedly, and
> +/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
> +/// exist. A timer can be manipulated through any of the handles, and a handle
> +/// may represent a cancelled timer.
> +pub trait HrTimerPointer: Sync + Sized {
> + /// A handle representing a started or restarted timer.
> + ///
> + /// If the timer is running or if the timer callback is executing when the
> + /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
> + /// until the timer is stopped and the callback has completed.
> + ///
> + /// Note: When implementing this trait, consider that it is not unsafe to
> + /// leak the handle.
What does leak mean in this context?
> + type TimerHandle: HrTimerHandle;
> +
> + /// Start the timer with expiry after `expires` time units. If the timer was
> + /// already running, it is restarted with the new expiry time.
> + fn start(self, expires: Ktime) -> Self::TimerHandle;
> +}
> +
> +/// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
> +/// function to call.
> +// This is split from `HrTimerPointer` to make it easier to specify trait bounds.
> +pub trait RawHrTimerCallback {
> + /// This type is passed to [`HrTimerCallback::run`]. It may be a borrow of
> + /// [`Self::CallbackTarget`], or it may be `Self::CallbackTarget` if the
> + /// implementation can guarantee correct access (exclusive or shared
> + /// depending on the type) to the target during timer handler execution.
> + type CallbackTarget<'a>;
> +
> + /// Callback to be called from C when timer fires.
> + ///
> + /// # Safety
> + ///
> + /// Only to be called by C code in `hrtimer` subsystem. `ptr` must point to
missing article, should be "...in the `hrtimer`..."
> + /// the `bindings::hrtimer` structure that was used to start the timer.
> + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
> +}
> +
> +/// Implemented by structs that can be the target of a timer callback.
> +pub trait HrTimerCallback {
> + /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
> + /// the timer expires.
> + type Pointer<'a>: RawHrTimerCallback;
> +
> + /// Called by the timer logic when the timer fires.
> + fn run(this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>)
> + where
> + Self: Sized;
> +}
> +
> +/// A handle representing a potentially running timer.
> +///
> +/// More than one handle representing the same timer might exist.
> +///
> +/// # Safety
> +///
> +/// When dropped, the timer represented by this handle must be cancelled, if it
> +/// is running. If the timer handler is running when the handle is dropped, the
> +/// drop method must wait for the handler to finish before returning.
> +///
> +/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
> +/// the drop implementation for `Self.`
> +pub unsafe trait HrTimerHandle {
> + /// Cancel the timer, if it is running. If the timer handler is running, block
> + /// till the handler has finished.
Here's another case where "running" is confusingly used to refer to
the timer being in the state before the handler has begun to execute,
and also to the state after the handler has begun to execute.
> + fn cancel(&mut self) -> bool;
> +}
> +
> +/// Implemented by structs that contain timer nodes.
> +///
> +/// Clients of the timer API would usually safely implement this trait by using
> +/// the [`crate::impl_has_hr_timer`] macro.
> +///
> +/// # Safety
> +///
> +/// Implementers of this trait must ensure that the implementer has a [`HrTimer`]
> +/// field at the offset specified by `OFFSET` and that all trait methods are
> +/// implemented according to their documentation.
> +///
> +/// [`impl_has_timer`]: crate::impl_has_timer
> +pub unsafe trait HasHrTimer<T> {
> + /// Offset of the [`HrTimer`] field within `Self`
> + const OFFSET: usize;
> +
> + /// Return a pointer to the [`HrTimer`] within `Self`.
> + ///
> + /// This function does not create any references.
> + ///
> + /// # Safety
> + ///
> + /// `ptr` must point to a valid struct of type `Self`.
> + unsafe fn raw_get_timer(ptr: *const Self) -> *const HrTimer<T> {
> + // SAFETY: By the safety requirement of this trait, the trait
> + // implementor will have a `HrTimer` field at the specified offset.
> + unsafe { ptr.cast::<u8>().add(Self::OFFSET).cast::<HrTimer<T>>() }
> + }
> +
> + /// Return a pointer to the struct that is embedding the [`HrTimer`] pointed
> + /// to by `ptr`.
> + ///
> + /// This function does not create any references.
> + ///
> + /// # Safety
> + ///
> + /// `ptr` must point to a [`HrTimer<T>`] field in a struct of type `Self`.
> + unsafe fn timer_container_of(ptr: *mut HrTimer<T>) -> *mut Self
> + where
> + Self: Sized,
> + {
> + // SAFETY: By the safety requirement of this function and the `HasHrTimer`
> + // trait, the following expression will yield a pointer to the `Self`
> + // containing the timer addressed by `ptr`.
> + unsafe { ptr.cast::<u8>().sub(Self::OFFSET).cast::<Self>() }
> + }
> +
> + /// Get pointer to embedded `bindings::hrtimer` struct.
> + ///
> + /// This function does not create any references.
> + ///
> + /// # Safety
> + ///
> + /// `self_ptr` must point to a valid `Self`.
> + unsafe fn c_timer_ptr(self_ptr: *const Self) -> *const bindings::hrtimer {
> + // SAFETY: `self_ptr` is a valid pointer to a `Self`.
> + let timer_ptr = unsafe { Self::raw_get_timer(self_ptr) };
> +
> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
> + unsafe { HrTimer::raw_get(timer_ptr) }
> + }
> +
> + /// Start the timer contained in the `Self` pointed to by `self_ptr`. If
> + /// it is already running it is removed and inserted.
> + ///
> + /// # Safety
> + ///
> + /// - `self_ptr` must point to a valid `Self`.
> + /// - Caller must ensure that `self` lives until the timer fires or is
> + /// canceled.
> + unsafe fn start(self_ptr: *const Self, expires: Ktime) {
> + // SAFETY: By function safety requirement, `self_ptr`is a valid `Self`.
> + unsafe {
> + bindings::hrtimer_start_range_ns(
> + Self::c_timer_ptr(self_ptr).cast_mut(),
> + expires.to_ns(),
> + 0,
> + bindings::hrtimer_mode_HRTIMER_MODE_REL,
> + );
> + }
> + }
> +}
> +
> +/// Use to implement the [`HasHrTimer<T>`] trait.
> +///
> +/// See [`module`] documentation for an example.
> +///
> +/// [`module`]: crate::time::hrtimer
> +#[macro_export]
> +macro_rules! impl_has_hr_timer {
> + (
> + impl$({$($generics:tt)*})?
> + HasHrTimer<$timer_type:ty>
> + for $self:ty
> + { self.$field:ident }
> + $($rest:tt)*
> + ) => {
> + // SAFETY: This implementation of `raw_get_timer` only compiles if the
> + // field has the right type.
> + unsafe impl$(<$($generics)*>)? $crate::time::hrtimer::HasHrTimer<$timer_type> for $self {
> + const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize;
> +
> + #[inline]
> + unsafe fn raw_get_timer(ptr: *const Self) ->
> + *const $crate::time::hrtimer::HrTimer<$timer_type>
> + {
> + // SAFETY: The caller promises that the pointer is not dangling.
> + unsafe {
> + ::core::ptr::addr_of!((*ptr).$field)
> + }
> + }
> + }
> + }
> +}
>
> --
> 2.47.0
>
>
Cheers.
Tamir
"Tamir Duberstein" <tamird@gmail.com> writes:
> Hi Andreas, mostly grammar and prose clarity comments below.
>
> I still think HasHrTimer::OFFSET is less clear and more fragile than
> just generating compiler-checked implementations in the macro (you're
> already generating OFFSET and one method implementation rather than
> generating 2 method implementations).
I don't agree with you assessment. My argument is that I would rather
generate as little code as possible in the macro, and the trait would in
practice never be implemented by hand.
>
> On Mon, Feb 24, 2025 at 7:06 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>>
[...]
>> +//! # Vocabulary
>> +//!
>> +//! States:
>> +//!
>> +//! - Stopped: initialized but not started, or cancelled, or not restarted.
>> +//! - Started: initialized and started or restarted.
>> +//! - Running: executing the callback.
>> +//!
>> +//! Operations:
>> +//!
>> +//! * Start
>> +//! * Cancel
>> +//! * Restart
>> +//!
>> +//! Events:
>> +//!
>> +//! * Expire
>> +//!
>> +//! ## State Diagram
>> +//!
>> +//! ```text
>> +//! Return NoRestart
>> +//! +---------------------------------------------------------------------+
>> +//! | |
>> +//! | |
>> +//! | |
>> +//! | Return Restart |
>> +//! | +------------------------+ |
>> +//! | | | |
>> +//! | | | |
>> +//! v v | |
>> +//! +-----------------+ Start +------------------+ +--------+-----+--+
>> +//! | +---------------->| | | |
>> +//! Init | | | | Expire | |
>> +//! --------->| Stopped | | Started +---------->| Running |
>> +//! | | Cancel | | | |
>> +//! | |<----------------+ | | |
>> +//! +-----------------+ +---------------+--+ +-----------------+
>> +//! ^ |
>> +//! | |
>> +//! +---------+
>> +//! Restart
>> +//! ```
>> +//!
>> +//!
>> +//! A timer is initialized in the **stopped** state. A stopped timer can be
>> +//! **started** by the `start` operation, with an **expiry** time. After the
>> +//! `start` operation, the timer is in the **started** state. When the timer
>> +//! **expires**, the timer enters the **running** state and the handler is
>> +//! executed. After the handler has finished executing, the timer may enter the
>> +//! **started* or **stopped** state, depending on the return value of the
>> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
>> +//! timer that is cancelled enters the **stopped** state.
>
> This is a bit confusing because it sounds like you're describing a
> *started* timer. After reading the next paragraph I think this wording
> applies to both *started* and *running*, but it isn't unambiguous.
Right, I think I understand. It's a mistake. Last sentence should be:
A timer in the **started** or **running** state be **canceled** by the
`cancel` operation. A timer that is cancelled enters the **stopped**
state.
>
>> +//!
>> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
>> +//! effect after the handler has finished executing and the timer has transitioned
>> +//! out of the **running** state.
>
> There's no external restart, right?
There will be, eventually. Conceptually there is, because the state
diagram and this text describe the operation.
> I think this wording is confused
> by the unification of cancel and restart under operations, though they
> are not isomorphic.
Hmm, I am not following. Can you elaborate? The set of operations is
start, cancel, restart.
> Restart (as I understand it) can only happen from
> the handler, and cancel can only happen via a call to hrtimer_cancel.
This text introduces the restart operation. There is no code path to
reach it from rust at the moment, but I am inclined to add the function
due to this confusion. It would be dead code for now though.
> It's also a bit strange that start isn't mentioned whenever cancel and
> restart are mentioned.
Why is that?
>
>> +//!
>> +//! A `restart` operation on a timer in the **stopped** state is equivalent to a
>> +//! `start` operation.
>> +
>> +use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque};
>> +use core::marker::PhantomData;
>> +
>> +/// A timer backed by a C `struct hrtimer`.
>> +///
>> +/// # Invariants
>> +///
>> +/// * `self.timer` is initialized by `bindings::hrtimer_setup`.
>> +#[pin_data]
>> +#[repr(C)]
>> +pub struct HrTimer<T> {
>> + #[pin]
>> + timer: Opaque<bindings::hrtimer>,
>> + _t: PhantomData<T>,
>> +}
>> +
>> +// SAFETY: Ownership of an `HrTimer` can be moved to other threads and
>> +// used/dropped from there.
>> +unsafe impl<T> Send for HrTimer<T> {}
>> +
>> +// SAFETY: Timer operations are locked on C side, so it is safe to operate on a
>> +// timer from multiple threads
>
> nit: missing article ("the" C side) and missing period.
Thanks.
>
>> +unsafe impl<T> Sync for HrTimer<T> {}
>> +
>> +impl<T> HrTimer<T> {
>> + /// Return an initializer for a new timer instance.
>> + pub fn new() -> impl PinInit<Self>
>> + where
>> + T: HrTimerCallback,
>> + {
>> + pin_init!(Self {
>> + // INVARIANTS: We initialize `timer` with `hrtimer_setup` below.
>
> Why plural INVARIANTS?
Mistake, will fix.
>
>> + timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
>> + // SAFETY: By design of `pin_init!`, `place` is a pointer to a
>> + // live allocation. hrtimer_setup will initialize `place` and
>> + // does not require `place` to be initialized prior to the call.
>> + unsafe {
>> + bindings::hrtimer_setup(
>> + place,
>> + Some(T::Pointer::run),
>> + bindings::CLOCK_MONOTONIC as i32,
>> + bindings::hrtimer_mode_HRTIMER_MODE_REL,
>> + );
>> + }
>> + }),
>> + _t: PhantomData,
>> + })
>> + }
>> +
>> + /// Get a pointer to the contained `bindings::hrtimer`.
>> + ///
>> + /// This function do not create any references.
>
> s/do/does/
Thanks.
>
> But maybe this should use the same wording from Opaque::raw_get?
>
> /// This function is useful to get access to the value without
> creating intermediate
> /// references.
To me those two wordings have the same effect. I don't mind changing the
wording if you feel strongly about it.
>
> If so, consider also naming the argument "this" for consistency. Same
> for other methods below.
Sure.
>
>> + ///
>> + /// # Safety
>> + ///
>> + /// `ptr` must point to a live allocation of at least the size of `Self`.
>> + unsafe fn raw_get(ptr: *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 `ptr` points to an
>> + // allocation of at least the size of `Self`.
>> + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) }
>> + }
>> +
>> + /// Cancel an initialized and potentially running timer.
>> + ///
>> + /// If the timer handler is running, this will block until the handler is
>> + /// finished.
>
> nit: s/is finished/returns/ and maybe clarify the ordering, namely
> that the timer is definitely in a stopped state after this returns.
/// If the timer handler is running, this function will block until the
/// handler returns. Before this function returns, the timer will be in the
/// stopped state.
If we have a concurrent call to start, the timer might actually be in
the started state when this function returns. But this function will
transition the timer to the stopped state.
>
>> + ///
>> + /// Users of the `HrTimer` API would not usually call this method directly.
>> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
>> + /// returned when the timer was started.
>> + ///
>> + /// This function does not create any references.
>> + ///
>> + /// # Safety
>> + ///
>> + /// `self_ptr` must point to a valid `Self`.
>
> Why use different phrasing here than on raw_get? The parameter name is
> also different. Would be nice to be consistent.
They are different requirements, one is stronger than the other. I
construct safety requirements based on the unsafe operations in the
function. The unsafe operations in these two functions have different
requirements. I would not impose a stronger requirement than I have to.
>
>> + #[allow(dead_code)]
>> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
>> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
>> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
>> +
>> + // If the handler is running, this will wait for the handler to finish
>> + // before returning.
>> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
>> + // handled on C side.
>
> missing article here.
👍
>
>> + unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
>> + }
>> +}
>> +
>> +/// Implemented by pointer types that point to structs that embed a [`HrTimer`].
>> +///
>> +/// Target (pointee) must be [`Sync`] because timer callbacks happen in another
>> +/// thread of execution (hard or soft interrupt context).
>
> Is this explaining the bound on the trait, or something that exists
> outside the type system? If it's the former, isn't the Sync bound on
> the trait going to apply to the pointer rather than the pointee?
It is explaining the bound on the trait, and as you say it is not
correct. Pointer types that do not apply synchronization internally can
only be `Sync` when their target is `Sync`, which was probably my line
of thought.
I will rephrase:
`Self` must be [`Sync`] because timer callbacks happen in another
thread of execution (hard or soft interrupt context).
>
>> +///
>> +/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
>> +/// the timer. Note that it is OK to call the start function repeatedly, and
>> +/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
>> +/// exist. A timer can be manipulated through any of the handles, and a handle
>> +/// may represent a cancelled timer.
>> +pub trait HrTimerPointer: Sync + Sized {
>> + /// A handle representing a started or restarted timer.
>> + ///
>> + /// If the timer is running or if the timer callback is executing when the
>> + /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
>> + /// until the timer is stopped and the callback has completed.
>> + ///
>> + /// Note: When implementing this trait, consider that it is not unsafe to
>> + /// leak the handle.
>
> What does leak mean in this context?
The same as in all other contexts (I think?). Leave the object alive for
'static and forget the address. Thus never drop it and thus never run
the drop method.
>
>> + type TimerHandle: HrTimerHandle;
>> +
>> + /// Start the timer with expiry after `expires` time units. If the timer was
>> + /// already running, it is restarted with the new expiry time.
>> + fn start(self, expires: Ktime) -> Self::TimerHandle;
>> +}
>> +
>> +/// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
>> +/// function to call.
>> +// This is split from `HrTimerPointer` to make it easier to specify trait bounds.
>> +pub trait RawHrTimerCallback {
>> + /// This type is passed to [`HrTimerCallback::run`]. It may be a borrow of
>> + /// [`Self::CallbackTarget`], or it may be `Self::CallbackTarget` if the
>> + /// implementation can guarantee correct access (exclusive or shared
>> + /// depending on the type) to the target during timer handler execution.
>> + type CallbackTarget<'a>;
>> +
>> + /// Callback to be called from C when timer fires.
>> + ///
>> + /// # Safety
>> + ///
>> + /// Only to be called by C code in `hrtimer` subsystem. `ptr` must point to
>
> missing article, should be "...in the `hrtimer`..."
English is difficult 😅
>
>> + /// the `bindings::hrtimer` structure that was used to start the timer.
>> + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
>> +}
>> +
>> +/// Implemented by structs that can be the target of a timer callback.
>> +pub trait HrTimerCallback {
>> + /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
>> + /// the timer expires.
>> + type Pointer<'a>: RawHrTimerCallback;
>> +
>> + /// Called by the timer logic when the timer fires.
>> + fn run(this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>)
>> + where
>> + Self: Sized;
>> +}
>> +
>> +/// A handle representing a potentially running timer.
>> +///
>> +/// More than one handle representing the same timer might exist.
>> +///
>> +/// # Safety
>> +///
>> +/// When dropped, the timer represented by this handle must be cancelled, if it
>> +/// is running. If the timer handler is running when the handle is dropped, the
>> +/// drop method must wait for the handler to finish before returning.
>> +///
>> +/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
>> +/// the drop implementation for `Self.`
>> +pub unsafe trait HrTimerHandle {
>> + /// Cancel the timer, if it is running. If the timer handler is running, block
>> + /// till the handler has finished.
>
> Here's another case where "running" is confusingly used to refer to
> the timer being in the state before the handler has begun to execute,
> and also to the state after the handler has begun to execute.
Thanks for catching this. How is this:
/// Cancel the timer, if it is in the started or running state. If the timer
/// is in the running state, block till the handler has finished executing.
Thanks for the comments!
Best regards,
Andreas Hindborg
On Tue, Feb 25, 2025 at 3:52 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>
> "Tamir Duberstein" <tamird@gmail.com> writes:
>
> > Hi Andreas, mostly grammar and prose clarity comments below.
> >
> > I still think HasHrTimer::OFFSET is less clear and more fragile than
> > just generating compiler-checked implementations in the macro (you're
> > already generating OFFSET and one method implementation rather than
> > generating 2 method implementations).
>
> I don't agree with you assessment. My argument is that I would rather
> generate as little code as possible in the macro, and the trait would in
> practice never be implemented by hand.
In the current patch, the trait:
- provides raw_get_timer
- provides timer_container_of
and the macro:
- defines OFFSET
- defines raw_get_timer
The justification for the redundancy is that without defining
raw_get_timer in the macro the user might invoke the macro
incorrectly. But why is that better than defining both methods in the
macro? Either way the macro provides 2 items. The key benefit of
defining both methods in the macro is that there's no dead-code
implementation of raw_get_pointer in the trait. It also reduces the
surface of the trait, which is always a benefit due to Hyrum's law.
>
> >
> > On Mon, Feb 24, 2025 at 7:06 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
> >>
>
> [...]
>
> >> +//! # Vocabulary
> >> +//!
> >> +//! States:
> >> +//!
> >> +//! - Stopped: initialized but not started, or cancelled, or not restarted.
> >> +//! - Started: initialized and started or restarted.
> >> +//! - Running: executing the callback.
> >> +//!
> >> +//! Operations:
> >> +//!
> >> +//! * Start
> >> +//! * Cancel
> >> +//! * Restart
> >> +//!
> >> +//! Events:
> >> +//!
> >> +//! * Expire
> >> +//!
> >> +//! ## State Diagram
> >> +//!
> >> +//! ```text
> >> +//! Return NoRestart
> >> +//! +---------------------------------------------------------------------+
> >> +//! | |
> >> +//! | |
> >> +//! | |
> >> +//! | Return Restart |
> >> +//! | +------------------------+ |
> >> +//! | | | |
> >> +//! | | | |
> >> +//! v v | |
> >> +//! +-----------------+ Start +------------------+ +--------+-----+--+
> >> +//! | +---------------->| | | |
> >> +//! Init | | | | Expire | |
> >> +//! --------->| Stopped | | Started +---------->| Running |
> >> +//! | | Cancel | | | |
> >> +//! | |<----------------+ | | |
> >> +//! +-----------------+ +---------------+--+ +-----------------+
> >> +//! ^ |
> >> +//! | |
> >> +//! +---------+
> >> +//! Restart
> >> +//! ```
> >> +//!
> >> +//!
> >> +//! A timer is initialized in the **stopped** state. A stopped timer can be
> >> +//! **started** by the `start` operation, with an **expiry** time. After the
> >> +//! `start` operation, the timer is in the **started** state. When the timer
> >> +//! **expires**, the timer enters the **running** state and the handler is
> >> +//! executed. After the handler has finished executing, the timer may enter the
> >> +//! **started* or **stopped** state, depending on the return value of the
> >> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
> >> +//! timer that is cancelled enters the **stopped** state.
> >
> > This is a bit confusing because it sounds like you're describing a
> > *started* timer. After reading the next paragraph I think this wording
> > applies to both *started* and *running*, but it isn't unambiguous.
>
> Right, I think I understand. It's a mistake. Last sentence should be:
>
> A timer in the **started** or **running** state be **canceled** by the
> `cancel` operation. A timer that is cancelled enters the **stopped**
> state.
I think you meant "*may* be canceled"? I assume this replaces the last
two sentences?
I noticed below I had suggested talking about the handler as
"returning" rather than "finishing execution"; please consider that
throughout.
>
> >
> >> +//!
> >> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
> >> +//! effect after the handler has finished executing and the timer has transitioned
> >> +//! out of the **running** state.
> >
> > There's no external restart, right?
>
> There will be, eventually. Conceptually there is, because the state
> diagram and this text describe the operation.
OK.
>
> > I think this wording is confused
> > by the unification of cancel and restart under operations, though they
> > are not isomorphic.
>
> Hmm, I am not following. Can you elaborate? The set of operations is
> start, cancel, restart.
I wrote this when I thought there was no external restart. By the way,
what is the difference between restart and start? Can a running timer
not be started, or does that do something other than reset it to the
new expiry time?
> > Restart (as I understand it) can only happen from
> > the handler, and cancel can only happen via a call to hrtimer_cancel.
>
> This text introduces the restart operation. There is no code path to
> reach it from rust at the moment, but I am inclined to add the function
> due to this confusion. It would be dead code for now though.
>
> > It's also a bit strange that start isn't mentioned whenever cancel and
> > restart are mentioned.
>
> Why is that?
See above - I think I am confused about the difference between start
and restart when called on a running timer.
>
> >
> >> +//!
> >> +//! A `restart` operation on a timer in the **stopped** state is equivalent to a
> >> +//! `start` operation.
> >> +
> >> +use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque};
> >> +use core::marker::PhantomData;
> >> +
> >> +/// A timer backed by a C `struct hrtimer`.
> >> +///
> >> +/// # Invariants
> >> +///
> >> +/// * `self.timer` is initialized by `bindings::hrtimer_setup`.
> >> +#[pin_data]
> >> +#[repr(C)]
> >> +pub struct HrTimer<T> {
> >> + #[pin]
> >> + timer: Opaque<bindings::hrtimer>,
> >> + _t: PhantomData<T>,
> >> +}
> >> +
> >> +// SAFETY: Ownership of an `HrTimer` can be moved to other threads and
> >> +// used/dropped from there.
> >> +unsafe impl<T> Send for HrTimer<T> {}
> >> +
> >> +// SAFETY: Timer operations are locked on C side, so it is safe to operate on a
> >> +// timer from multiple threads
> >
> > nit: missing article ("the" C side) and missing period.
>
> Thanks.
>
> >
> >> +unsafe impl<T> Sync for HrTimer<T> {}
> >> +
> >> +impl<T> HrTimer<T> {
> >> + /// Return an initializer for a new timer instance.
> >> + pub fn new() -> impl PinInit<Self>
> >> + where
> >> + T: HrTimerCallback,
> >> + {
> >> + pin_init!(Self {
> >> + // INVARIANTS: We initialize `timer` with `hrtimer_setup` below.
> >
> > Why plural INVARIANTS?
>
> Mistake, will fix.
>
> >
> >> + timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
> >> + // SAFETY: By design of `pin_init!`, `place` is a pointer to a
> >> + // live allocation. hrtimer_setup will initialize `place` and
> >> + // does not require `place` to be initialized prior to the call.
> >> + unsafe {
> >> + bindings::hrtimer_setup(
> >> + place,
> >> + Some(T::Pointer::run),
> >> + bindings::CLOCK_MONOTONIC as i32,
> >> + bindings::hrtimer_mode_HRTIMER_MODE_REL,
> >> + );
> >> + }
> >> + }),
> >> + _t: PhantomData,
> >> + })
> >> + }
> >> +
> >> + /// Get a pointer to the contained `bindings::hrtimer`.
> >> + ///
> >> + /// This function do not create any references.
> >
> > s/do/does/
>
> Thanks.
>
> >
> > But maybe this should use the same wording from Opaque::raw_get?
> >
> > /// This function is useful to get access to the value without
> > creating intermediate
> > /// references.
>
> To me those two wordings have the same effect. I don't mind changing the
> wording if you feel strongly about it.
Yeah, I would prefer the wording be the exact same if it is intended
to have the same meaning. Using different wording may trigger Chekov's
Gun in the reader's mind (as it did for me).
> >
> > If so, consider also naming the argument "this" for consistency. Same
> > for other methods below.
>
> Sure.
>
> >
> >> + ///
> >> + /// # Safety
> >> + ///
> >> + /// `ptr` must point to a live allocation of at least the size of `Self`.
> >> + unsafe fn raw_get(ptr: *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 `ptr` points to an
> >> + // allocation of at least the size of `Self`.
> >> + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) }
> >> + }
> >> +
> >> + /// Cancel an initialized and potentially running timer.
> >> + ///
> >> + /// If the timer handler is running, this will block until the handler is
> >> + /// finished.
> >
> > nit: s/is finished/returns/ and maybe clarify the ordering, namely
> > that the timer is definitely in a stopped state after this returns.
>
> /// If the timer handler is running, this function will block until the
> /// handler returns. Before this function returns, the timer will be in the
> /// stopped state.
>
> If we have a concurrent call to start, the timer might actually be in
> the started state when this function returns. But this function will
> transition the timer to the stopped state.
Got it. Consider dropping the last sentence ("before this function
returns..."), I don't think it makes this clearer.
>
> >
> >> + ///
> >> + /// Users of the `HrTimer` API would not usually call this method directly.
> >> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
> >> + /// returned when the timer was started.
> >> + ///
> >> + /// This function does not create any references.
> >> + ///
> >> + /// # Safety
> >> + ///
> >> + /// `self_ptr` must point to a valid `Self`.
> >
> > Why use different phrasing here than on raw_get? The parameter name is
> > also different. Would be nice to be consistent.
>
> They are different requirements, one is stronger than the other. I
> construct safety requirements based on the unsafe operations in the
> function. The unsafe operations in these two functions have different
> requirements. I would not impose a stronger requirement than I have to.
Ah, the requirement is stronger here than on `raw_get`. Thanks for clarifying.
How about the parameter name bit? Can we be consistent?
Opaque::raw_get calls it "this".
>
> >
> >> + #[allow(dead_code)]
> >> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
> >> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
> >> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
> >> +
> >> + // If the handler is running, this will wait for the handler to finish
> >> + // before returning.
> >> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
> >> + // handled on C side.
> >
> > missing article here.
>
> 👍
>
> >
> >> + unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
> >> + }
> >> +}
> >> +
> >> +/// Implemented by pointer types that point to structs that embed a [`HrTimer`].
This comment says "embed a [`HrTimer`]" but in `trait HrTimer` the
wording is "Implemented by structs that contain timer nodes." Is the
difference significant?
Also the naming of the two traits feels inconsistent; one contains
"Has" and the other doesn't.
> >> +///
> >> +/// Target (pointee) must be [`Sync`] because timer callbacks happen in another
> >> +/// thread of execution (hard or soft interrupt context).
> >
> > Is this explaining the bound on the trait, or something that exists
> > outside the type system? If it's the former, isn't the Sync bound on
> > the trait going to apply to the pointer rather than the pointee?
>
> It is explaining the bound on the trait, and as you say it is not
> correct. Pointer types that do not apply synchronization internally can
> only be `Sync` when their target is `Sync`, which was probably my line
> of thought.
>
> I will rephrase:
>
> `Self` must be [`Sync`] because timer callbacks happen in another
> thread of execution (hard or soft interrupt context).
How about "...because it is passed to timer callbacks in another
thread of execution ..."?
> >
> >> +///
> >> +/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
> >> +/// the timer. Note that it is OK to call the start function repeatedly, and
> >> +/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
> >> +/// exist. A timer can be manipulated through any of the handles, and a handle
> >> +/// may represent a cancelled timer.
> >> +pub trait HrTimerPointer: Sync + Sized {
> >> + /// A handle representing a started or restarted timer.
> >> + ///
> >> + /// If the timer is running or if the timer callback is executing when the
> >> + /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
> >> + /// until the timer is stopped and the callback has completed.
> >> + ///
> >> + /// Note: When implementing this trait, consider that it is not unsafe to
> >> + /// leak the handle.
> >
> > What does leak mean in this context?
>
> The same as in all other contexts (I think?). Leave the object alive for
> 'static and forget the address. Thus never drop it and thus never run
> the drop method.
Got it. Is leaking memory generally allowed in the kernel? In other
words, is there nothing that will complain about such memory never
being reclaimed?
>
> >
> >> + type TimerHandle: HrTimerHandle;
> >> +
> >> + /// Start the timer with expiry after `expires` time units. If the timer was
> >> + /// already running, it is restarted with the new expiry time.
> >> + fn start(self, expires: Ktime) -> Self::TimerHandle;
> >> +}
> >> +
> >> +/// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
> >> +/// function to call.
> >> +// This is split from `HrTimerPointer` to make it easier to specify trait bounds.
> >> +pub trait RawHrTimerCallback {
> >> + /// This type is passed to [`HrTimerCallback::run`]. It may be a borrow of
> >> + /// [`Self::CallbackTarget`], or it may be `Self::CallbackTarget` if the
> >> + /// implementation can guarantee correct access (exclusive or shared
> >> + /// depending on the type) to the target during timer handler execution.
> >> + type CallbackTarget<'a>;
> >> +
> >> + /// Callback to be called from C when timer fires.
> >> + ///
> >> + /// # Safety
> >> + ///
> >> + /// Only to be called by C code in `hrtimer` subsystem. `ptr` must point to
> >
> > missing article, should be "...in the `hrtimer`..."
>
> English is difficult 😅
>
> >
> >> + /// the `bindings::hrtimer` structure that was used to start the timer.
> >> + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
> >> +}
> >> +
> >> +/// Implemented by structs that can be the target of a timer callback.
> >> +pub trait HrTimerCallback {
> >> + /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
> >> + /// the timer expires.
> >> + type Pointer<'a>: RawHrTimerCallback;
> >> +
> >> + /// Called by the timer logic when the timer fires.
> >> + fn run(this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>)
> >> + where
> >> + Self: Sized;
> >> +}
> >> +
> >> +/// A handle representing a potentially running timer.
> >> +///
> >> +/// More than one handle representing the same timer might exist.
> >> +///
> >> +/// # Safety
> >> +///
> >> +/// When dropped, the timer represented by this handle must be cancelled, if it
> >> +/// is running. If the timer handler is running when the handle is dropped, the
> >> +/// drop method must wait for the handler to finish before returning.
> >> +///
> >> +/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
> >> +/// the drop implementation for `Self.`
> >> +pub unsafe trait HrTimerHandle {
> >> + /// Cancel the timer, if it is running. If the timer handler is running, block
> >> + /// till the handler has finished.
> >
> > Here's another case where "running" is confusingly used to refer to
> > the timer being in the state before the handler has begun to execute,
> > and also to the state after the handler has begun to execute.
>
> Thanks for catching this. How is this:
>
> /// Cancel the timer, if it is in the started or running state. If the timer
> /// is in the running state, block till the handler has finished executing.
Certainly better. Consider dropping "if it is in the started or running state".
>
>
>
> Thanks for the comments!
You're welcome!
"Tamir Duberstein" <tamird@gmail.com> writes:
> On Tue, Feb 25, 2025 at 3:52 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>>
>> "Tamir Duberstein" <tamird@gmail.com> writes:
>>
>> > Hi Andreas, mostly grammar and prose clarity comments below.
>> >
>> > I still think HasHrTimer::OFFSET is less clear and more fragile than
>> > just generating compiler-checked implementations in the macro (you're
>> > already generating OFFSET and one method implementation rather than
>> > generating 2 method implementations).
>>
>> I don't agree with you assessment. My argument is that I would rather
>> generate as little code as possible in the macro, and the trait would in
>> practice never be implemented by hand.
>
> In the current patch, the trait:
> - provides raw_get_timer
> - provides timer_container_of
> and the macro:
> - defines OFFSET
> - defines raw_get_timer
>
> The justification for the redundancy is that without defining
> raw_get_timer in the macro the user might invoke the macro
> incorrectly.
It's not that they might invoke the macro incorrectly, it's that we
would not be able to make the macro safe. The way it is implemented now,
it will only compile if it is safe.
> But why is that better than defining both methods in the
> macro?
Because it is generating less code. I would rather write the library code than
have the macro generate the code for us on every invocation.
> Either way the macro provides 2 items. The key benefit of
> defining both methods in the macro is that there's no dead-code
> implementation of raw_get_pointer in the trait. It also reduces the
> surface of the trait, which is always a benefit due to Hyrum's law.
When you say that the surface would be smaller, you mean that by
dropping OFFSET entirely, the trait would have fewer items?
I'm not familiar with Hyrum's law.
>
>>
>> >
>> > On Mon, Feb 24, 2025 at 7:06 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>> >>
>>
>> [...]
>>
>> >> +//! # Vocabulary
>> >> +//!
>> >> +//! States:
>> >> +//!
>> >> +//! - Stopped: initialized but not started, or cancelled, or not restarted.
>> >> +//! - Started: initialized and started or restarted.
>> >> +//! - Running: executing the callback.
>> >> +//!
>> >> +//! Operations:
>> >> +//!
>> >> +//! * Start
>> >> +//! * Cancel
>> >> +//! * Restart
>> >> +//!
>> >> +//! Events:
>> >> +//!
>> >> +//! * Expire
>> >> +//!
>> >> +//! ## State Diagram
>> >> +//!
>> >> +//! ```text
>> >> +//! Return NoRestart
>> >> +//! +---------------------------------------------------------------------+
>> >> +//! | |
>> >> +//! | |
>> >> +//! | |
>> >> +//! | Return Restart |
>> >> +//! | +------------------------+ |
>> >> +//! | | | |
>> >> +//! | | | |
>> >> +//! v v | |
>> >> +//! +-----------------+ Start +------------------+ +--------+-----+--+
>> >> +//! | +---------------->| | | |
>> >> +//! Init | | | | Expire | |
>> >> +//! --------->| Stopped | | Started +---------->| Running |
>> >> +//! | | Cancel | | | |
>> >> +//! | |<----------------+ | | |
>> >> +//! +-----------------+ +---------------+--+ +-----------------+
>> >> +//! ^ |
>> >> +//! | |
>> >> +//! +---------+
>> >> +//! Restart
>> >> +//! ```
>> >> +//!
>> >> +//!
>> >> +//! A timer is initialized in the **stopped** state. A stopped timer can be
>> >> +//! **started** by the `start` operation, with an **expiry** time. After the
>> >> +//! `start` operation, the timer is in the **started** state. When the timer
>> >> +//! **expires**, the timer enters the **running** state and the handler is
>> >> +//! executed. After the handler has finished executing, the timer may enter the
>> >> +//! **started* or **stopped** state, depending on the return value of the
>> >> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
>> >> +//! timer that is cancelled enters the **stopped** state.
>> >
>> > This is a bit confusing because it sounds like you're describing a
>> > *started* timer. After reading the next paragraph I think this wording
>> > applies to both *started* and *running*, but it isn't unambiguous.
>>
>> Right, I think I understand. It's a mistake. Last sentence should be:
>>
>> A timer in the **started** or **running** state be **canceled** by the
>> `cancel` operation. A timer that is cancelled enters the **stopped**
>> state.
>
> I think you meant "*may* be canceled"? I assume this replaces the last
> two sentences?
Yes and yes.
> I noticed below I had suggested talking about the handler as
> "returning" rather than "finishing execution"; please consider that
> throughout.
I do not prefer one over the other. Do you care strongly about this one?
>
>>
>> >
>> >> +//!
>> >> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
>> >> +//! effect after the handler has finished executing and the timer has transitioned
>> >> +//! out of the **running** state.
>> >
>> > There's no external restart, right?
>>
>> There will be, eventually. Conceptually there is, because the state
>> diagram and this text describe the operation.
>
> OK.
>
>>
>> > I think this wording is confused
>> > by the unification of cancel and restart under operations, though they
>> > are not isomorphic.
>>
>> Hmm, I am not following. Can you elaborate? The set of operations is
>> start, cancel, restart.
>
> I wrote this when I thought there was no external restart. By the way,
> what is the difference between restart and start? Can a running timer
> not be started, or does that do something other than reset it to the
> new expiry time?
That is good question. I will add the following to address that
question:
//! When a type implements both `HrTimerPointer` and `Clone`, it is possible to
//! issue the `start` operation while the timer is in the **started** state In
//! this case the `start` operation is equivalent to the `restart` operation.
>> > Restart (as I understand it) can only happen from
>> > the handler, and cancel can only happen via a call to hrtimer_cancel.
>>
>> This text introduces the restart operation. There is no code path to
>> reach it from rust at the moment, but I am inclined to add the function
>> due to this confusion. It would be dead code for now though.
>>
>> > It's also a bit strange that start isn't mentioned whenever cancel and
>> > restart are mentioned.
>>
>> Why is that?
>
> See above - I think I am confused about the difference between start
> and restart when called on a running timer.
OK.
[...]
>> >
>> > But maybe this should use the same wording from Opaque::raw_get?
>> >
>> > /// This function is useful to get access to the value without
>> > creating intermediate
>> > /// references.
>>
>> To me those two wordings have the same effect. I don't mind changing the
>> wording if you feel strongly about it.
>
> Yeah, I would prefer the wording be the exact same if it is intended
> to have the same meaning. Using different wording may trigger Chekov's
> Gun in the reader's mind (as it did for me).
I'm not familiar with any guns 😅
I'll apply your suggestion.
[...]
>> >
>> >> + ///
>> >> + /// # Safety
>> >> + ///
>> >> + /// `ptr` must point to a live allocation of at least the size of `Self`.
>> >> + unsafe fn raw_get(ptr: *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 `ptr` points to an
>> >> + // allocation of at least the size of `Self`.
>> >> + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) }
>> >> + }
>> >> +
>> >> + /// Cancel an initialized and potentially running timer.
>> >> + ///
>> >> + /// If the timer handler is running, this will block until the handler is
>> >> + /// finished.
>> >
>> > nit: s/is finished/returns/ and maybe clarify the ordering, namely
>> > that the timer is definitely in a stopped state after this returns.
>>
>> /// If the timer handler is running, this function will block until the
>> /// handler returns. Before this function returns, the timer will be in the
>> /// stopped state.
>>
>> If we have a concurrent call to start, the timer might actually be in
>> the started state when this function returns. But this function will
>> transition the timer to the stopped state.
>
> Got it. Consider dropping the last sentence ("before this function
> returns..."), I don't think it makes this clearer.
OK.
>
>>
>> >
>> >> + ///
>> >> + /// Users of the `HrTimer` API would not usually call this method directly.
>> >> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
>> >> + /// returned when the timer was started.
>> >> + ///
>> >> + /// This function does not create any references.
>> >> + ///
>> >> + /// # Safety
>> >> + ///
>> >> + /// `self_ptr` must point to a valid `Self`.
>> >
>> > Why use different phrasing here than on raw_get? The parameter name is
>> > also different. Would be nice to be consistent.
>>
>> They are different requirements, one is stronger than the other. I
>> construct safety requirements based on the unsafe operations in the
>> function. The unsafe operations in these two functions have different
>> requirements. I would not impose a stronger requirement than I have to.
>
> Ah, the requirement is stronger here than on `raw_get`. Thanks for clarifying.
>
> How about the parameter name bit? Can we be consistent?
> Opaque::raw_get calls it "this".
Yes, I applied this throughout where a pointer to `Self` is passed.
>
>>
>> >
>> >> + #[allow(dead_code)]
>> >> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
>> >> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
>> >> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
>> >> +
>> >> + // If the handler is running, this will wait for the handler to finish
>> >> + // before returning.
>> >> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
>> >> + // handled on C side.
>> >
>> > missing article here.
>>
>> 👍
>>
>> >
>> >> + unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
>> >> + }
>> >> +}
>> >> +
>> >> +/// Implemented by pointer types that point to structs that embed a [`HrTimer`].
>
> This comment says "embed a [`HrTimer`]" but in `trait HrTimer` the
> wording is "Implemented by structs that contain timer nodes."
I don't follow. There is no `trait HrTimer`, there is a `struct
HrTimer`, but it has no such wording.
> Is the difference significant?
No, I would say they are semantically the same. Whether a struct
contains a field of a type or it embeds another struct - I would say
that is the same.
> Also the naming of the two traits feels inconsistent; one contains
> "Has" and the other doesn't.
One is not a trait, not sure if you are looking on another item than
`struct HrTimer`?
>
>> >> +///
>> >> +/// Target (pointee) must be [`Sync`] because timer callbacks happen in another
>> >> +/// thread of execution (hard or soft interrupt context).
>> >
>> > Is this explaining the bound on the trait, or something that exists
>> > outside the type system? If it's the former, isn't the Sync bound on
>> > the trait going to apply to the pointer rather than the pointee?
>>
>> It is explaining the bound on the trait, and as you say it is not
>> correct. Pointer types that do not apply synchronization internally can
>> only be `Sync` when their target is `Sync`, which was probably my line
>> of thought.
>>
>> I will rephrase:
>>
>> `Self` must be [`Sync`] because timer callbacks happen in another
>> thread of execution (hard or soft interrupt context).
>
> How about "...because it is passed to timer callbacks in another
> thread of execution ..."?
OK.
>
>> >
>> >> +///
>> >> +/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
>> >> +/// the timer. Note that it is OK to call the start function repeatedly, and
>> >> +/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
>> >> +/// exist. A timer can be manipulated through any of the handles, and a handle
>> >> +/// may represent a cancelled timer.
>> >> +pub trait HrTimerPointer: Sync + Sized {
>> >> + /// A handle representing a started or restarted timer.
>> >> + ///
>> >> + /// If the timer is running or if the timer callback is executing when the
>> >> + /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
>> >> + /// until the timer is stopped and the callback has completed.
>> >> + ///
>> >> + /// Note: When implementing this trait, consider that it is not unsafe to
>> >> + /// leak the handle.
>> >
>> > What does leak mean in this context?
>>
>> The same as in all other contexts (I think?). Leave the object alive for
>> 'static and forget the address. Thus never drop it and thus never run
>> the drop method.
>
> Got it. Is leaking memory generally allowed in the kernel? In other
> words, is there nothing that will complain about such memory never
> being reclaimed?
Leaking is generally unacceptable in the kernel. However, leaking is
considered safe in rust and is possible within the safe subset of rust.
The first time I implemented this trait, it was unsound in the face of
the handle being leaked. Of curse this is no different than any other
code, and we can generally not hinge soundness on things not being
leaked. But after I foot gunned myself with this, I put the comment.
[...]
>> >> +/// A handle representing a potentially running timer.
>> >> +///
>> >> +/// More than one handle representing the same timer might exist.
>> >> +///
>> >> +/// # Safety
>> >> +///
>> >> +/// When dropped, the timer represented by this handle must be cancelled, if it
>> >> +/// is running. If the timer handler is running when the handle is dropped, the
>> >> +/// drop method must wait for the handler to finish before returning.
>> >> +///
>> >> +/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
>> >> +/// the drop implementation for `Self.`
>> >> +pub unsafe trait HrTimerHandle {
>> >> + /// Cancel the timer, if it is running. If the timer handler is running, block
>> >> + /// till the handler has finished.
>> >
>> > Here's another case where "running" is confusingly used to refer to
>> > the timer being in the state before the handler has begun to execute,
>> > and also to the state after the handler has begun to execute.
>>
>> Thanks for catching this. How is this:
>>
>> /// Cancel the timer, if it is in the started or running state. If the timer
>> /// is in the running state, block till the handler has finished executing.
>
> Certainly better. Consider dropping "if it is in the started or running state".
OK.
Best regards,
Andreas Hindborg
On Tue, Feb 25, 2025 at 2:12 PM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>
> "Tamir Duberstein" <tamird@gmail.com> writes:
>
> > On Tue, Feb 25, 2025 at 3:52 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
> >>
> >> "Tamir Duberstein" <tamird@gmail.com> writes:
> >>
> >> > Hi Andreas, mostly grammar and prose clarity comments below.
> >> >
> >> > I still think HasHrTimer::OFFSET is less clear and more fragile than
> >> > just generating compiler-checked implementations in the macro (you're
> >> > already generating OFFSET and one method implementation rather than
> >> > generating 2 method implementations).
> >>
> >> I don't agree with you assessment. My argument is that I would rather
> >> generate as little code as possible in the macro, and the trait would in
> >> practice never be implemented by hand.
> >
> > In the current patch, the trait:
> > - provides raw_get_timer
> > - provides timer_container_of
> > and the macro:
> > - defines OFFSET
> > - defines raw_get_timer
> >
> > The justification for the redundancy is that without defining
> > raw_get_timer in the macro the user might invoke the macro
> > incorrectly.
>
> It's not that they might invoke the macro incorrectly, it's that we
> would not be able to make the macro safe. The way it is implemented now,
> it will only compile if it is safe.
>
> > But why is that better than defining both methods in the
> > macro?
>
> Because it is generating less code. I would rather write the library code than
> have the macro generate the code for us on every invocation.
How is it less code? It's the same amount, just harder to reason about
because you're doing pointer arithmetic rather than relying on
existing macros like container_of.
>
> > Either way the macro provides 2 items. The key benefit of
> > defining both methods in the macro is that there's no dead-code
> > implementation of raw_get_pointer in the trait. It also reduces the
> > surface of the trait, which is always a benefit due to Hyrum's law.
>
> When you say that the surface would be smaller, you mean that by
> dropping OFFSET entirely, the trait would have fewer items?
Yes.
> I'm not familiar with Hyrum's law.
TL;DR is that anything that can become load bearing will. So even if
the intent is that OFFSET is an implementation detail, there's no way
to enforce that, and so someone will misuse it.
> >
> >>
> >> >
> >> > On Mon, Feb 24, 2025 at 7:06 AM Andreas Hindborg <a.hindborg@kernel.org> wrote:
> >> >>
> >>
> >> [...]
> >>
> >> >> +//! # Vocabulary
> >> >> +//!
> >> >> +//! States:
> >> >> +//!
> >> >> +//! - Stopped: initialized but not started, or cancelled, or not restarted.
> >> >> +//! - Started: initialized and started or restarted.
> >> >> +//! - Running: executing the callback.
> >> >> +//!
> >> >> +//! Operations:
> >> >> +//!
> >> >> +//! * Start
> >> >> +//! * Cancel
> >> >> +//! * Restart
> >> >> +//!
> >> >> +//! Events:
> >> >> +//!
> >> >> +//! * Expire
> >> >> +//!
> >> >> +//! ## State Diagram
> >> >> +//!
> >> >> +//! ```text
> >> >> +//! Return NoRestart
> >> >> +//! +---------------------------------------------------------------------+
> >> >> +//! | |
> >> >> +//! | |
> >> >> +//! | |
> >> >> +//! | Return Restart |
> >> >> +//! | +------------------------+ |
> >> >> +//! | | | |
> >> >> +//! | | | |
> >> >> +//! v v | |
> >> >> +//! +-----------------+ Start +------------------+ +--------+-----+--+
> >> >> +//! | +---------------->| | | |
> >> >> +//! Init | | | | Expire | |
> >> >> +//! --------->| Stopped | | Started +---------->| Running |
> >> >> +//! | | Cancel | | | |
> >> >> +//! | |<----------------+ | | |
> >> >> +//! +-----------------+ +---------------+--+ +-----------------+
> >> >> +//! ^ |
> >> >> +//! | |
> >> >> +//! +---------+
> >> >> +//! Restart
> >> >> +//! ```
> >> >> +//!
> >> >> +//!
> >> >> +//! A timer is initialized in the **stopped** state. A stopped timer can be
> >> >> +//! **started** by the `start` operation, with an **expiry** time. After the
> >> >> +//! `start` operation, the timer is in the **started** state. When the timer
> >> >> +//! **expires**, the timer enters the **running** state and the handler is
> >> >> +//! executed. After the handler has finished executing, the timer may enter the
> >> >> +//! **started* or **stopped** state, depending on the return value of the
> >> >> +//! handler. A running timer can be **canceled** by the `cancel` operation. A
> >> >> +//! timer that is cancelled enters the **stopped** state.
> >> >
> >> > This is a bit confusing because it sounds like you're describing a
> >> > *started* timer. After reading the next paragraph I think this wording
> >> > applies to both *started* and *running*, but it isn't unambiguous.
> >>
> >> Right, I think I understand. It's a mistake. Last sentence should be:
> >>
> >> A timer in the **started** or **running** state be **canceled** by the
> >> `cancel` operation. A timer that is cancelled enters the **stopped**
> >> state.
> >
> > I think you meant "*may* be canceled"? I assume this replaces the last
> > two sentences?
>
> Yes and yes.
>
>
> > I noticed below I had suggested talking about the handler as
> > "returning" rather than "finishing execution"; please consider that
> > throughout.
>
> I do not prefer one over the other. Do you care strongly about this one?
I prefer return since it's more obvious but don't feel strongly about
the choice, only that the usage is consistent.
>
> >
> >>
> >> >
> >> >> +//!
> >> >> +//! A `cancel` or `restart` operation on a timer in the **running** state takes
> >> >> +//! effect after the handler has finished executing and the timer has transitioned
> >> >> +//! out of the **running** state.
> >> >
> >> > There's no external restart, right?
> >>
> >> There will be, eventually. Conceptually there is, because the state
> >> diagram and this text describe the operation.
> >
> > OK.
> >
> >>
> >> > I think this wording is confused
> >> > by the unification of cancel and restart under operations, though they
> >> > are not isomorphic.
> >>
> >> Hmm, I am not following. Can you elaborate? The set of operations is
> >> start, cancel, restart.
> >
> > I wrote this when I thought there was no external restart. By the way,
> > what is the difference between restart and start? Can a running timer
> > not be started, or does that do something other than reset it to the
> > new expiry time?
>
> That is good question. I will add the following to address that
> question:
>
> //! When a type implements both `HrTimerPointer` and `Clone`, it is possible to
> //! issue the `start` operation while the timer is in the **started** state In
> //! this case the `start` operation is equivalent to the `restart` operation.
>
> >> > Restart (as I understand it) can only happen from
> >> > the handler, and cancel can only happen via a call to hrtimer_cancel.
> >>
> >> This text introduces the restart operation. There is no code path to
> >> reach it from rust at the moment, but I am inclined to add the function
> >> due to this confusion. It would be dead code for now though.
> >>
> >> > It's also a bit strange that start isn't mentioned whenever cancel and
> >> > restart are mentioned.
> >>
> >> Why is that?
> >
> > See above - I think I am confused about the difference between start
> > and restart when called on a running timer.
>
> OK.
>
> [...]
>
> >> >
> >> > But maybe this should use the same wording from Opaque::raw_get?
> >> >
> >> > /// This function is useful to get access to the value without
> >> > creating intermediate
> >> > /// references.
> >>
> >> To me those two wordings have the same effect. I don't mind changing the
> >> wording if you feel strongly about it.
> >
> > Yeah, I would prefer the wording be the exact same if it is intended
> > to have the same meaning. Using different wording may trigger Chekov's
> > Gun in the reader's mind (as it did for me).
>
> I'm not familiar with any guns 😅
>
> I'll apply your suggestion.
>
> [...]
>
> >> >
> >> >> + ///
> >> >> + /// # Safety
> >> >> + ///
> >> >> + /// `ptr` must point to a live allocation of at least the size of `Self`.
> >> >> + unsafe fn raw_get(ptr: *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 `ptr` points to an
> >> >> + // allocation of at least the size of `Self`.
> >> >> + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) }
> >> >> + }
> >> >> +
> >> >> + /// Cancel an initialized and potentially running timer.
> >> >> + ///
> >> >> + /// If the timer handler is running, this will block until the handler is
> >> >> + /// finished.
> >> >
> >> > nit: s/is finished/returns/ and maybe clarify the ordering, namely
> >> > that the timer is definitely in a stopped state after this returns.
> >>
> >> /// If the timer handler is running, this function will block until the
> >> /// handler returns. Before this function returns, the timer will be in the
> >> /// stopped state.
> >>
> >> If we have a concurrent call to start, the timer might actually be in
> >> the started state when this function returns. But this function will
> >> transition the timer to the stopped state.
> >
> > Got it. Consider dropping the last sentence ("before this function
> > returns..."), I don't think it makes this clearer.
>
> OK.
>
> >
> >>
> >> >
> >> >> + ///
> >> >> + /// Users of the `HrTimer` API would not usually call this method directly.
> >> >> + /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
> >> >> + /// returned when the timer was started.
> >> >> + ///
> >> >> + /// This function does not create any references.
> >> >> + ///
> >> >> + /// # Safety
> >> >> + ///
> >> >> + /// `self_ptr` must point to a valid `Self`.
> >> >
> >> > Why use different phrasing here than on raw_get? The parameter name is
> >> > also different. Would be nice to be consistent.
> >>
> >> They are different requirements, one is stronger than the other. I
> >> construct safety requirements based on the unsafe operations in the
> >> function. The unsafe operations in these two functions have different
> >> requirements. I would not impose a stronger requirement than I have to.
> >
> > Ah, the requirement is stronger here than on `raw_get`. Thanks for clarifying.
> >
> > How about the parameter name bit? Can we be consistent?
> > Opaque::raw_get calls it "this".
>
> Yes, I applied this throughout where a pointer to `Self` is passed.
>
> >
> >>
> >> >
> >> >> + #[allow(dead_code)]
> >> >> + pub(crate) unsafe fn raw_cancel(self_ptr: *const Self) -> bool {
> >> >> + // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
> >> >> + let c_timer_ptr = unsafe { HrTimer::raw_get(self_ptr) };
> >> >> +
> >> >> + // If the handler is running, this will wait for the handler to finish
> >> >> + // before returning.
> >> >> + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
> >> >> + // handled on C side.
> >> >
> >> > missing article here.
> >>
> >> 👍
> >>
> >> >
> >> >> + unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
> >> >> + }
> >> >> +}
> >> >> +
> >> >> +/// Implemented by pointer types that point to structs that embed a [`HrTimer`].
> >
> > This comment says "embed a [`HrTimer`]" but in `trait HrTimer` the
> > wording is "Implemented by structs that contain timer nodes."
>
> I don't follow. There is no `trait HrTimer`, there is a `struct
> HrTimer`, but it has no such wording.
>
> > Is the difference significant?
>
> No, I would say they are semantically the same. Whether a struct
> contains a field of a type or it embeds another struct - I would say
> that is the same.
Can we use the same wording in both places then?
>
> > Also the naming of the two traits feels inconsistent; one contains
> > "Has" and the other doesn't.
>
> One is not a trait, not sure if you are looking on another item than
> `struct HrTimer`?
Sorry, I meant HasHrTimer and HrTimerPointer rather than HrTimer and
HrTimerPointer.
> >
> >> >> +///
> >> >> +/// Target (pointee) must be [`Sync`] because timer callbacks happen in another
> >> >> +/// thread of execution (hard or soft interrupt context).
> >> >
> >> > Is this explaining the bound on the trait, or something that exists
> >> > outside the type system? If it's the former, isn't the Sync bound on
> >> > the trait going to apply to the pointer rather than the pointee?
> >>
> >> It is explaining the bound on the trait, and as you say it is not
> >> correct. Pointer types that do not apply synchronization internally can
> >> only be `Sync` when their target is `Sync`, which was probably my line
> >> of thought.
> >>
> >> I will rephrase:
> >>
> >> `Self` must be [`Sync`] because timer callbacks happen in another
> >> thread of execution (hard or soft interrupt context).
> >
> > How about "...because it is passed to timer callbacks in another
> > thread of execution ..."?
>
> OK.
>
> >
> >> >
> >> >> +///
> >> >> +/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
> >> >> +/// the timer. Note that it is OK to call the start function repeatedly, and
> >> >> +/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
> >> >> +/// exist. A timer can be manipulated through any of the handles, and a handle
> >> >> +/// may represent a cancelled timer.
> >> >> +pub trait HrTimerPointer: Sync + Sized {
> >> >> + /// A handle representing a started or restarted timer.
> >> >> + ///
> >> >> + /// If the timer is running or if the timer callback is executing when the
> >> >> + /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
> >> >> + /// until the timer is stopped and the callback has completed.
> >> >> + ///
> >> >> + /// Note: When implementing this trait, consider that it is not unsafe to
> >> >> + /// leak the handle.
> >> >
> >> > What does leak mean in this context?
> >>
> >> The same as in all other contexts (I think?). Leave the object alive for
> >> 'static and forget the address. Thus never drop it and thus never run
> >> the drop method.
> >
> > Got it. Is leaking memory generally allowed in the kernel? In other
> > words, is there nothing that will complain about such memory never
> > being reclaimed?
>
> Leaking is generally unacceptable in the kernel. However, leaking is
> considered safe in rust and is possible within the safe subset of rust.
>
> The first time I implemented this trait, it was unsound in the face of
> the handle being leaked. Of curse this is no different than any other
> code, and we can generally not hinge soundness on things not being
> leaked. But after I foot gunned myself with this, I put the comment.
>
> [...]
>
> >> >> +/// A handle representing a potentially running timer.
> >> >> +///
> >> >> +/// More than one handle representing the same timer might exist.
> >> >> +///
> >> >> +/// # Safety
> >> >> +///
> >> >> +/// When dropped, the timer represented by this handle must be cancelled, if it
> >> >> +/// is running. If the timer handler is running when the handle is dropped, the
> >> >> +/// drop method must wait for the handler to finish before returning.
> >> >> +///
> >> >> +/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
> >> >> +/// the drop implementation for `Self.`
> >> >> +pub unsafe trait HrTimerHandle {
> >> >> + /// Cancel the timer, if it is running. If the timer handler is running, block
> >> >> + /// till the handler has finished.
> >> >
> >> > Here's another case where "running" is confusingly used to refer to
> >> > the timer being in the state before the handler has begun to execute,
> >> > and also to the state after the handler has begun to execute.
> >>
> >> Thanks for catching this. How is this:
> >>
> >> /// Cancel the timer, if it is in the started or running state. If the timer
> >> /// is in the running state, block till the handler has finished executing.
> >
> > Certainly better. Consider dropping "if it is in the started or running state".
>
> OK.
>
>
> Best regards,
> Andreas Hindborg
>
>
"Tamir Duberstein" <tamird@gmail.com> writes: > On Tue, Feb 25, 2025 at 2:12 PM Andreas Hindborg <a.hindborg@kernel.org> wrote: >> >> "Tamir Duberstein" <tamird@gmail.com> writes: >> >> > On Tue, Feb 25, 2025 at 3:52 AM Andreas Hindborg <a.hindborg@kernel.org> wrote: >> >> >> >> "Tamir Duberstein" <tamird@gmail.com> writes: >> >> >> >> > Hi Andreas, mostly grammar and prose clarity comments below. >> >> > >> >> > I still think HasHrTimer::OFFSET is less clear and more fragile than >> >> > just generating compiler-checked implementations in the macro (you're >> >> > already generating OFFSET and one method implementation rather than >> >> > generating 2 method implementations). >> >> >> >> I don't agree with you assessment. My argument is that I would rather >> >> generate as little code as possible in the macro, and the trait would in >> >> practice never be implemented by hand. >> > >> > In the current patch, the trait: >> > - provides raw_get_timer >> > - provides timer_container_of >> > and the macro: >> > - defines OFFSET >> > - defines raw_get_timer >> > >> > The justification for the redundancy is that without defining >> > raw_get_timer in the macro the user might invoke the macro >> > incorrectly. >> >> It's not that they might invoke the macro incorrectly, it's that we >> would not be able to make the macro safe. The way it is implemented now, >> it will only compile if it is safe. >> >> > But why is that better than defining both methods in the >> > macro? >> >> Because it is generating less code. I would rather write the library code than >> have the macro generate the code for us on every invocation. > > How is it less code? It's the same amount, just harder to reason about > because you're doing pointer arithmetic rather than relying on > existing macros like container_of. > >> >> > Either way the macro provides 2 items. The key benefit of >> > defining both methods in the macro is that there's no dead-code >> > implementation of raw_get_pointer in the trait. It also reduces the >> > surface of the trait, which is always a benefit due to Hyrum's law. >> >> When you say that the surface would be smaller, you mean that by >> dropping OFFSET entirely, the trait would have fewer items? > > Yes. > > >> I'm not familiar with Hyrum's law. > > TL;DR is that anything that can become load bearing will. So even if > the intent is that OFFSET is an implementation detail, there's no way > to enforce that, and so someone will misuse it. I don't fully agree with your assessment, but either way is fine for me. So I shall implement your suggestion. [...] >> > I noticed below I had suggested talking about the handler as >> > "returning" rather than "finishing execution"; please consider that >> > throughout. >> >> I do not prefer one over the other. Do you care strongly about this one? > > I prefer return since it's more obvious but don't feel strongly about > the choice, only that the usage is consistent. Ok, let's do that then. [...] >> >> >> +/// Implemented by pointer types that point to structs that embed a [`HrTimer`]. >> > >> > This comment says "embed a [`HrTimer`]" but in `trait HrTimer` the >> > wording is "Implemented by structs that contain timer nodes." >> >> I don't follow. There is no `trait HrTimer`, there is a `struct >> HrTimer`, but it has no such wording. >> >> > Is the difference significant? >> >> No, I would say they are semantically the same. Whether a struct >> contains a field of a type or it embeds another struct - I would say >> that is the same. > > Can we use the same wording in both places then? OK. >> > Also the naming of the two traits feels inconsistent; one contains >> > "Has" and the other doesn't. >> >> One is not a trait, not sure if you are looking on another item than >> `struct HrTimer`? > > Sorry, I meant HasHrTimer and HrTimerPointer rather than HrTimer and > HrTimerPointer. `HasHrTimer` is named so because it is meant to be implemented by types that contain a field of type `HrTimer`. `HrTimerPointer` is meant to be implemented by pointer types that point to types that implement `HasHrTimer`. They are different, and the naming reflect that. I will not rename `HasHrTimer` to `ContainsHrTimer`, because the rest of the rust kernel uses the `HasFoo` naming scheme. Best regards, Andreas Hindborg
On Wed, Feb 26, 2025 at 6:48 AM Andreas Hindborg <a.hindborg@kernel.org> wrote: > > "Tamir Duberstein" <tamird@gmail.com> writes: > > > Sorry, I meant HasHrTimer and HrTimerPointer rather than HrTimer and > > HrTimerPointer. > > `HasHrTimer` is named so because it is meant to be implemented by types > that contain a field of type `HrTimer`. > > `HrTimerPointer` is meant to be implemented by pointer types that point > to types that implement `HasHrTimer`. > > They are different, and the naming reflect that. > > I will not rename `HasHrTimer` to `ContainsHrTimer`, because the rest of > the rust kernel uses the `HasFoo` naming scheme. The Has prefix makes sense in HasHrTimer. Shouldn't the name HrTimerPointer also contain "Has"? HasHrTimerPointer would be confusing, but perhaps PointerToHasHrTimer? It's a mouthful to be sure.
"Tamir Duberstein" <tamird@gmail.com> writes: > On Wed, Feb 26, 2025 at 6:48 AM Andreas Hindborg <a.hindborg@kernel.org> wrote: >> >> "Tamir Duberstein" <tamird@gmail.com> writes: >> >> > Sorry, I meant HasHrTimer and HrTimerPointer rather than HrTimer and >> > HrTimerPointer. >> >> `HasHrTimer` is named so because it is meant to be implemented by types >> that contain a field of type `HrTimer`. >> >> `HrTimerPointer` is meant to be implemented by pointer types that point >> to types that implement `HasHrTimer`. >> >> They are different, and the naming reflect that. >> >> I will not rename `HasHrTimer` to `ContainsHrTimer`, because the rest of >> the rust kernel uses the `HasFoo` naming scheme. > > The Has prefix makes sense in HasHrTimer. Shouldn't the name > HrTimerPointer also contain "Has"? HasHrTimerPointer would be > confusing, but perhaps PointerToHasHrTimer? It's a mouthful to be > sure. I get your point, but I really think that `HasHrTimer` and `HrTimerPointer` is pretty good. Names _can_ get too long. Best regards, Andreas Hindborg
Hi Frederic, "Andreas Hindborg" <a.hindborg@kernel.org> writes: > This patch adds support for intrusive use of the hrtimer system. For now, > only one timer can be embedded in a Rust struct. > > The hrtimer Rust API is based on the intrusive style pattern introduced by > the Rust workqueue API. > > Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org> > --- I dropped your ack because I added the kconfig. Re-ack if you are still happy :) Best regards, Andreas Hindborg
Hi Andreas, On Mon, Feb 24, 2025 at 02:19:45PM +0100, Andreas Hindborg wrote: > Hi Frederic, > > "Andreas Hindborg" <a.hindborg@kernel.org> writes: > > > This patch adds support for intrusive use of the hrtimer system. For now, > > only one timer can be embedded in a Rust struct. > > > > The hrtimer Rust API is based on the intrusive style pattern introduced by > > the Rust workqueue API. > > > > Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org> > > --- > > I dropped your ack because I added the kconfig. Re-ack if you are still > happy :) > Why do we need this new kconfig? Regards, Boqun > > Best regards, > Andreas Hindborg > >
On Mon, Feb 24, 2025 at 4:46 PM Boqun Feng <boqun.feng@gmail.com> wrote: > > Why do we need this new kconfig? I suspect it is to provide flexibility (i.e. to avoid building everything if there are no users of the abstraction) and/or to limit the set of configs that may be affected by a breaking change on the C side -- Andreas and I discussed it the other day. The description of the issue has some lines, but perhaps the commit message could clarify. We have a similar one already, i.e. a "Rust-only" config, in `CONFIG_RUST_FW_LOADER_ABSTRACTIONS`. Since this one is default "y", it may still affect unrelated subsystems that just enable `RUST=y`, though. (I guess we could consider `select`ing from end users. But they cannot be hidden symbols, because that limits the control too much (e.g. someone may want to just build the abstraction), and in general they may have dependencies, so it may not be a good idea.) Cheers, Miguel
On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: > On Mon, Feb 24, 2025 at 4:46 PM Boqun Feng <boqun.feng@gmail.com> wrote: > > > > Why do we need this new kconfig? > > I suspect it is to provide flexibility (i.e. to avoid building > everything if there are no users of the abstraction) and/or to limit > the set of configs that may be affected by a breaking change on the C > side -- Andreas and I discussed it the other day. The description of > the issue has some lines, but perhaps the commit message could Do you have a link to the issue? I asked because hrtimer API is always available regardless of the configuration, and it's such a core API, so it should always be there (Rust or C). Regards, Boqun > clarify. > > We have a similar one already, i.e. a "Rust-only" config, in > `CONFIG_RUST_FW_LOADER_ABSTRACTIONS`. > > Since this one is default "y", it may still affect unrelated > subsystems that just enable `RUST=y`, though. > > (I guess we could consider `select`ing from end users. But they cannot > be hidden symbols, because that limits the control too much (e.g. > someone may want to just build the abstraction), and in general they > may have dependencies, so it may not be a good idea.) > > Cheers, > Miguel
On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: > > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: > > > > side -- Andreas and I discussed it the other day. The description of > > the issue has some lines, but perhaps the commit message could > > Do you have a link to the issue? Sorry, I meant "description of the symbol", i.e. the description field in the patch. > I asked because hrtimer API is always available regardless of the > configuration, and it's such a core API, so it should always be there > (Rust or C). It may not make sense for something that is always built on the C side, yeah. I think the intention here may be that one can easily disable it while "developing" a change on the C side. I am not sure what "developing" means here, though, and we need to be careful -- after all, Kconfig options are visible to users and they do not care about that. If it is just for local development, then I would expect the maintainers to simply disable Rust entirely. I guess that may be harder in the medium/long-term future, but currently, I don't see a big issue not enabling Rust while developing the C side, no? Cheers, Miguel
On Mon, Feb 24, 2025 at 05:45:03PM +0100, Miguel Ojeda wrote: > On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: > > > > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: > > > > > > side -- Andreas and I discussed it the other day. The description of > > > the issue has some lines, but perhaps the commit message could > > > > Do you have a link to the issue? > > Sorry, I meant "description of the symbol", i.e. the description field > in the patch. > Oh, I see. Yes, the patch description should provide more information about what the kconfig means for hrtimer maintainers' development. > > I asked because hrtimer API is always available regardless of the > > configuration, and it's such a core API, so it should always be there > > (Rust or C). > > It may not make sense for something that is always built on the C > side, yeah. I think the intention here may be that one can easily > disable it while "developing" a change on the C side. I am not sure > what "developing" means here, though, and we need to be careful -- > after all, Kconfig options are visible to users and they do not care > about that. > Personally, I don't think CONFIG_RUST_HRTIMER is necessarily because as you mentioned below, people can disable Rust entirely during "developing". And if I understand the intention correctly, the CONFIG_RUST_HRTIMER config provides hrtimer maintainers a way that they could disable Rust hrtimer abstraction (while enabling other Rust component) when they're developing a change on the C side, right? If so, it's hrtimer maintainers' call, and this patch should provide more information on this. Back to my personal opinion, I don't think this is necessary ;-) Particularly because I can fix if something breaks Rust side, and I'm confident and happy to do so for hrtimer ;-) Regards, Boqun > If it is just for local development, then I would expect the > maintainers to simply disable Rust entirely. I guess that may be > harder in the medium/long-term future, but currently, I don't see a > big issue not enabling Rust while developing the C side, no? > > Cheers, > Miguel
"Boqun Feng" <boqun.feng@gmail.com> writes: > On Mon, Feb 24, 2025 at 05:45:03PM +0100, Miguel Ojeda wrote: >> On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: >> > >> > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: >> > > >> > > side -- Andreas and I discussed it the other day. The description of >> > > the issue has some lines, but perhaps the commit message could >> > >> > Do you have a link to the issue? >> >> Sorry, I meant "description of the symbol", i.e. the description field >> in the patch. >> > > Oh, I see. Yes, the patch description should provide more information > about what the kconfig means for hrtimer maintainers' development. Right, I neglected to update the commit message. I will do that if we have another version. > >> > I asked because hrtimer API is always available regardless of the >> > configuration, and it's such a core API, so it should always be there >> > (Rust or C). >> >> It may not make sense for something that is always built on the C >> side, yeah. I think the intention here may be that one can easily >> disable it while "developing" a change on the C side. I am not sure >> what "developing" means here, though, and we need to be careful -- >> after all, Kconfig options are visible to users and they do not care >> about that. >> > > Personally, I don't think CONFIG_RUST_HRTIMER is necessarily because as > you mentioned below, people can disable Rust entirely during > "developing". > > And if I understand the intention correctly, the CONFIG_RUST_HRTIMER > config provides hrtimer maintainers a way that they could disable Rust > hrtimer abstraction (while enabling other Rust component) when they're > developing a change on the C side, right? If so, it's hrtimer > maintainers' call, and this patch should provide more information on > this. > > Back to my personal opinion, I don't think this is necessary ;-) > Particularly because I can fix if something breaks Rust side, and I'm > confident and happy to do so for hrtimer ;-) As Miguel said, the idea for this came up in the past week in one of the mega threads discussing rust in general. We had a lot of "what happens if I change something in my subsystem and that breaks rust" kind of discussions. For subsystems where the people maintaining the C subsystem is not the same people maintaining the Rust abstractions, this switch might be valuable. It would allow making breaking changes to the C code of a subsystem without refactoring the Rust code in the same sitting. Rather than having to disable rust entirely - or going and commenting out lines in the kernel crate - I think it is better to provide an option to just disable building these particular bindings. This has nothing to do with general policies related to breakage between Rust and C code, and how to fix such breakage in a timely manner. It is simply a useful switch for disabling part of the build so that people can move on with their business, while someone else scrambles to fix whatever needs fixing on the Rust side. I am of course also available to fix anything that would eventually break. In fact, I expect to be able to catch breakage most of the time automatically and very early by means of automatically monitoring the relevant trees. I do this for block, and it has worked really well since rust code was merged in that subsystem. Best regards, Andreas Hindborg
On Mon, Feb 24, 2025 at 07:58:04PM +0100, Andreas Hindborg wrote: > "Boqun Feng" <boqun.feng@gmail.com> writes: > > > On Mon, Feb 24, 2025 at 05:45:03PM +0100, Miguel Ojeda wrote: > >> On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: > >> > > >> > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: > >> > > > >> > > side -- Andreas and I discussed it the other day. The description of > >> > > the issue has some lines, but perhaps the commit message could > >> > > >> > Do you have a link to the issue? > >> > >> Sorry, I meant "description of the symbol", i.e. the description field > >> in the patch. > >> > > > > Oh, I see. Yes, the patch description should provide more information > > about what the kconfig means for hrtimer maintainers' development. > > Right, I neglected to update the commit message. I will do that if we > have another version. > > > > >> > I asked because hrtimer API is always available regardless of the > >> > configuration, and it's such a core API, so it should always be there > >> > (Rust or C). > >> > >> It may not make sense for something that is always built on the C > >> side, yeah. I think the intention here may be that one can easily > >> disable it while "developing" a change on the C side. I am not sure > >> what "developing" means here, though, and we need to be careful -- > >> after all, Kconfig options are visible to users and they do not care > >> about that. > >> > > > > Personally, I don't think CONFIG_RUST_HRTIMER is necessarily because as > > you mentioned below, people can disable Rust entirely during > > "developing". > > > > And if I understand the intention correctly, the CONFIG_RUST_HRTIMER > > config provides hrtimer maintainers a way that they could disable Rust > > hrtimer abstraction (while enabling other Rust component) when they're > > developing a change on the C side, right? If so, it's hrtimer > > maintainers' call, and this patch should provide more information on > > this. > > > > Back to my personal opinion, I don't think this is necessary ;-) > > Particularly because I can fix if something breaks Rust side, and I'm > > confident and happy to do so for hrtimer ;-) > > As Miguel said, the idea for this came up in the past week in one of the > mega threads discussing rust in general. We had a lot of "what happens > if I change something in my subsystem and that breaks rust" kind of > discussions. > So far we haven't heard such a question from hrtimer maintainers, I would only add such a kconfig if explicitly requested. > For subsystems where the people maintaining the C subsystem is not the > same people maintaining the Rust abstractions, this switch might be > valuable. It would allow making breaking changes to the C code of a > subsystem without refactoring the Rust code in the same sitting. Rather That's why I asked Frederic to be a reviewer of Rust hrtimer API. In longer-term, more and more people will get more or less Rust knowledge, and I'd argue that's the direction we should head to. So my vision is a significant amount of core kernel developers would be able to make C and Rust changes at the same time. It's of course not mandatory, but it's better collaboration. > than having to disable rust entirely - or going and commenting out lines > in the kernel crate - I think it is better to provide an option to just > disable building these particular bindings. > > This has nothing to do with general policies related to breakage between > Rust and C code, and how to fix such breakage in a timely manner. It is > simply a useful switch for disabling part of the build so that people > can move on with their business, while someone else scrambles to fix > whatever needs fixing on the Rust side. > It's of course up to hrtimer maintainers. But I personally nack this kconfig, because it's not necessary, and hrtimer API has been stable for a while. Regards, Boqun > I am of course also available to fix anything that would eventually > break. In fact, I expect to be able to catch breakage most of the time > automatically and very early by means of automatically monitoring the > relevant trees. I do this for block, and it has worked really well since > rust code was merged in that subsystem. > > > Best regards, > Andreas Hindborg > > > > >
"Boqun Feng" <boqun.feng@gmail.com> writes: > On Mon, Feb 24, 2025 at 07:58:04PM +0100, Andreas Hindborg wrote: >> "Boqun Feng" <boqun.feng@gmail.com> writes: >> >> > On Mon, Feb 24, 2025 at 05:45:03PM +0100, Miguel Ojeda wrote: >> >> On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: >> >> > >> >> > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: >> >> > > >> >> > > side -- Andreas and I discussed it the other day. The description of >> >> > > the issue has some lines, but perhaps the commit message could >> >> > >> >> > Do you have a link to the issue? >> >> >> >> Sorry, I meant "description of the symbol", i.e. the description field >> >> in the patch. >> >> >> > >> > Oh, I see. Yes, the patch description should provide more information >> > about what the kconfig means for hrtimer maintainers' development. >> >> Right, I neglected to update the commit message. I will do that if we >> have another version. >> >> > >> >> > I asked because hrtimer API is always available regardless of the >> >> > configuration, and it's such a core API, so it should always be there >> >> > (Rust or C). >> >> >> >> It may not make sense for something that is always built on the C >> >> side, yeah. I think the intention here may be that one can easily >> >> disable it while "developing" a change on the C side. I am not sure >> >> what "developing" means here, though, and we need to be careful -- >> >> after all, Kconfig options are visible to users and they do not care >> >> about that. >> >> >> > >> > Personally, I don't think CONFIG_RUST_HRTIMER is necessarily because as >> > you mentioned below, people can disable Rust entirely during >> > "developing". >> > >> > And if I understand the intention correctly, the CONFIG_RUST_HRTIMER >> > config provides hrtimer maintainers a way that they could disable Rust >> > hrtimer abstraction (while enabling other Rust component) when they're >> > developing a change on the C side, right? If so, it's hrtimer >> > maintainers' call, and this patch should provide more information on >> > this. >> > >> > Back to my personal opinion, I don't think this is necessary ;-) >> > Particularly because I can fix if something breaks Rust side, and I'm >> > confident and happy to do so for hrtimer ;-) >> >> As Miguel said, the idea for this came up in the past week in one of the >> mega threads discussing rust in general. We had a lot of "what happens >> if I change something in my subsystem and that breaks rust" kind of >> discussions. >> > > So far we haven't heard such a question from hrtimer maintainers, I > would only add such a kconfig if explicitly requested. It gives flexibility and has no negative side effects. Of course, if it is unwanted, we can just remove it. But I would like to understand the deeper rationale. > >> For subsystems where the people maintaining the C subsystem is not the >> same people maintaining the Rust abstractions, this switch might be >> valuable. It would allow making breaking changes to the C code of a >> subsystem without refactoring the Rust code in the same sitting. Rather > > That's why I asked Frederic to be a reviewer of Rust hrtimer API. In > longer-term, more and more people will get more or less Rust knowledge, > and I'd argue that's the direction we should head to. So my vision is a > significant amount of core kernel developers would be able to make C and > Rust changes at the same time. It's of course not mandatory, but it's > better collaboration. Having this switch does not prevent longer term plans or change directions of anything. It's simply a convenience feature made available. I also expect the future you envision. But it is an envisioned _future_. It is not the present reality. > >> than having to disable rust entirely - or going and commenting out lines >> in the kernel crate - I think it is better to provide an option to just >> disable building these particular bindings. >> >> This has nothing to do with general policies related to breakage between >> Rust and C code, and how to fix such breakage in a timely manner. It is >> simply a useful switch for disabling part of the build so that people >> can move on with their business, while someone else scrambles to fix >> whatever needs fixing on the Rust side. >> > > It's of course up to hrtimer maintainers. But I personally nack this > kconfig, because it's not necessary, and hrtimer API has been stable for > a while. Having the switch is fine for me, removing it is fine as well. It's just an added convenience that might come in handy. But having this kconfig very close to zero overhead, so I do not really understand your objection. I would like to better understand your reasoning. Best regards, Andreas Hindborg
Le Mon, Feb 24, 2025 at 08:52:35PM +0100, Andreas Hindborg a écrit : > > It's of course up to hrtimer maintainers. But I personally nack this > > kconfig, because it's not necessary, and hrtimer API has been stable for > > a while. > > Having the switch is fine for me, removing it is fine as well. It's just > an added convenience that might come in handy. But having this kconfig > very close to zero overhead, so I do not really understand your > objection. I would like to better understand your reasoning. If you choose to make a such a Kconfig switch, it would only make sense in order to spare some bytes when no drivers use it for example. But if you're afraid that the Rust binding is on the way while the core is changing some API then I guess simply disabling Rust would be enough for testing. I don't think it's necessary (unless it's strictly selected by drivers). But it's your call. Thanks. > > > Best regards, > Andreas Hindborg > >
"Frederic Weisbecker" <frederic@kernel.org> writes: > Le Mon, Feb 24, 2025 at 08:52:35PM +0100, Andreas Hindborg a écrit : >> > It's of course up to hrtimer maintainers. But I personally nack this >> > kconfig, because it's not necessary, and hrtimer API has been stable for >> > a while. >> >> Having the switch is fine for me, removing it is fine as well. It's just >> an added convenience that might come in handy. But having this kconfig >> very close to zero overhead, so I do not really understand your >> objection. I would like to better understand your reasoning. > > If you choose to make a such a Kconfig switch, it would only make sense > in order to spare some bytes when no drivers use it for example. But if > you're afraid that the Rust binding is on the way while the core is > changing some API then I guess simply disabling Rust would be enough for > testing. > > I don't think it's necessary (unless it's strictly selected by drivers). > But it's your call. I that case, I will drop it. Thanks for chiming in. Best regards, Andreas Hindborg
On Mon, Feb 24, 2025 at 08:52:35PM +0100, Andreas Hindborg wrote: > "Boqun Feng" <boqun.feng@gmail.com> writes: > > > On Mon, Feb 24, 2025 at 07:58:04PM +0100, Andreas Hindborg wrote: > >> > On Mon, Feb 24, 2025 at 05:45:03PM +0100, Miguel Ojeda wrote: > >> >> On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: > >> >> > > >> >> > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: > >> >> > > > >> >> > > side -- Andreas and I discussed it the other day. The description of > >> >> > > the issue has some lines, but perhaps the commit message could > >> >> > > >> >> > Do you have a link to the issue? > >> >> > >> >> Sorry, I meant "description of the symbol", i.e. the description field > >> >> in the patch. > >> >> > >> > > >> > Oh, I see. Yes, the patch description should provide more information > >> > about what the kconfig means for hrtimer maintainers' development. > >> > >> Right, I neglected to update the commit message. I will do that if we > >> have another version. > >> > >> > > >> >> > I asked because hrtimer API is always available regardless of the > >> >> > configuration, and it's such a core API, so it should always be there > >> >> > (Rust or C). > >> >> > >> >> It may not make sense for something that is always built on the C > >> >> side, yeah. I think the intention here may be that one can easily > >> >> disable it while "developing" a change on the C side. I am not sure > >> >> what "developing" means here, though, and we need to be careful -- > >> >> after all, Kconfig options are visible to users and they do not care > >> >> about that. > >> >> > >> > > >> > Personally, I don't think CONFIG_RUST_HRTIMER is necessarily because as > >> > you mentioned below, people can disable Rust entirely during > >> > "developing". > >> > > >> > And if I understand the intention correctly, the CONFIG_RUST_HRTIMER > >> > config provides hrtimer maintainers a way that they could disable Rust > >> > hrtimer abstraction (while enabling other Rust component) when they're > >> > developing a change on the C side, right? If so, it's hrtimer > >> > maintainers' call, and this patch should provide more information on > >> > this. > >> > > >> > Back to my personal opinion, I don't think this is necessary ;-) > >> > Particularly because I can fix if something breaks Rust side, and I'm > >> > confident and happy to do so for hrtimer ;-) > >> > >> As Miguel said, the idea for this came up in the past week in one of the > >> mega threads discussing rust in general. We had a lot of "what happens > >> if I change something in my subsystem and that breaks rust" kind of > >> discussions. > >> > > > > So far we haven't heard such a question from hrtimer maintainers, I > > would only add such a kconfig if explicitly requested. > > It gives flexibility and has no negative side effects. Of course, if it The negative side effects that I can think of: * It doubles the work for testing, it's a Kconfig after all, so every reasonable test run will have to run at least one build with it and one build without it combined with other configs. * It may compelicate other component. For example, if I would like use hrtimer in a doc test of a lock component (the component itself doesn't depend on hrtimer, so it exists with CONFIG_RUST_HRTIMER=n), because I would like to unlock something after a certain time. Now since CONFIG_RUST_HRTIMER can be unset, how would I write the test? #[cfg(CONFIG_RUST_HRTIMER)] <use the Rust timer> #[cfg(not(CONFIG_RUST_HRTIMER))] <use the C timer? with unsafe??> A new kconfig is not something free. We will need to cope with it in multiple places. > is unwanted, we can just remove it. But I would like to understand the > deeper rationale. > > > > > >> For subsystems where the people maintaining the C subsystem is not the > >> same people maintaining the Rust abstractions, this switch might be > >> valuable. It would allow making breaking changes to the C code of a > >> subsystem without refactoring the Rust code in the same sitting. Rather > > > > That's why I asked Frederic to be a reviewer of Rust hrtimer API. In > > longer-term, more and more people will get more or less Rust knowledge, > > and I'd argue that's the direction we should head to. So my vision is a > > significant amount of core kernel developers would be able to make C and > > Rust changes at the same time. It's of course not mandatory, but it's > > better collaboration. > > Having this switch does not prevent longer term plans or change > directions of anything. It's simply a convenience feature made > available. I also expect the future you envision. But it is an > envisioned _future_. It is not the present reality. > The reality is: we haven't heard hrtimer maintainers ask for this, right? I know you're trying to do something nice, I do appreciate your intention, but if hrtimer maintainers haven't asked for this, maybe it implies that they can handle or trust that wouldn't be a problem? > > > >> than having to disable rust entirely - or going and commenting out lines > >> in the kernel crate - I think it is better to provide an option to just > >> disable building these particular bindings. > >> > >> This has nothing to do with general policies related to breakage between > >> Rust and C code, and how to fix such breakage in a timely manner. It is > >> simply a useful switch for disabling part of the build so that people > >> can move on with their business, while someone else scrambles to fix > >> whatever needs fixing on the Rust side. > >> > > > > It's of course up to hrtimer maintainers. But I personally nack this > > kconfig, because it's not necessary, and hrtimer API has been stable for > > a while. > > Having the switch is fine for me, removing it is fine as well. It's just > an added convenience that might come in handy. But having this kconfig > very close to zero overhead, so I do not really understand your > objection. I would like to better understand your reasoning. > Hope my explanation above is helpful. Regards, Boqun > > Best regards, > Andreas Hindborg > >
"Boqun Feng" <boqun.feng@gmail.com> writes: > On Mon, Feb 24, 2025 at 08:52:35PM +0100, Andreas Hindborg wrote: >> "Boqun Feng" <boqun.feng@gmail.com> writes: >> >> > On Mon, Feb 24, 2025 at 07:58:04PM +0100, Andreas Hindborg wrote: >> >> > On Mon, Feb 24, 2025 at 05:45:03PM +0100, Miguel Ojeda wrote: >> >> >> On Mon, Feb 24, 2025 at 5:31 PM Boqun Feng <boqun.feng@gmail.com> wrote: >> >> >> > >> >> >> > On Mon, Feb 24, 2025 at 05:23:59PM +0100, Miguel Ojeda wrote: >> >> >> > > >> >> >> > > side -- Andreas and I discussed it the other day. The description of >> >> >> > > the issue has some lines, but perhaps the commit message could >> >> >> > >> >> >> > Do you have a link to the issue? >> >> >> >> >> >> Sorry, I meant "description of the symbol", i.e. the description field >> >> >> in the patch. >> >> >> >> >> > >> >> > Oh, I see. Yes, the patch description should provide more information >> >> > about what the kconfig means for hrtimer maintainers' development. >> >> >> >> Right, I neglected to update the commit message. I will do that if we >> >> have another version. >> >> >> >> > >> >> >> > I asked because hrtimer API is always available regardless of the >> >> >> > configuration, and it's such a core API, so it should always be there >> >> >> > (Rust or C). >> >> >> >> >> >> It may not make sense for something that is always built on the C >> >> >> side, yeah. I think the intention here may be that one can easily >> >> >> disable it while "developing" a change on the C side. I am not sure >> >> >> what "developing" means here, though, and we need to be careful -- >> >> >> after all, Kconfig options are visible to users and they do not care >> >> >> about that. >> >> >> >> >> > >> >> > Personally, I don't think CONFIG_RUST_HRTIMER is necessarily because as >> >> > you mentioned below, people can disable Rust entirely during >> >> > "developing". >> >> > >> >> > And if I understand the intention correctly, the CONFIG_RUST_HRTIMER >> >> > config provides hrtimer maintainers a way that they could disable Rust >> >> > hrtimer abstraction (while enabling other Rust component) when they're >> >> > developing a change on the C side, right? If so, it's hrtimer >> >> > maintainers' call, and this patch should provide more information on >> >> > this. >> >> > >> >> > Back to my personal opinion, I don't think this is necessary ;-) >> >> > Particularly because I can fix if something breaks Rust side, and I'm >> >> > confident and happy to do so for hrtimer ;-) >> >> >> >> As Miguel said, the idea for this came up in the past week in one of the >> >> mega threads discussing rust in general. We had a lot of "what happens >> >> if I change something in my subsystem and that breaks rust" kind of >> >> discussions. >> >> >> > >> > So far we haven't heard such a question from hrtimer maintainers, I >> > would only add such a kconfig if explicitly requested. >> >> It gives flexibility and has no negative side effects. Of course, if it > > The negative side effects that I can think of: > > * It doubles the work for testing, it's a Kconfig after all, so every > reasonable test run will have to run at least one build with it and > one build without it combined with other configs. > > * It may compelicate other component. For example, if I would like > use hrtimer in a doc test of a lock component (the component itself > doesn't depend on hrtimer, so it exists with CONFIG_RUST_HRTIMER=n), > because I would like to unlock something after a certain time. Now > since CONFIG_RUST_HRTIMER can be unset, how would I write the test? > > #[cfg(CONFIG_RUST_HRTIMER)] > <use the Rust timer> > #[cfg(not(CONFIG_RUST_HRTIMER))] > <use the C timer? with unsafe??> > > A new kconfig is not something free. We will need to cope with it in > multiple places. Alright, those are valid arguments. > >> is unwanted, we can just remove it. But I would like to understand the >> deeper rationale. >> >> >> > >> >> For subsystems where the people maintaining the C subsystem is not the >> >> same people maintaining the Rust abstractions, this switch might be >> >> valuable. It would allow making breaking changes to the C code of a >> >> subsystem without refactoring the Rust code in the same sitting. Rather >> > >> > That's why I asked Frederic to be a reviewer of Rust hrtimer API. In >> > longer-term, more and more people will get more or less Rust knowledge, >> > and I'd argue that's the direction we should head to. So my vision is a >> > significant amount of core kernel developers would be able to make C and >> > Rust changes at the same time. It's of course not mandatory, but it's >> > better collaboration. >> >> Having this switch does not prevent longer term plans or change >> directions of anything. It's simply a convenience feature made >> available. I also expect the future you envision. But it is an >> envisioned _future_. It is not the present reality. >> > > The reality is: we haven't heard hrtimer maintainers ask for this, > right? I know you're trying to do something nice, I do appreciate your > intention, but if hrtimer maintainers haven't asked for this, maybe it > implies that they can handle or trust that wouldn't be a problem? Thanks for explaining. For reference, we do not have this feature in block, and it was not a problem yet. Let's await hrtimer maintainers and follow their lead. Best regards, Andreas Hindborg
© 2016 - 2026 Red Hat, Inc.