rust: use Delta instead of raw jiffies for timeouts and delays
Subsystems (3)
v7 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 means 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 Delta<Jiffy> instead. The condvar patch also updates binder's ioctl_freeze(), the only caller of wait_interruptible_timeout().
This series is based on timekeeping-next, because the binder change uses Delta::to_jiffies_timeout(). The workqueue patch conflicts with Danilo's workqueue series [1], which also changes the signature of enqueue_delayed(). The conflict is trivial.
Binder and workqueue maintainers, could you take a look at the changes to your code? Andreas and Boqun, which tree should this series go through?
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
---
v7:
- Drop patches 1-3, merged in v7.3-rc1
- Drop patch 4, reworked and applied to timekeeping-next
- Drop patch 7, rust/kernel/serdev.rs now uses the Jiffies alias
- Rebase on timekeeping-next
- workqueue: keep the parameter name delay
- workqueue: document that a negative delay is treated as zero
- condvar: document that a negative timeout is treated as zero
- Reword the commit messages of both patches. The condvar one now
describes how the binder freeze timeout changes for 2^31 ms or more
v6: https://lore.kernel.org/rust-for-linux/[email protected]/
- 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 (2):
rust: workqueue: take a Delta<Jiffy> for the enqueue delay
rust: sync: condvar: use Delta<Jiffy> for timeout and result
drivers/android/binder/process.rs | 7 ++++--- rust/kernel/sync/condvar.rs | 31 ++++++++++++++++++++++--------- rust/kernel/workqueue.rs | 14 +++++++++++--- 3 files changed, 37 insertions(+), 15 deletions(-)
base-commit: 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38
Signature · 1 line
2.43.0
PATCH v7 1/2 rust: workqueue: take a Delta<Jiffy> for the enqueue delay
From: FUJITA Tomonori <[email protected]>
enqueue_delayed() takes the delay as a raw Jiffies, which is a c_ulong alias. The type does not show the unit, so callers pass a bare integer.
Take the delay as Delta<Jiffy> instead. A caller that already has a value in jiffies passes it without conversion. A caller that has a Delta in nanoseconds converts it with Delta::to_jiffies_timeout(), which rounds up, so a short delay does not become zero.
Delta<Jiffy> is signed, but queue_delayed_work_on() takes an unsigned long. Clamp a negative delay to zero, so it means "no delay" instead of a very long delay.
--- rust/kernel/workqueue.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
rust/kernel/workqueue.rs +11 -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,16 @@ 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 +/// +/// A negative delay is treated as zero. +pub fn enqueue_delayed <W ,const ID :u64 >(&self, w:W , delay: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 = isize::max (delay.as_jiffies (),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 v7 2/2 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 CondVarTimeoutResult reports the remaining time as a raw Jiffies. The type does not show the unit.
Switch the parameter and the result fields to Delta<Jiffy>, in the same way as enqueue_delayed().
Delta<Jiffy> is signed, but schedule_timeout() prints an error and a stack dump for a negative timeout. Clamp a negative timeout to zero, so it means an immediate timeout.
Update the only user, binder. It now converts the freeze timeout with Delta::to_jiffies_timeout() instead of msecs_to_jiffies(). Both round up, so a short timeout does not become zero. They differ only for a very long timeout. msecs_to_jiffies() returns MAX_JIFFY_OFFSET for 2^31 ms (about 24.9 days) or more, but to_jiffies_timeout() converts such a value like any other value.
--- drivers/android/binder/process.rs | 7 ++++--- rust/kernel/sync/condvar.rs | 31 ++++++++++++++++++++++--------- 2 files changed, 26 insertions(+), 12 deletions(-)
drivers/android/binder/process.rs +4 -3
@@ -35,6 +35,7 @@ Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SetOnce, SpinLock, UniqueArc, }, task::{Pid, Task}, + time::Delta, uaccess::{UserSlice, UserSliceReader}, uapi, workqueue::{self, Work},
@@ -1549,8 +1550,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 ; }
@@ -1567,7 +1568,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 +22 -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};
@@ -182,19 +185,29 @@ pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>(/// Atomically releases the given lock (whose ownership is proven by the guard) and puts the /// thread to sleep. It wakes up when notified by [`CondVar::notify_one`] or /// [`CondVar::notify_all`], or when a timeout occurs, or when the thread receives a signal. +/// +/// A negative timeout is treated as zero. #[must_use = "wait_interruptible_timeout returns if a signal is pending, so the caller must check the return value" ] 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 +261,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
Gary Guo
maintainerRe: [PATCH v7 2/2] rust: sync: condvar: use Delta<Jiffy> for timeout and result
Quoted 51 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
wait_interruptible_timeout()takes the timeout as a raw Jiffies, and CondVarTimeoutResult reports the remaining time as a raw Jiffies. The type does not show the unit.Switch the parameter and the result fields to Delta<Jiffy>, in the same way as
enqueue_delayed().Delta<Jiffy> is signed, but
schedule_timeout()prints an error and a stack dump for a negative timeout. Clamp a negative timeout to zero, so it means an immediate timeout.Update the only user, binder. It now converts the freeze timeout with
Delta::to_jiffies_timeout()instead ofmsecs_to_jiffies(). Both round up, so a short timeout does not become zero. They differ only for a very long timeout.msecs_to_jiffies()returnsMAX_JIFFY_OFFSETfor 2^31 ms (about 24.9 days) or more, butto_jiffies_timeout()converts such a value like any other value.Reviewed-by Gary Guo <[email protected]>Signed-off-by FUJITA Tomonori <[email protected]>--- drivers/android/binder/process.rs | 7 ++++--- rust/kernel/sync/condvar.rs | 31 ++++++++++++++++++++++--------- 2 files changed, 26 insertions(+), 12 deletions(-)drivers/android/binder/process.rs +3
-2@@ -35,6 +35,7 @@ Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SetOnce, SpinLock, UniqueArc, }, task::{Pid, Task}, + time::Delta, uaccess::{UserSlice, UserSliceReader}, uapi, workqueue::{self, Work},@@ -1549,8 +1550,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 ; }
drivers/android/binder/process.rs pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { · line 1571
Quoted 5 lines
drivers/android/binder/process.rs +1
-1@@ -1567,7 +1568,7 @@ pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { jiffies = remaining; } CondVarTimeoutResult::Timeout => { - jiffies =0 ; + jiffies =Delta ::from_jiffies (0 );
Hmm, we should make Delta::ZERO work for jiffies too.
Quoted 29 lines
drivers/android/binder/process.rs +0
-0} } }rust/kernel/sync/condvar.rs +6
-1@@ -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};@@ -182,19 +185,29 @@ pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>(/// Atomically releases the given lock (whose ownership is proven by the guard) and puts the /// thread to sleep. It wakes up when notified by [`CondVar::notify_one`] or /// [`CondVar::notify_all`], or when a timeout occurs, or when the thread receives a signal. +/// +/// A negative timeout is treated as zero. #[must_use = "wait_interruptible_timeout returns if a signal is pending, so the caller must check the return value" ] pub fn wait_interruptible_timeout <T : ?Sized ,B :Backend >( &self, guard: &mut Guard<'_, T, B>,
rust/kernel/sync/condvar.rs pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>( · line 200
Quoted 10 lines
rust/kernel/sync/condvar.rs +6
-3- 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),
This pattern shows up many times..
Makes me wonder if we want a Duration type that is Delta but unsigned (value range restricted between 0..isize::MAX (or i64::MAX for Nsec).
Or just have a as_jiffies_unsigned() which does the clamp.
Best,
Gary
Quoted 30 lines
rust/kernel/sync/condvar.rs +10
-5+ ); -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 +261,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>, }, }
Re: [PATCH v7 2/2] rust: sync: condvar: use Delta<Jiffy> for timeout and result
Quoted 15 lines · On Thu, 01 Oct 2026 01:50:41 +0100 "Gary Guo" <[email protected]> wrote:
Quoted 15 lines
drivers/android/binder/process.rs +1
-0@@ -35,6 +35,7 @@ Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SetOnce, SpinLock, UniqueArc, }, task::{Pid, Task}, + time::Delta, uaccess::{UserSlice, UserSliceReader}, uapi, workqueue::{self, Work},@@ -1549,8 +1550,8 @@ pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { inner.is_frozen =IsFrozen ::InProgress ;
Quoted 16 lines
Quoted 9 lines
drivers/android/binder/process.rs +2
-2if 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 ; }drivers/android/binder/process.rs pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { · line 1571
Quoted 5 lines
drivers/android/binder/process.rs +1
-1@@ -1567,7 +1568,7 @@ pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { jiffies = remaining; } CondVarTimeoutResult::Timeout => { - jiffies =0 ; + jiffies =Delta ::from_jiffies (0 );Hmm, we should make
Delta::ZEROwork for jiffies too.
Agreed. I'll add a patch for it in v8.
Quoted 23 lines
Quoted 10 lines
drivers/android/binder/process.rs +2
-0@@ -182,19 +185,29 @@ pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>(/// Atomically releases the given lock (whose ownership is proven by the guard) and puts the /// thread to sleep. It wakes up when notified by [`CondVar::notify_one`] or /// [`CondVar::notify_all`], or when a timeout occurs, or when the thread receives a signal. +/// +/// A negative timeout is treated as zero. #[must_use = "wait_interruptible_timeout returns if a signal is pending, so the caller must check the return value" ] pub fn wait_interruptible_timeout <T : ?Sized ,B :Backend >( &self, guard: &mut Guard<'_, T, B>,drivers/android/binder/process.rs pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>( · line 200
Quoted 10 lines
drivers/android/binder/process.rs +6
-3- 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),This pattern shows up many times..
Quoted 4 lines
Makes me wonder if we want a
Durationtype that isDeltabut unsigned (value range restricted between 0..isize::MAX (ori64::MAXfor Nsec).Or just have a
as_jiffies_unsigned()which does the clamp.
I think Delta should stay signed. Once we have Instant for jiffies, the difference of two instants can be negative, for example a deadline minus the current jiffies. This is a common pattern in C.
I'll add as_jiffies_unsigned() in v8. It clamps a negative value to 0 and returns unsigned long.