Skip to contentSkip to conversation

rust: use Delta instead of raw jiffies for timeouts and delays

PATCH Applied FUJITA Tomonori 4 participants 13 messages Oct 2 – Oct 12

Subsystems (4)

v8 of 10 Applied Latest is v10 →

lore
Share & tools
lore
#0 lore raw

v8 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]/

---
v8:
- Add a patch to make Delta::ZERO generic over the time unit (Markus, Gary)
- Add a patch to add Delta::as_jiffies_unsigned() (Gary)
- workqueue: use as_jiffies_unsigned()
- condvar: use Delta::ZERO in binder (Gary)
v7: https://lore.kernel.org/rust-for-linux/[email protected]/
- 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 (4):
rust: time: make Delta::ZERO generic over the time unit
rust: time: add Delta::as_jiffies_unsigned()
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/time.rs               | 34 ++++++++++++++++++++++++++++---
 rust/kernel/workqueue.rs          | 13 ++++++++----
 4 files changed, 66 insertions(+), 19 deletions(-)

base-commit: 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38

Signature · 1 line
2.43.0
#1 lore raw

PATCH v8 1/4 rust: time: make Delta::ZERO generic over the time unit

From: FUJITA Tomonori <[email protected]>

Delta::ZERO is defined only for Delta<Nsec>, so code that needs a zero Delta<Jiffy> has to write Delta::from_jiffies(0).

Define ZERO for every Delta<U> instead. An integer literal cannot be used for a generic U::Repr, so add ZERO to TimeUnit.

---
 rust/kernel/time.rs | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
rust/kernel/time.rs +10 -3
index 5ae377e70dd8..9f231bf25ead 100644
@@ -306,6 +306,9 @@ impl Sealed for super::Jiffy {}
 pub trait TimeUnit: private::Sealed {
     /// The underlying representation of the time unit.
     type Repr: Copy + Clone + PartialEq + PartialOrd + Eq + Ord + core::fmt::Debug;
+
+    /// The zero value of [`Self::Repr`].
+    const ZERO: Self::Repr;
 }
 
 /// A time unit of nanoseconds.
@@ -317,6 +320,7 @@ pub enum Nsec {}
 
 impl TimeUnit for Nsec {
     type Repr = i64;
+    const ZERO: Self::Repr = 0;
 }
 
 /// A time unit of jiffies.
@@ -328,6 +332,7 @@ pub enum Jiffy {}
 
 impl TimeUnit for Jiffy {
     type Repr = isize;
+    const ZERO: Self::Repr = 0;
 }
 
 /// A span of time.
@@ -341,6 +346,11 @@ pub struct Delta<U: TimeUnit = Nsec> {
     value: U::Repr,
 }
 
+impl<U: TimeUnit> Delta<U> {
+    /// A span of time equal to zero.
+    pub const ZERO: Self = Self { value: U::ZERO };
+}
+
 impl Delta<Jiffy> {
     /// Create a new [`Delta`] from a number of jiffies.
     #[inline]
@@ -428,9 +438,6 @@ fn div(self, rhs: Self) -> Self::Output {
 }
 
 impl Delta {
-    /// A span of time equal to zero.
-    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 {
Signature · 1 line
2.43.0
#3 lore raw

PATCH v8 2/4 rust: time: add Delta::as_jiffies_unsigned()

In reply to FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

Delta<Jiffy> is signed, but some C functions, such as queue_delayed_work_on(), take a span in jiffies as unsigned long. So each caller has to clamp a negative value to zero and cast it before it passes the value to C. Add a helper that does both.

---
 rust/kernel/time.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/time.rs +21 -0
index 9f231bf25ead..b6a2aab12a50 100644
@@ -363,6 +363,27 @@ pub const fn from_jiffies(jiffies: isize) -> Self {
     pub const fn as_jiffies(self) -> isize {
         self.value
     }
+
+    /// Return the number of jiffies in the [`Delta`] as an unsigned value.
+    ///
+    /// If the number of jiffies is negative, zero is returned.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::time::Delta;
+    ///
+    /// // A negative span returns zero.
+    /// assert_eq!(Delta::from_jiffies(-1).as_jiffies_unsigned(), 0);
+    ///
+    /// // A positive span returns its value.
+    /// assert_eq!(Delta::from_jiffies(1).as_jiffies_unsigned(), 1);
+    /// ```
+    #[inline]
+    pub fn as_jiffies_unsigned(self) -> usize {
+        // CAST: `isize::max()` makes the value non-negative, so the cast keeps it.
+        isize::max(self.value, 0) as usize
+    }
 }
 
 impl ops::Add for Delta {
Signature · 1 line
2.43.0
#5 lore raw

PATCH v8 3/4 rust: workqueue: take a Delta<Jiffy> for the enqueue delay

In reply to FUJITA Tomonori

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.

---
 rust/kernel/workqueue.rs | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
rust/kernel/workqueue.rs +9 -4
index 7e253b6f299c..6dc33bac07aa 100644
@@ -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,7 +306,9 @@ 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,
     {
@@ -328,7 +333,7 @@ pub fn enqueue_delayed<W, const ID: u64>(&self, w: W, delay: Jiffies) -> W::Enqu
                     bindings::wq_misc_consts_WORK_CPU_UNBOUND as ffi::c_int,
                     queue_ptr,
                     container_of!(work_ptr, bindings::delayed_work, work),
-                    delay,
+                    delay.as_jiffies_unsigned(),
                 )
             })
         }
Signature · 1 line
2.43.0
#6 lore raw

PATCH v8 4/4 rust: sync: condvar: use Delta<Jiffy> for timeout and result

In reply to 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 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
index 5372bfbd93b3..2edd3dcd4edc 100644
@@ -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::ZERO;
                     }
                 }
             }
rust/kernel/sync/condvar.rs +22 -9
index 69d58dfbad7b..ae70e91eca94 100644
@@ -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 (res as 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
maintainer
#7 lore raw

Re: [PATCH v8 4/4] rust: sync: condvar: use Delta<Jiffy> for timeout and result

Quoted 85 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 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
index 5372bfbd93b3..2edd3dcd4edc 100644
@@ -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::ZERO;
                     }
                 }
             }
rust/kernel/sync/condvar.rs +6 -1
index 69d58dfbad7b..ae70e91eca94 100644
@@ -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),

I suppose this can be delta.as_jiffies_unsigned() too, although the clamp makes it more explicit?

Best,
Gary

Quoted 30 lines
rust/kernel/sync/condvar.rs +10 -5
+        );
 
-        match (res as 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>,
     },
 }
maintainer Reviewed-by on the v8 series
#10 lore raw
In reply to FUJITA Tomonori
Quoted 31 lines · FUJITA Tomonori

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]/

---
v8:
- Add a patch to make Delta::ZERO generic over the time unit (Markus, Gary)
- Add a patch to add Delta::as_jiffies_unsigned() (Gary)
- workqueue: use as_jiffies_unsigned()
- condvar: use Delta::ZERO in binder (Gary)
v7: https://lore.kernel.org/rust-for-linux/[email protected]/

Quoted 5 lines

FUJITA Tomonori (4):
rust: time: make Delta::ZERO generic over the time unit
rust: time: add Delta::as_jiffies_unsigned()
rust: workqueue: take a Delta<Jiffy> for the enqueue delay
rust: sync: condvar: use Delta<Jiffy> for timeout and result

For the series:

Quoted 9 lines
 drivers/android/binder/process.rs |  7 ++++---
 rust/kernel/sync/condvar.rs       | 31 ++++++++++++++++++++--------
 rust/kernel/time.rs               | 34 ++++++++++++++++++++++++++++---
 rust/kernel/workqueue.rs          | 13 ++++++++----
 4 files changed, 66 insertions(+), 19 deletions(-)

base-commit: 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38

#8 lore raw

Re: [PATCH v8 4/4] rust: sync: condvar: use Delta<Jiffy> for timeout and result

In reply to Gary Guo
Quoted 2 lines · On Fri, 02 Oct 2026 11:00:40 +0100 "Gary Guo" <[email protected]> wrote:
Quoted 1 line · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

[...]

Quoted 15 lines
Quoted 15 lines
rust/kernel/sync/condvar.rs +3 -3
@@ -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);
Quoted 8 lines

rust/kernel/sync/condvar.rs pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>( · line 200

Quoted 5 lines
rust/kernel/sync/condvar.rs +5 -0
+        let jiffies = delta.as_jiffies();
+        let res = self.wait_internal(
+            TASK_INTERRUPTIBLE,
+            guard,
+            jiffies.clamp(0, MAX_SCHEDULE_TIMEOUT),

I suppose this can be delta.as_jiffies_unsigned() too, although the clamp makes it more explicit?

wait_internal() takes isize, so with as_jiffies_unsigned() we need to cast the value back:

| // CAST: `as_jiffies_unsigned()` returns at most `isize::MAX`, so the
| // value fits in `isize`.
| let jiffies = delta.as_jiffies_unsigned() as isize;
| let res = self.wait_internal(TASK_INTERRUPTIBLE, guard, jiffies);

The clamp needs no cast, so I'd keep it.

maintainer
#9 lore raw

Re: [PATCH v8 4/4] rust: sync: condvar: use Delta<Jiffy> for timeout and result

Quoted 35 lines · FUJITA Tomonori
Quoted 2 lines · On Fri, 02 Oct 2026 11:00:40 +0100 "Gary Guo" <[email protected]> wrote:
Quoted 1 line · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

[...]

Quoted 15 lines
Quoted 15 lines
rust/kernel/sync/condvar.rs +3 -3
@@ -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);
Quoted 8 lines

rust/kernel/sync/condvar.rs pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>( · line 200

Quoted 5 lines
rust/kernel/sync/condvar.rs +5 -0
+        let jiffies = delta.as_jiffies();
+        let res = self.wait_internal(
+            TASK_INTERRUPTIBLE,
+            guard,
+            jiffies.clamp(0, MAX_SCHEDULE_TIMEOUT),

I suppose this can be delta.as_jiffies_unsigned() too, although the clamp makes it more explicit?

wait_internal() takes isize, so with as_jiffies_unsigned() we need to cast the value back:

Quoted 6 lines
| // CAST: `as_jiffies_unsigned()` returns at most `isize::MAX`, so the
| // value fits in `isize`.
| let jiffies = delta.as_jiffies_unsigned() as isize;
| let res = self.wait_internal(TASK_INTERRUPTIBLE, guard, jiffies);

The clamp needs no cast, so I'd keep it.

Right, sounds reasonable. This can also be isize::max(delta.as_jiffies(), 0) I suppose, but clamp reads fine too.

Best,
Gary

maintainer Acked-by on v8 2/4
#4 lore raw

Re: [PATCH v8 2/4] rust: time: add Delta::as_jiffies_unsigned()

In reply to FUJITA Tomonori
Quoted 9 lines · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

Delta<Jiffy> is signed, but some C functions, such as queue_delayed_work_on(), take a span in jiffies as unsigned long. So each caller has to clamp a negative value to zero and cast it before it passes the value to C. Add a helper that does both.

I'm not taking more patches for timekeeping this cycle. Up to Miguel if he wants to take it through rust tree.

Best regards,
Andreas Hindborg

maintainer
#11 lore raw
In reply to FUJITA Tomonori
Quoted 12 lines · FUJITA Tomonori

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().

Quoted 9 lines

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?

For the future, I would prefer if you can submit timekeeping changes as a separate series.

Best regards,
Andreas Hindborg

maintainer Acked-by on v8 1/4
#2 lore raw

Re: [PATCH v8 1/4] rust: time: make Delta::ZERO generic over the time unit

In reply to FUJITA Tomonori
Quoted 11 lines · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

Delta::ZERO is defined only for Delta<Nsec>, so code that needs a zero Delta<Jiffy> has to write Delta::from_jiffies(0).

Define ZERO for every Delta<U> instead. An integer literal cannot be used for a generic U::Repr, so add ZERO to TimeUnit.

I'm not taking more patches for timekeeping this cycle. Up to Miguel if he wants to take it through rust tree.

Best regards,
Andreas Hindborg

Applied
#12 lore raw
In reply to FUJITA Tomonori
Quoted 3 lines · FUJITA Tomonori

rust: time: make Delta::ZERO generic over the time unit
rust: time: add Delta::as_jiffies_unsigned()

Applied as requested to rust-next -- thanks everyone!

Cheers,
Miguel