* [PATCH v3 0/2] rust: use Delta and new Jiffies type instead of raw jiffies for timeouts and delays
@ 2026-07-17 4:22 FUJITA Tomonori
2026-07-17 4:22 ` [PATCH v3 1/2] rust: time: add Delta::as_millis_ceil() FUJITA Tomonori
2026-07-17 4:22 ` [PATCH v3 2/2] rust: use Delta and a Jiffies newtype for timeouts and delays FUJITA Tomonori
0 siblings, 2 replies; 3+ messages in thread
From: FUJITA Tomonori @ 2026-07-17 4:22 UTC (permalink / raw)
To: a.hindborg, aliceryhl, arve, boqun, brauner, cmllamas, gary,
gregkh, ojeda, tkjos
Cc: acourbot, anna-maria, bjorn3_gh, dakr, daniel.almeida, frederic,
jstultz, lossin, lyude, sboyd, tamird, tglx, tmgross, work,
rust-for-linux, FUJITA Tomonori
From: FUJITA Tomonori <fujita.tomonori@gmail.com>
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).
Unlike the previous versions, v3 introduces a dedicated `Jiffies`
newtype instead. The APIs take `impl Into<Jiffies>`, so a caller can
pass either a `Delta` (the duration is converted once, rounding up) or
a `Jiffies` directly with no conversion. Jiffies returned by the C
side stay as `Jiffies`, so a caller that works in jiffies never
converts and the round trip is gone.
Why a `Jiffies` type, but no `Micros`/`Nanos`/... types?
`Delta` represents a span of time as a nanosecond count. Microseconds,
milliseconds and seconds are exact multiples of a nanosecond, so they
embed into `Delta` losslessly and round-trip through it losslessly; they
are already covered by Delta's constructors and accessors (from_millis(),
as_millis_ceil(), ...) and would gain nothing from their own types.
A jiffy is 1/HZ of a second, which is generally not an exact number of
nanoseconds (e.g. HZ=300). Converting between jiffies and Delta is
therefore inherently lossy in both directions, and that is exactly
what makes a jiffies count a distinct quantity -- a count of timer
ticks -- rather than just another way to spell a Delta. So it, and
only it, gets its own (unsigned) newtype.
The Delta -> Jiffies conversion reuses the C `__msecs_to_jiffies()`
helper -- the same routine the existing Rust `msecs_to_jiffies()`
wrapper already called. The arithmetic (and the range clamping) is
done on the C side so it works on 32-bit architectures.
v3:
- Add new Jiffies type and convert the APIs to take impl Into<Jiffies>
v2: https://lore.kernel.org/rust-for-linux/20260712235246.3069713-1-tomo@flapping.org/
- 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/20260704132558.2253275-1-tomo@aliasing.net/
FUJITA Tomonori (2):
rust: time: add Delta::as_millis_ceil()
rust: use Delta and a Jiffies newtype for timeouts and delays
drivers/android/binder/process.rs | 7 ++--
rust/kernel/sync/condvar.rs | 21 +++++++---
rust/kernel/time.rs | 64 ++++++++++++++++++++++++++-----
rust/kernel/workqueue.rs | 11 ++++--
4 files changed, 82 insertions(+), 21 deletions(-)
base-commit: 7059bdf4f04a3e14f4fafb3ac35fdca913e3e21a
--
2.43.0
^ permalink raw reply [flat|nested] 3+ messages in thread
* [PATCH v3 1/2] rust: time: add Delta::as_millis_ceil()
2026-07-17 4:22 [PATCH v3 0/2] rust: use Delta and new Jiffies type instead of raw jiffies for timeouts and delays FUJITA Tomonori
@ 2026-07-17 4:22 ` FUJITA Tomonori
2026-07-17 4:22 ` [PATCH v3 2/2] rust: use Delta and a Jiffies newtype for timeouts and delays FUJITA Tomonori
1 sibling, 0 replies; 3+ messages in thread
From: FUJITA Tomonori @ 2026-07-17 4:22 UTC (permalink / raw)
To: a.hindborg, aliceryhl, arve, boqun, brauner, cmllamas, gary,
gregkh, ojeda, tkjos
Cc: acourbot, anna-maria, bjorn3_gh, dakr, daniel.almeida, frederic,
jstultz, lossin, lyude, sboyd, tamird, tglx, tmgross, work,
rust-for-linux, FUJITA Tomonori
From: FUJITA Tomonori <fujita.tomonori@gmail.com>
Add a ceiling variant, mirroring the existing as_micros_ceil() since
the existing as_millis() truncates towards zero.
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
---
rust/kernel/time.rs | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index 363e93cbb139..23ef5c77383f 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -468,6 +468,29 @@ 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 {
+ let n = self.as_nanos();
+ let n = if n > 0 {
+ n.saturating_add(NSEC_PER_MSEC - 1)
+ } else {
+ n
+ };
+
+ #[cfg(CONFIG_64BIT)]
+ {
+ n / NSEC_PER_MSEC
+ }
+
+ #[cfg(not(CONFIG_64BIT))]
+ // SAFETY: It is always safe to call `ktime_to_ms()` with any value.
+ unsafe {
+ bindings::ktime_to_ms(n)
+ }
+ }
+
/// 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
--
2.43.0
^ permalink raw reply related [flat|nested] 3+ messages in thread
* [PATCH v3 2/2] rust: use Delta and a Jiffies newtype for timeouts and delays
2026-07-17 4:22 [PATCH v3 0/2] rust: use Delta and new Jiffies type instead of raw jiffies for timeouts and delays FUJITA Tomonori
2026-07-17 4:22 ` [PATCH v3 1/2] rust: time: add Delta::as_millis_ceil() FUJITA Tomonori
@ 2026-07-17 4:22 ` FUJITA Tomonori
1 sibling, 0 replies; 3+ messages in thread
From: FUJITA Tomonori @ 2026-07-17 4:22 UTC (permalink / raw)
To: a.hindborg, aliceryhl, arve, boqun, brauner, cmllamas, gary,
gregkh, ojeda, tkjos
Cc: acourbot, anna-maria, bjorn3_gh, dakr, daniel.almeida, frederic,
jstultz, lossin, lyude, sboyd, tamird, tglx, tmgross, work,
rust-for-linux, FUJITA Tomonori
From: FUJITA Tomonori <fujita.tomonori@gmail.com>
Turn Jiffies into a distinct newtype and let these APIs take
impl Into<Jiffies>. A caller can now pass a Delta, the duration type
already used elsewhere, so the unit is part of the type rather than a
caller convention. A caller that already holds a jiffies count can
still pass Jiffies directly, avoiding a lossy jiffies -> Delta ->
jiffies round trip.
Update CondVar::wait_interruptible_timeout() and
Queue::enqueue_delayed(), which took a raw jiffies count through a
bare c_ulong alias with no type safety. Callers had to know on their
own that the value meant jiffies and convert to and from it
themselves, which is easy to get wrong.
Once callers express timeouts and delays as Delta, msecs_to_jiffies()
and the Msecs alias have no remaining users, so remove them.
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
---
drivers/android/binder/process.rs | 7 +++---
rust/kernel/sync/condvar.rs | 21 +++++++++++-----
rust/kernel/time.rs | 41 ++++++++++++++++++++++++-------
rust/kernel/workqueue.rs | 11 ++++++---
4 files changed, 59 insertions(+), 21 deletions(-)
diff --git a/drivers/android/binder/process.rs b/drivers/android/binder/process.rs
index cdd1a9079726..5230ea492a75 100644
--- a/drivers/android/binder/process.rs
+++ b/drivers/android/binder/process.rs
@@ -1482,8 +1482,9 @@ 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: kernel::time::Jiffies =
+ kernel::time::Delta::from_millis(info.timeout_ms.into()).into();
+ while !jiffies.is_zero() {
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 = kernel::time::Jiffies::ZERO;
}
}
}
diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs
index 69d58dfbad7b..e215f83825e4 100644
--- a/rust/kernel/sync/condvar.rs
+++ b/rust/kernel/sync/condvar.rs
@@ -7,7 +7,7 @@
use super::{lock::Backend, lock::Guard, LockClassKey};
use crate::{
- ffi::{c_int, c_long},
+ ffi::{c_int, c_long, c_ulong},
str::{CStr, CStrExt as _},
task::{
MAX_SCHEDULE_TIMEOUT, TASK_FREEZABLE, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE,
@@ -186,15 +186,24 @@ 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,
+ duration: impl Into<Jiffies>,
) -> CondVarTimeoutResult {
- let jiffies = jiffies.try_into().unwrap_or(MAX_SCHEDULE_TIMEOUT);
+ let raw_jiffies: c_ulong = duration.into().as_raw();
+ let jiffies = c_long::try_from(raw_jiffies).unwrap_or(MAX_SCHEDULE_TIMEOUT);
let res = self.wait_internal(TASK_INTERRUPTIBLE, guard, jiffies);
- match (res as Jiffies, crate::current!().signal_pending()) {
- (jiffies, true) => CondVarTimeoutResult::Signal { jiffies },
+ match (res, crate::current!().signal_pending()) {
+ (jiffies, true) => CondVarTimeoutResult::Signal {
+ // CAST: `wait_internal()` never returns negative,
+ // so it is safe to cast `jiffies` to `c_ulong`.
+ jiffies: Jiffies::new(jiffies as c_ulong),
+ },
(0, false) => CondVarTimeoutResult::Timeout,
- (jiffies, false) => CondVarTimeoutResult::Woken { jiffies },
+ (jiffies, false) => CondVarTimeoutResult::Woken {
+ // CAST: `wait_internal()` never returns negative,
+ // so it is safe to cast `jiffies` to `c_ulong`.
+ jiffies: Jiffies::new(jiffies as c_ulong),
+ },
}
}
diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index 23ef5c77383f..206296b6b6ea 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -40,17 +40,40 @@
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;
+#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
+pub struct Jiffies(crate::ffi::c_ulong);
-/// The millisecond time unit.
-pub type Msecs = crate::ffi::c_uint;
+impl Jiffies {
+ /// A jiffies value of zero.
+ pub const ZERO: Self = Self(0);
-/// 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) }
+ /// Create a new [`Jiffies`] from the C side's `jiffies` value.
+ #[inline]
+ pub const fn new(jiffies: crate::ffi::c_ulong) -> Self {
+ Self(jiffies)
+ }
+
+ #[inline]
+ pub(crate) const fn as_raw(self) -> crate::ffi::c_ulong {
+ self.0
+ }
+
+ /// Return `true` if the [`Jiffies`] has a value of zero.
+ #[inline]
+ pub fn is_zero(self) -> bool {
+ self.0 == 0
+ }
+}
+
+impl From<Delta> for Jiffies {
+ #[inline]
+ fn from(delta: Delta) -> Self {
+ let millis = u32::try_from(delta.as_millis_ceil().max(0)).unwrap_or(u32::MAX);
+ // SAFETY: The `__msecs_to_jiffies` function is always safe to call no
+ // matter what the argument is.
+ let jiffies = unsafe { bindings::__msecs_to_jiffies(millis) };
+ Self(jiffies)
+ }
}
/// Trait for clock sources.
diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
index 7e253b6f299c..41fa1a9eb9d7 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -136,6 +136,7 @@
//! ```
//! use kernel::sync::Arc;
//! use kernel::workqueue::{self, impl_has_delayed_work, new_delayed_work, DelayedWork, WorkItem};
+//! use kernel::time::Jiffies;
//!
//! #[pin_data]
//! struct MyStruct {
@@ -171,7 +172,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, Jiffies::new(12));
//! }
//!
//! /// It is also possible to use the ordinary `enqueue` method together with `DelayedWork`. This
@@ -303,7 +304,11 @@ 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,
+ delay: impl Into<Jiffies>,
+ ) -> 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.into().as_raw(),
)
})
}
--
2.43.0
^ permalink raw reply related [flat|nested] 3+ messages in thread
end of thread, other threads:[~2026-07-17 4:23 UTC | newest]
Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-07-17 4:22 [PATCH v3 0/2] rust: use Delta and new Jiffies type instead of raw jiffies for timeouts and delays FUJITA Tomonori
2026-07-17 4:22 ` [PATCH v3 1/2] rust: time: add Delta::as_millis_ceil() FUJITA Tomonori
2026-07-17 4:22 ` [PATCH v3 2/2] rust: use Delta and a Jiffies newtype for timeouts and delays FUJITA Tomonori
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox