rust: use Delta instead of raw jiffies for timeouts and delays
Subsystems (4)
v6 cover rust: use Delta instead of raw jiffies for timeouts and delays
From: FUJITA Tomonori <[email protected]>
CondVar::wait_interruptible_timeout() and Queue::enqueue_delayed() use a raw jiffies count (a plain c_ulong alias with no type safety). Callers have to know on their own that the value meant jiffies and convert to/from it themselves, which is easy to get wrong (e.g. passing a millisecond value where a jiffies value is expected).
Both APIs just take a span of time so, they can use the Delta type instead.
This series makes Delta generic over its time unit with Nsec and Jiffy types, switches CondVar and Queue to use Delta instead of raw jiffies (updating binder's ioctl_freeze(), the only caller of wait_interruptible_timeout()), and then removes the now-unused Jiffies and Msecs type aliases.
---
v6:
- Make Nsec/Jiffy zero-variant enums so they can't be constructed
- Rename Delta::to_jiffies() to to_jiffies_timeout() to reflect its timeout semantics
v5: https://lore.kernel.org/rust-for-linux/[email protected]/
- Fix as_millis_ceil() rounding near i64::MAX
- Import Delta instead of using kernel::time::Delta twice
v4: https://lore.kernel.org/rust-for-linux/[email protected]/
- Make Delta generic over its time unit with Nsec and Jiffy types
v3: https://lore.kernel.org/rust-for-linux/[email protected]/
- Add new Jiffies type and convert the APIs to take impl Into<Jiffies>
v2: https://lore.kernel.org/rust-for-linux/[email protected]/
- Fix potential overflow in from_jiffies()
- Fix inflating bug in as_jiffies_ceil()
- Add a patch to convert enqueue_delayed()
- Add a patch to remove Jiffies/Msecs aliases
v1: https://lore.kernel.org/rust-for-linux/[email protected]/
FUJITA Tomonori (7):
rust: time: make Delta generic over its time unit
rust: time: add jiffies time unit for Delta
rust: time: add Delta::as_millis_ceil()
rust: time: add Delta::to_jiffies_timeout() for timeout conversion
rust: workqueue: take a Delta<Jiffy> for the enqueue delay
rust: sync: condvar: use Delta<Jiffy> for timeout and result
rust: time: remove unused Jiffies/Msecs helpers
drivers/android/binder/process.rs | 7 +- rust/kernel/sync/condvar.rs | 29 ++++-- rust/kernel/time.rs | 159 +++++++++++++++++++++++------- rust/kernel/workqueue.rs | 12 ++- 4 files changed, 154 insertions(+), 53 deletions(-)
base-commit: dc01dfb37b34beeefcfe1c3055364d41a4070c7e
Signature · 1 line
2.43.0
PATCH v6 1/7 rust: time: make Delta generic over its time unit
From: FUJITA Tomonori <[email protected]>
Delta hardcodes its value as i64 nanoseconds. A later patch adds a jiffies span, whose natural representation is isize jiffies rather than i64 nanoseconds, and a separate type per unit would duplicate the arithmetic and comparison machinery.
Make Delta generic over its time unit so the jiffies span can reuse that machinery. The nanosecond Delta keeps its current representation and API via the default unit parameter, so no functional change. users.
--- rust/kernel/time.rs | 72 ++++++++++++++++++++++++++++++--------------- 1 file changed, 48 insertions(+), 24 deletions(-)
rust/kernel/time.rs +48 -24
@@ -246,7 +246,7 @@ impl<C: ClockSource> ops::Sub for Instant<C> {#[inline] fn sub (self, other:Instant <C >) ->Delta {Delta { - nanos: self.inner - other.inner, + value: self.inner - other.inner, } } }
@@ -258,7 +258,7 @@ impl<T: ClockSource> ops::Add<Delta> for Instant<T> {fn add (self, rhs:Delta ) ->Self ::Output {// INVARIANT: With arithmetic over/underflow checks enabled, this will panic if we overflow // (e.g. go above `KTIME_MAX`) -let res = self.inner + rhs.nanos; +let res = self.inner + rhs.value;// INVARIANT: With overflow checks enabled, we verify here that the value is >= 0 #[cfg( CONFIG_RUST_OVERFLOW_CHECKS )]
@@ -278,7 +278,7 @@ impl<T: ClockSource> ops::Sub<Delta> for Instant<T> {fn sub (self, rhs:Delta ) ->Self ::Output {// INVARIANT: With arithmetic over/underflow checks enabled, this will panic if we overflow // (e.g. go above `KTIME_MAX`) -let res = self.inner - rhs.nanos; +let res = self.inner - rhs.value;// INVARIANT: With overflow checks enabled, we verify here that the value is >= 0 #[cfg( CONFIG_RUST_OVERFLOW_CHECKS )]
@@ -291,14 +291,38 @@ fn sub(self, rhs: Delta) -> Self::Output { } } +mod private { +pub trait Sealed {} + +impl Sealed for super ::Nsec {} +} + +/// A trait for time units. +pub trait TimeUnit : private::Sealed { +/// The underlying representation of the time unit. +type Repr :Copy +Clone +PartialEq +PartialOrd +Eq +Ord + core::fmt::Debug ; +} + +/// A time unit of nanoseconds. +/// +/// A [`Delta<Nsec>`] stores its value as `i64` nanoseconds and can represent +/// any `i64` value, including negative, zero, and positive numbers. +#[derive( Copy , Clone , PartialEq , PartialOrd , Eq , Ord , Debug )] +pub enum Nsec {} + +impl TimeUnit for Nsec { +type Repr =i64 ; +} +/// A span of time. /// -/// This struct represents a span of time, with its value stored as nanoseconds. -/// The value can represent any valid i64 value, including negative, zero, and -/// positive numbers. +/// The span is stored in the unit given by the type parameter `U` (see +/// [`TimeUnit`]); its value has type `U::Repr`. `U` defaults to [`Nsec`], so a +/// plain [`Delta`] is a span in nanoseconds. The value can be negative, zero, or +/// positive. #[derive( Copy , Clone , PartialEq , PartialOrd , Eq , Ord , Debug )] -pub struct Delta { - nanos:i64 , +pub struct Delta <U :TimeUnit =Nsec > { + value:U ::Repr , }impl ops::Add for Delta {
@@ -307,7 +331,7 @@ impl ops::Add for Delta {#[inline] fn add (self, rhs:Self ) ->Self {Self { - nanos: self.nanos + rhs.nanos, + value: self.value + rhs.value, } } }
@@ -315,7 +339,7 @@ fn add(self, rhs: Self) -> Self {impl ops::AddAssign for Delta {#[inline] fn add_assign (&mut self, rhs:Self ) { - self.nanos += rhs.nanos; + self.value += rhs.value; } }
@@ -325,7 +349,7 @@ impl ops::Sub for Delta {#[inline] fn sub (self, rhs:Self ) ->Self ::Output {Self { - nanos: self.nanos - rhs.nanos, + value: self.value - rhs.value, } } }
@@ -333,7 +357,7 @@ fn sub(self, rhs: Self) -> Self::Output {impl ops::SubAssign for Delta {#[inline] fn sub_assign (&mut self, rhs:Self ) { - self.nanos -= rhs.nanos; + self.value -= rhs.value; } }
@@ -343,7 +367,7 @@ impl ops::Mul<i64> for Delta {#[inline] fn mul (self, rhs:i64 ) ->Self ::Output {Self { - nanos: self.nanos * rhs, + value: self.value * rhs, } } }
@@ -351,7 +375,7 @@ fn mul(self, rhs: i64) -> Self::Output {impl ops::MulAssign <i64 >for Delta {#[inline] fn mul_assign (&mut self, rhs:i64 ) { - self.nanos *= rhs; + self.value *= rhs; } }
@@ -362,25 +386,25 @@ impl ops::Div for Delta {fn div (self, rhs:Self ) ->Self ::Output {#[cfg( CONFIG_64BIT )] { - self.nanos / rhs.nanos + self.value / rhs.value }#[cfg(not( CONFIG_64BIT ))] {// SAFETY: This function is always safe to call regardless of the input values -unsafe { bindings::div64_s64 (self.nanos, rhs.nanos) } +unsafe { bindings::div64_s64 (self.value, rhs.value) } } } }impl Delta {/// A span of time equal to zero. -pub const ZERO :Self =Self { nanos:0 }; +pub const ZERO :Self =Self { value:0 };/// Create a new [`Delta`] from a number of nanoseconds. #[inline] pub const fn from_nanos (nanos:i64 ) ->Self { -Self { nanos } +Self { value: nanos } }/// Create a new [`Delta`] from a number of microseconds.
@@ -391,7 +415,7 @@ pub const fn from_nanos(nanos: i64) -> Self {#[inline] pub const fn from_micros (micros:i64 ) ->Self {Self { - nanos: micros.saturating_mul (NSEC_PER_USEC ), + value: micros.saturating_mul (NSEC_PER_USEC ), } }
@@ -403,7 +427,7 @@ pub const fn from_micros(micros: i64) -> Self {#[inline] pub const fn from_millis (millis:i64 ) ->Self {Self { - nanos: millis.saturating_mul (NSEC_PER_MSEC ), + value: millis.saturating_mul (NSEC_PER_MSEC ), } }
@@ -415,7 +439,7 @@ pub const fn from_millis(millis: i64) -> Self {#[inline] pub const fn from_secs (secs:i64 ) ->Self {Self { - nanos: secs.saturating_mul (NSEC_PER_SEC ), + value: secs.saturating_mul (NSEC_PER_SEC ), } }
@@ -434,7 +458,7 @@ pub fn is_negative(self) -> bool {/// Return the number of nanoseconds in the [`Delta`]. #[inline] pub const fn as_nanos (self) ->i64 { - self.nanos + self.value }/// Return the smallest number of microseconds greater than or equal
@@ -484,7 +508,7 @@ pub fn rem_nanos(self, dividend: i32) -> Self {#[cfg( CONFIG_64BIT )] {Self { - nanos: self.as_nanos () % i64::from (dividend), + value: self.as_nanos () % i64::from (dividend), } }
@@ -496,7 +520,7 @@ pub fn rem_nanos(self, dividend: i32) -> Self {unsafe { bindings::div_s64_rem (self.as_nanos (), dividend, &mut rem) };Self { - nanos: i64::from (rem), + value: i64::from (rem), } } }
Signature · 1 line
2.43.0
Re: [PATCH v6 1/7] rust: time: make Delta generic over its time unit
Quoted 7 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Delta hardcodes its value as i64 nanoseconds. A later patch adds a jiffies span, whose natural representation is isize jiffies rather than i64 nanoseconds, and a separate type per unit would duplicate the arithmetic and comparison machinery.
Quoted 7 lines
Make Delta generic over its time unit so the jiffies span can reuse that machinery. The nanosecond Delta keeps its current representation and API via the default unit parameter, so no functional change. users.
Reviewed-by Gary Guo <[email protected]>Signed-off-by FUJITA Tomonori <[email protected]>
Best regards,
Andreas Hindborg
PATCH v6 2/7 rust: time: add jiffies time unit for Delta
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
Add a Jiffy time unit with isize as its representation and provide Delta<Jiffy>::from_jiffies() and as_jiffies() as the unit-specific constructor and accessor, mirroring from_nanos()/as_nanos() on the nanosecond Delta.
Represent the jiffies span as isize: Delta is a signed span (nanoseconds use i64) and, as a timeout, the value only needs to reach MAX_JIFFY_OFFSET ((LONG_MAX >> 1) - 1). isize is signed and matches the kernel's c_long, so it meets both.
--- rust/kernel/time.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)
rust/kernel/time.rs +26 -0
@@ -295,6 +295,7 @@ mod private {pub trait Sealed {}impl Sealed for super ::Nsec {} +impl Sealed for super ::Jiffy {} }/// A trait for time units.
@@ -314,6 +315,17 @@ impl TimeUnit for Nsec {type Repr =i64 ; } +/// A time unit of jiffies. +/// +/// A [`Delta<Jiffy>`] stores its value as `isize` jiffies and can represent +/// any `isize` value, including negative, zero, and positive numbers. +#[derive( Copy , Clone , PartialEq , PartialOrd , Eq , Ord , Debug )] +pub enum Jiffy {} + +impl TimeUnit for Jiffy { +type Repr =isize ; +} +/// A span of time. /// /// The span is stored in the unit given by the type parameter `U` (see
@@ -325,6 +337,20 @@ pub struct Delta<U: TimeUnit = Nsec> { value: U::Repr, } +impl Delta <Jiffy > { +/// Create a new [`Delta`] from a number of jiffies. +#[inline] +pub const fn from_jiffies (jiffies:isize ) ->Self { +Self { value: jiffies } + } + +/// Return the number of jiffies in the [`Delta`]. +#[inline] +pub const fn as_jiffies (self) ->isize { + self.value + } +} +impl ops::Add for Delta {type Output =Self ;
Signature · 1 line
2.43.0
Re: [PATCH v6 2/7] rust: time: add jiffies time unit for Delta
Quoted 7 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Add a Jiffy time unit with isize as its representation and provide Delta<Jiffy>::from_jiffies() and
as_jiffies()as the unit-specific constructor and accessor, mirroring from_nanos()/as_nanos() on the nanosecond Delta.
Quoted 7 lines
Represent the jiffies span as isize: Delta is a signed span (nanoseconds use i64) and, as a timeout, the value only needs to reach
MAX_JIFFY_OFFSET((LONG_MAX>> 1) - 1). isize is signed and matches the kernel'sc_long, so it meets both.Reviewed-by Gary Guo <[email protected]>Signed-off-by FUJITA Tomonori <[email protected]>
Best regards,
Andreas Hindborg
PATCH v6 3/7 rust: time: add Delta::as_millis_ceil()
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
Add a ceiling variant, mirroring the existing as_micros_ceil() since the existing as_millis() truncates towards zero.
--- rust/kernel/time.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)
rust/kernel/time.rs +26 -0
@@ -525,6 +525,32 @@ pub fn as_millis(self) -> i64 { } } +/// Return the smallest number of milliseconds greater than or equal +/// to the value in the [`Delta`]. +#[inline] +pub fn as_millis_ceil (self) ->i64 { +// Only positive values need to be rounded up: truncating division already +// rounds towards zero, i.e. up, for negative values. +// +// The usual `(nanos + d - 1) / d` is not used because the addition overflows +// once `nanos` exceeds `i64::MAX - (d - 1)`; saturating the addition instead +// would drop the rounding bias and return a result one unit too small. +let n = self.as_nanos (); + +let (n, add) =if n >0 { (n -1 ,1 ) }else { (n,0 ) }; + +#[cfg( CONFIG_64BIT )] + { + n /NSEC_PER_MSEC + add + } + +#[cfg(not( CONFIG_64BIT ))] +// SAFETY: It is always safe to call `ktime_to_ms()` with any value. +unsafe { + bindings::ktime_to_ms (n) + add + } + } +/// Return `self % dividend` where `dividend` is in nanoseconds. /// /// The kernel doesn't have any emulation for `s64 % s64` on 32 bit platforms, so this is
Signature · 1 line
2.43.0
Re: [PATCH v6 3/7] rust: time: add Delta::as_millis_ceil()
Quoted 7 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Add a ceiling variant, mirroring the existing
as_micros_ceil()since the existingas_millis()truncates towards zero.Reviewed-by Gary Guo <[email protected]>Signed-off-by FUJITA Tomonori <[email protected]>
Best regards,
Andreas Hindborg
PATCH v6 4/7 rust: time: add Delta::to_jiffies_timeout() for timeout conversion
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
Add Delta<Nsec>::to_jiffies_timeout() conversion that rounds up so the resulting timeout is never shorter than the requested span, clamps a negative span to an immediate timeout, and saturates an overlong span to the kernel's MAX_JIFFY_OFFSET "wait forever" value.
--- rust/kernel/time.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
rust/kernel/time.rs +21 -0
@@ -551,6 +551,27 @@ pub fn as_millis_ceil(self) -> i64 { } } +/// Convert this span to a [`Delta<Jiffy>`] suitable for use as a timeout. +/// +/// The value is rounded up to the next whole jiffy, so the resulting +/// timeout is never shorter than `self` (as `msecs_to_jiffies()` does). +/// A negative span clamps to zero jiffies (an immediate timeout). +#[inline] +pub fn to_jiffies_timeout (self) ->Delta <Jiffy > { +let msecs = self.as_millis_ceil (); + +// CAST: `msecs` is clamped to `0..=c_uint::MAX`, so it is non-negative and +// fits in `c_uint`. +let msecs = msecs.clamp (0 , i64::from (crate ::ffi::c_uint::MAX ))as crate ::ffi::c_uint ; + +// SAFETY: `__msecs_to_jiffies()` is always safe to call. +let jiffies =unsafe { bindings::__msecs_to_jiffies (msecs) }; + +// CAST: `__msecs_to_jiffies()` returns a value in `0..=MAX_JIFFY_OFFSET`, i.e. +// `((LONG_MAX >> 1) - 1)`, which is non-negative and well within `isize`. +Delta ::<Jiffy >::from_jiffies (jiffiesas isize ) + } +/// Return `self % dividend` where `dividend` is in nanoseconds. /// /// The kernel doesn't have any emulation for `s64 % s64` on 32 bit platforms, so this is
Signature · 1 line
2.43.0
Re: [PATCH v6 4/7] rust: time: add Delta::to_jiffies_timeout() for timeout conversion
Quoted 9 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Add Delta<Nsec>::to_jiffies_timeout() conversion that rounds up so the resulting timeout is never shorter than the requested span, clamps a negative span to an immediate timeout, and saturates an overlong span to the kernel's
MAX_JIFFY_OFFSET"wait forever" value.Reviewed-by Gary Guo <[email protected]>Signed-off-by FUJITA Tomonori <[email protected]>
Best regards,
Andreas Hindborg
Gary Guo
maintainerRe: [PATCH v6 4/7] rust: time: add Delta::to_jiffies_timeout() for timeout conversion
In reply to FUJITA TomonoriQuoted 31 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Add Delta<Nsec>::to_jiffies_timeout() conversion that rounds up so the resulting timeout is never shorter than the requested span, clamps a negative span to an immediate timeout, and saturates an overlong span to the kernel's
MAX_JIFFY_OFFSET"wait forever" value.Reviewed-by Gary Guo <[email protected]>Signed-off-by FUJITA Tomonori <[email protected]>--- rust/kernel/time.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)rust/kernel/time.rs +10
-0@@ -551,6 +551,27 @@ pub fn as_millis_ceil(self) -> i64 { } } +/// Convert this span to a [`Delta<Jiffy>`] suitable for use as a timeout. +/// +/// The value is rounded up to the next whole jiffy, so the resulting +/// timeout is never shorter than `self` (as `msecs_to_jiffies()` does). +/// A negative span clamps to zero jiffies (an immediate timeout). +#[inline] +pub fn to_jiffies_timeout (self) ->Delta <Jiffy > { +let msecs = self.as_millis_ceil (); + +// CAST: `msecs` is clamped to `0..=c_uint::MAX`, so it is non-negative and
rust/kernel/time.rs pub fn as_millis_ceil(self) -> i64 { · line 573
Quoted 10 lines
rust/kernel/time.rs +10
-0+// fits in `c_uint`. +let msecs = msecs.clamp (0 , i64::from (crate ::ffi::c_uint::MAX ))as crate ::ffi::c_uint ; + +// SAFETY: `__msecs_to_jiffies()` is always safe to call. +let jiffies =unsafe { bindings::__msecs_to_jiffies (msecs) }; + +// CAST: `__msecs_to_jiffies()` returns a value in `0..=MAX_JIFFY_OFFSET`, i.e. +// `((LONG_MAX >> 1) - 1)`, which is non-negative and well within `isize`. +Delta ::<Jiffy >::from_jiffies (jiffiesas isize ) + }
I think it's fine to merge this as is, but I still want this to be simplified to not have two divisions eventually.
Something like
fn to_jiffies(self) -> Delta<Jiffy> {
// implement using nsecs_to_jiffies
}
fn to_jiffies_ceil(self) -> Delta<Jiffy> {
// implement with to_jiffies
}
fn to_jiffies_timeout(self) -> Delta<Jiffy> {
// implement with to_jiffies_timeout and clamp to 0
}Perhaps?
Best,
Gary
Quoted 4 lines
rust/kernel/time.rs +1
-0+/// Return `self % dividend` where `dividend` is in nanoseconds. /// /// The kernel doesn't have any emulation for `s64 % s64` on 32 bit platforms, so this is
Re: [PATCH v6 4/7] rust: time: add Delta::to_jiffies_timeout() for timeout conversion
In reply to FUJITA Tomonorirust/kernel/time.rs pub fn as_millis_ceil(self) -> i64 { · line 571
Quoted 3 lines · FUJITA Tomonori
rust/kernel/time.rs +2
-0+// CAST: `__msecs_to_jiffies()` returns a value in `0..=MAX_JIFFY_OFFSET`, i.e. +// `((LONG_MAX >> 1) - 1)`, which is non-negative and well within `isize`.
I don't think I can pick up this one, because this comment isn't true for arm32 HZ=1000, i.e. __msecs_to_jiffies() can be higher than MAX_JIFFY_OFFSET and can actually reach isize::MAX.
Which in turns means that we don't saturate to MAX_JIFFY_OFFSET like the commit message mentions.
It also makes the method non-monotonic, i.e. going from:
Delta::from_millis(i64::from(i32::MAX)).to_jiffies_timeout()
to:
Delta::from_millis(i64::from(i32::MAX) + 1).to_jiffies_timeout()
means a big drop, which was not what I would naively expect from the method.
Could the documentation clarify what the saturation is? And add some doctests? (Also to the previous patch's function if possible).
Thanks!
Cheers,
Miguel
Re: [PATCH v6 4/7] rust: time: add Delta::to_jiffies_timeout() for timeout conversion
Quoted 8 lines · On Tue, 11 Aug 2026 08:54:07 +0200 Miguel Ojeda…
rust/kernel/time.rs pub fn as_millis_ceil(self) -> i64 { · line 571
Quoted 3 lines · FUJITA Tomonori
rust/kernel/time.rs +2
-0+// CAST: `__msecs_to_jiffies()` returns a value in `0..=MAX_JIFFY_OFFSET`, i.e. +// `((LONG_MAX >> 1) - 1)`, which is non-negative and well within `isize`. I don't think I can pick up this one, because this comment isn't true for arm32
HZ=1000, i.e.__msecs_to_jiffies()can be higher thanMAX_JIFFY_OFFSETand can actually reachisize::MAX.
You are right, thanks. I'll fix the saturation, the comment and the commit message in the next version.
Quoted 2 lines
Could the documentation clarify what the saturation is? And add some doctests? (Also to the previous patch's function if possible).
Sure, for both functions. As we discussed before, I'll add examples too:
Re: [PATCH v6 4/7] rust: time: add Delta::to_jiffies_timeout() for timeout conversion
Quoted 3 lines · FUJITA Tomonori
You are right, thanks. I'll fix the saturation, the comment and the commit message in the next version.
Thanks!
By the way, please check the branch since I picked the earlier ones already -- I didn't send the notifications yet.
Cheers,
Miguel
PATCH v6 5/7 rust: workqueue: take a Delta<Jiffy> for the enqueue delay
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
enqueue_delayed() takes the delay as a raw Jiffies (c_ulong). That is the C representation rather than a kernel time type, so it neither carries the unit in its type nor composes with the Delta arithmetic used elsewhere for expressing spans, and it forces callers to hand the API a bare integer.
Change the delay parameter to Delta<Jiffy> so a delay is expressed in the same time vocabulary as the rest of the kernel crate. A signed Delta can be negative, so clamp it to zero before handing it to the C side, which keeps "no delay" the natural meaning of a non-positive span.
--- rust/kernel/workqueue.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
rust/kernel/workqueue.rs +9 -3
@@ -171,7 +171,7 @@//! /// This method will enqueue the struct for execution on the system workqueue, where its value //! /// will be printed 12 jiffies later. //! fn print_later(val: Arc<MyStruct>) { -//! let _ = workqueue::system().enqueue_delayed(val, 12); +//! let _ = workqueue::system().enqueue_delayed(val, kernel::time::Delta::from_jiffies(12)); //! } //! //! /// It is also possible to use the ordinary `enqueue` method together with `DelayedWork`. This
@@ -197,7 +197,10 @@ Arc, LockClassKey, // }, - time::Jiffies, + time::{ + Delta, + Jiffy, // + }, types::Opaque, };use core::{marker::PhantomData , ptr::NonNull };
@@ -303,11 +306,14 @@ pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput/// This may fail if the work item is already enqueued in a workqueue. /// /// The work item will be submitted using `WORK_CPU_UNBOUND`. -pub fn enqueue_delayed <W ,const ID :u64 >(&self, w:W , delay:Jiffies ) ->W ::EnqueueOutput +pub fn enqueue_delayed <W ,const ID :u64 >(&self, w:W , delta:Delta <Jiffy >) ->W ::EnqueueOutput where W :RawDelayedWorkItem <ID > +Send + 'static, {let queue_ptr = self.0 .get (); +// CAST: A negative delay is clamped to `0`, so the value is non-negative +// and fits in `c_ulong`. +let delay = delta.as_jiffies ().max (0 )as ffi::c_ulong ;// SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other // `__enqueue` requirements are not relevant since `W` is `Send` and static.
Signature · 1 line
2.43.0
PATCH v6 6/7 rust: sync: condvar: use Delta<Jiffy> for timeout and result
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
wait_interruptible_timeout() takes the timeout as a raw Jiffies and reports the remaining time as raw Jiffies in CondVarTimeoutResult. That is the C representation rather than a kernel time type, so it neither carries the unit in its type nor composes with the Delta spans used elsewhere, and it pushes the unsigned-to-signed conversion onto callers.
Switch the parameter and the result fields to Delta<Jiffy>. So a delay is expressed in the same time vocabulary as the rest of the kernel crate.
--- drivers/android/binder/process.rs | 7 ++++--- rust/kernel/sync/condvar.rs | 29 ++++++++++++++++++++--------- 2 files changed, 24 insertions(+), 12 deletions(-)
drivers/android/binder/process.rs +4 -3
@@ -33,6 +33,7 @@ Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock, UniqueArc, }, task::Task, + time::Delta, uaccess::{UserSlice, UserSliceReader}, uapi, workqueue::{self, Work},
@@ -1482,8 +1483,8 @@ pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { inner.is_frozen =IsFrozen ::InProgress ;if info.timeout_ms >0 { -let mut jiffies = kernel::time::msecs_to_jiffies (info.timeout_ms); -while jiffies >0 { +let mut jiffies =Delta ::from_millis (info.timeout_ms.into ()).to_jiffies_timeout (); +while jiffies.as_jiffies () >0 {if inner.outstanding_txns ==0 {break ; }
@@ -1500,7 +1501,7 @@ pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { jiffies = remaining; } CondVarTimeoutResult::Timeout => { - jiffies =0 ; + jiffies =Delta ::from_jiffies (0 ); } } }
rust/kernel/sync/condvar.rs +20 -9
@@ -12,7 +12,10 @@ task::{MAX_SCHEDULE_TIMEOUT ,TASK_FREEZABLE ,TASK_INTERRUPTIBLE ,TASK_NORMAL ,TASK_UNINTERRUPTIBLE , }, - time::Jiffies, + time::{ + Delta, + Jiffy, // + }, types::Opaque, };use core::{marker::PhantomPinned , pin::Pin , ptr};
@@ -186,15 +189,23 @@ pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>(pub fn wait_interruptible_timeout <T : ?Sized ,B :Backend >( &self, guard: &mut Guard <'_,T ,B >, - jiffies:Jiffies , + delta:Delta <Jiffy >, ) ->CondVarTimeoutResult { -let jiffies = jiffies.try_into ().unwrap_or (MAX_SCHEDULE_TIMEOUT ); -let res = self.wait_internal (TASK_INTERRUPTIBLE , guard, jiffies); +let jiffies = delta.as_jiffies (); +let res = self.wait_internal ( +TASK_INTERRUPTIBLE , + guard, + jiffies.clamp (0 ,MAX_SCHEDULE_TIMEOUT ), + ); -match (resas Jiffies ,crate ::current!().signal_pending ()) { - (jiffies,true ) =>CondVarTimeoutResult ::Signal { jiffies }, +match (res,crate ::current!().signal_pending ()) { + (jiffies,true ) =>CondVarTimeoutResult ::Signal { + jiffies:Delta ::from_jiffies (jiffies), + }, (0 ,false ) =>CondVarTimeoutResult ::Timeout , - (jiffies,false ) =>CondVarTimeoutResult ::Woken { jiffies }, + (jiffies,false ) =>CondVarTimeoutResult ::Woken { + jiffies:Delta ::from_jiffies (jiffies), + }, } }
@@ -248,11 +259,11 @@ pub enum CondVarTimeoutResult {/// Somebody woke us up. Woken { /// Remaining sleep duration. - jiffies: Jiffies, + jiffies: Delta<Jiffy>, },/// A signal occurred. Signal {/// Remaining sleep duration. - jiffies:Jiffies , + jiffies: Delta<Jiffy>, }, }
Signature · 1 line
2.43.0
PATCH v6 7/7 rust: time: remove unused Jiffies/Msecs helpers
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
CondVar's wait_interruptible_timeout() and workqueue's enqueue_delayed() have both moved from raw jiffies counts to Delta, so nothing in the tree calls msecs_to_jiffies() or uses the Jiffies and Msecs aliases anymore.
--- rust/kernel/time.rs | 14 -------------- 1 file changed, 14 deletions(-)
rust/kernel/time.rs +0 -14
@@ -39,20 +39,6 @@/// The number of nanoseconds per second. pub const NSEC_PER_SEC :i64 = bindings::NSEC_PER_SEC as i64 ; -/// The time unit of Linux kernel. One jiffy equals (1/HZ) second. -pub type Jiffies =crate ::ffi::c_ulong ; - -/// The millisecond time unit. -pub type Msecs =crate ::ffi::c_uint ; - -/// Converts milliseconds to jiffies. -#[inline] -pub fn msecs_to_jiffies (msecs:Msecs ) ->Jiffies { -// SAFETY: The `__msecs_to_jiffies` function is always safe to call no -// matter what the argument is. -unsafe { bindings::__msecs_to_jiffies (msecs) } -} -/// Trait for clock sources. /// /// Selection of the clock source depends on the use case. In some cases the usage of a
Signature · 1 line
2.43.0
Miguel Ojeda
AppliedQuoted 4 lines · FUJITA Tomonori
rust: time: make Delta generic over its time unit
rust: time: add jiffies time unit for Delta
rust: time: addDelta::as_millis_ceil()
Applied to rust-next -- thanks everyone!
[ Reworded to remove stray word. Added intra-doc links. - Miguel ]
[ Added intra-doc links. - Miguel ]
Cheers,
Miguel