rust: use Delta instead of raw jiffies for timeouts and delays
Subsystems (4)
v2 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. Jiffies are just another time unit, like milliseconds or nanoseconds.
This series adds jiffies conversion helpers to Delta, 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.
v2:
- 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: add jiffies conversion helpers to Delta
rust: sync: use Delta for CondVar timeout API
rust: workqueue: use Delta for enqueue_delayed's delay parameter
rust: time: remove unused Jiffies/Msecs helpers
drivers/android/binder/process.rs | 12 ++++----- rust/kernel/sync/condvar.rs | 20 ++++++++------ rust/kernel/time.rs | 44 +++++++++++++++++++++---------- rust/kernel/workqueue.rs | 6 ++--- 4 files changed, 51 insertions(+), 31 deletions(-)
base-commit: 0e35b9b6ec0ffcc5e23cbdec09f5c622ad532b53
Signature · 1 line
2.43.0
PATCH v2 1/4 rust: time: add jiffies conversion helpers to Delta
From: FUJITA Tomonori <[email protected]>
Callers that hand a timeout to some C APIs need conversion between Delta and jiffies.
--- rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)
rust/kernel/time.rs +30 -0
@@ -377,6 +377,20 @@ impl Delta {/// A span of time equal to zero. pub const ZERO :Self =Self { nanos:0 }; +/// Create a new [`Delta`] from a number of jiffies. +/// +/// If `jiffies` is large enough that the corresponding number of nanoseconds +/// would overflow an `i64`, the result saturates to `i64::MAX` nanoseconds. +/// The exact threshold depends on `CONFIG_HZ`. +#[inline] +pub fn from_jiffies (jiffies:u64 ) ->Self { +let nanos = (u128::from (jiffies) *NSEC_PER_SEC as u128 / u128::from (bindings::HZ )) + .min (i64::MAX as u128 ); +Self { + nanos: nanosas i64 , + } + } +/// Create a new [`Delta`] from a number of nanoseconds. #[inline] pub const fn from_nanos (nanos:i64 ) ->Self {
@@ -431,6 +445,22 @@ pub fn is_negative(self) -> bool { self.as_nanos () <0 } +/// Return the smallest number of jiffies greater than or equal +/// to the value in the [`Delta`]. +/// +/// If the value is negative, `0` is returned. +#[inline] +pub fn as_jiffies_ceil (self) ->crate ::ffi::c_ulong { +// Mirrors `MAX_JIFFY_OFFSET` in C side. bindgen doesn't generate a constant for it +// since it's a compound expression rather than a plain integer literal. +const MAX_JIFFY_OFFSET :u128 = ((crate ::ffi::c_long::MAX >>1 ) -1 )as u128 ; + +let nanos = self.as_nanos ().max (0 )as u128 ; +let jiffies = (nanos * u128::from (bindings::HZ )).div_ceil (NSEC_PER_SEC as u128 ); + + jiffies.min (MAX_JIFFY_OFFSET )as crate ::ffi::c_ulong + } +/// Return the number of nanoseconds in the [`Delta`]. #[inline] pub const fn as_nanos (self) ->i64 {
Signature · 1 line
2.43.0
PATCH v2 2/4 rust: sync: use Delta for CondVar timeout API
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
wait_interruptible_timeout() and CondVarTimeoutResult take/return 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).
Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Use as_jiffies_ceil() rather than a plain truncating conversion: a caller that passes a nonzero Delta expects the call to actually sleep for roughly that long (or return earlier via a wakeup or signal).
Update binder's ioctl_freeze(), the only caller, accordingly.
--- drivers/android/binder/process.rs | 12 ++++++------ rust/kernel/sync/condvar.rs | 20 ++++++++++++-------- 2 files changed, 18 insertions(+), 14 deletions(-)
drivers/android/binder/process.rs +6 -6
@@ -1468,25 +1468,25 @@ 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 delta = kernel::time::Delta ::from_millis (info.timeout_ms.into ()); +while !delta.is_zero () {if inner.outstanding_txns ==0 {break ; }match self .freeze_wait - .wait_interruptible_timeout (&mut inner, jiffies) + .wait_interruptible_timeout (&mut inner, delta) {CondVarTimeoutResult ::Signal { .. } => { inner.is_frozen =IsFrozen ::No ;return Err (ERESTARTSYS ); } -CondVarTimeoutResult ::Woken { jiffies: remaining } => { - jiffies = remaining; +CondVarTimeoutResult ::Woken { delta: remaining } => { + delta = remaining; }CondVarTimeoutResult ::Timeout => { - jiffies =0 ; + delta = kernel::time::Delta ::ZERO ; } } }
rust/kernel/sync/condvar.rs +12 -8
@@ -12,7 +12,7 @@ task::{ MAX_SCHEDULE_TIMEOUT, TASK_FREEZABLE, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE, }, - time::Jiffies, + time::Delta, types::Opaque, };use core::{marker::PhantomPinned , pin::Pin , ptr};
@@ -186,15 +186,19 @@ 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 , ) ->CondVarTimeoutResult { -let jiffies = jiffies.try_into ().unwrap_or (MAX_SCHEDULE_TIMEOUT ); +let jiffies = c_long::try_from (delta.as_jiffies_ceil ()).unwrap_or (MAX_SCHEDULE_TIMEOUT );let res = self.wait_internal (TASK_INTERRUPTIBLE , guard, jiffies); -match (resas Jiffies ,crate ::current!().signal_pending ()) { - (jiffies,true ) =>CondVarTimeoutResult ::Signal { jiffies }, +match (res,crate ::current!().signal_pending ()) { + (jiffies,true ) =>CondVarTimeoutResult ::Signal { + delta:Delta ::from_jiffies (jiffiesas u64 ), + }, (0 ,false ) =>CondVarTimeoutResult ::Timeout , - (jiffies,false ) =>CondVarTimeoutResult ::Woken { jiffies }, + (jiffies,false ) =>CondVarTimeoutResult ::Woken { + delta:Delta ::from_jiffies (jiffiesas u64 ), + }, } }
@@ -248,11 +252,11 @@ pub enum CondVarTimeoutResult {/// Somebody woke us up. Woken { /// Remaining sleep duration. - jiffies: Jiffies, + delta: Delta, },/// A signal occurred. Signal {/// Remaining sleep duration. - jiffies:Jiffies , + delta:Delta , }, }
Signature · 1 line
2.43.0
PATCH v2 3/4 rust: workqueue: use Delta for enqueue_delayed's delay parameter
In reply to FUJITA TomonoriFrom: FUJITA Tomonori <[email protected]>
enqueue_delayed() took a raw jiffies count (a plain c_ulong alias with no type safety), so callers had to know on their own that the value meant jiffies and convert to/from it themselves. This mirrors the issue already fixed for CondVar's wait_interruptible_timeout().
Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Use as_jiffies_ceil() rather than a plain truncating conversion:queue_delayed_work_on() treats a delay of 0 jiffies as "enqueue immediately", so truncating a small nonzero Delta down to 0 would silently turn a requested delay into no delay at all.
--- rust/kernel/workqueue.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
rust/kernel/workqueue.rs +3 -3
@@ -197,7 +197,7 @@ Arc, LockClassKey, // }, - time::Jiffies, + time::Delta, types::Opaque, };use core::{marker::PhantomData , ptr::NonNull };
@@ -303,7 +303,7 @@ 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:Delta ) ->W ::EnqueueOutput where W :RawDelayedWorkItem <ID > +Send + 'static, {
@@ -328,7 +328,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_ceil (), ) }) }
Signature · 1 line
2.43.0
PATCH v2 4/4 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
Alice Ryhl
maintainerRe: [PATCH v2 3/4] rust: workqueue: use Delta for enqueue_delayed's delay parameter
In reply to FUJITA TomonoriQuoted 10 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
enqueue_delayed()took a raw jiffies count (a plainc_ulongalias with no type safety), so callers had to know on their own that the value meant jiffies and convert to/from it themselves. This mirrors the issue already fixed for CondVar'swait_interruptible_timeout().Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Quoted 6 lines
Use
as_jiffies_ceil()rather than a plain truncating conversion:queue_delayed_work_on()treats a delay of 0 jiffies as "enqueue immediately", so truncating a small nonzero Delta down to 0 would silently turn a requested delay into no delay at all.Signed-off-by FUJITA Tomonori <[email protected]>
It seems unfortunate that a caller might be forced to convert jiffies -> nanos -> jiffies if they already have the value in jiffies.
Alice
Onur Özkan
reviewerRe: [PATCH v2 3/4] rust: workqueue: use Delta for enqueue_delayed's delay parameter
Quoted 16 lines · On Mon, 13 Jul 2026 08:59:56 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 15 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
enqueue_delayed()took a raw jiffies count (a plainc_ulongalias with no type safety), so callers had to know on their own that the value meant jiffies and convert to/from it themselves. This mirrors the issue already fixed for CondVar'swait_interruptible_timeout().Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Use
as_jiffies_ceil()rather than a plain truncating conversion:queue_delayed_work_on()treats a delay of 0 jiffies as "enqueue immediately", so truncating a small nonzero Delta down to 0 would silently turn a requested delay into no delay at all.
Quoted 6 lines
Quoted 1 line
Signed-off-by FUJITA Tomonori <[email protected]>It seems unfortunate that a caller might be forced to convert jiffies -> nanos -> jiffies if they already have the value in jiffies.
Alice
Yeah that's not ideal. We can solve this by making the argument something like impl Into<Delta>, right?
Regards,
Onur
Re: [PATCH v2 3/4] rust: workqueue: use Delta for enqueue_delayed's delay parameter
Quoted 21 lines · On Mon, 13 Jul 2026 12:07:30 +0300 Onur Özkan <[email protected]> wrote:
Quoted 18 lines · On Mon, 13 Jul 2026 08:59:56 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 16 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
enqueue_delayed()took a raw jiffies count (a plainc_ulongalias with no type safety), so callers had to know on their own that the value meant jiffies and convert to/from it themselves. This mirrors the issue already fixed for CondVar'swait_interruptible_timeout().Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Use
as_jiffies_ceil()rather than a plain truncating conversion:queue_delayed_work_on()treats a delay of 0 jiffies as "enqueue immediately", so truncating a small nonzero Delta down to 0 would silently turn a requested delay into no delay at all.Signed-off-by FUJITA Tomonori <[email protected]>
Quoted 7 lines
Quoted 4 lines
It seems unfortunate that a caller might be forced to convert jiffies -> nanos -> jiffies if they already have the value in jiffies.
Alice
Yeah that's not ideal. We can solve this by making the argument something like
impl Into<Delta>, right?
With impl Into<Delta>, the argument type changes, but if Delta's internal representation stays a plain nanosecond count, then .into() still performs the jiffies -> nanos conversion. Then enqueue_delayed() still calls as_jiffies_ceil() to convert back to jiffies afterwards.
#[derive(Copy, Clone)]
enum Repr {
Nanos(i64),
Jiffies(u64),
}#[derive(Copy, Clone)]
pub struct Delta {
repr: Repr,
}
The enum representation like above works? Delta::from_jiffies() just stores the jiffies count. APIs like enqueue_delayed() that uses jiffies time-unit don't need to do any conversion.
The downside is that it makes the Add/Sub/PartialEq methods complicated.
Gary Guo
maintainerRe: [PATCH v2 3/4] rust: workqueue: use Delta for enqueue_delayed's delay parameter
Quoted 43 lines · FUJITA Tomonori
Quoted 21 lines · On Mon, 13 Jul 2026 12:07:30 +0300 Onur Özkan <[email protected]> wrote:
Quoted 18 lines · On Mon, 13 Jul 2026 08:59:56 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 16 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
enqueue_delayed()took a raw jiffies count (a plainc_ulongalias with no type safety), so callers had to know on their own that the value meant jiffies and convert to/from it themselves. This mirrors the issue already fixed for CondVar'swait_interruptible_timeout().Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Use
as_jiffies_ceil()rather than a plain truncating conversion:queue_delayed_work_on()treats a delay of 0 jiffies as "enqueue immediately", so truncating a small nonzero Delta down to 0 would silently turn a requested delay into no delay at all.Signed-off-by FUJITA Tomonori <[email protected]>Quoted 7 lines
Quoted 4 lines
It seems unfortunate that a caller might be forced to convert jiffies -> nanos -> jiffies if they already have the value in jiffies.
Alice
Yeah that's not ideal. We can solve this by making the argument something like
impl Into<Delta>, right?With impl Into<Delta>, the argument type changes, but if Delta's internal representation stays a plain nanosecond count, then .into() still performs the jiffies -> nanos conversion. Then
enqueue_delayed()still callsas_jiffies_ceil()to convert back to jiffies afterwards.#[derive(Copy, Clone)]
enum Repr { Nanos(i64), Jiffies(u64), }
Quoted 8 lines
#[derive(Copy, Clone)]
pub struct Delta {
repr: Repr,
}The enum representation like above works?
Delta::from_jiffies()just stores the jiffies count. APIs likeenqueue_delayed()that uses jiffies time-unit don't need to do any conversion.
I don't think using enums is the correct approach.
Why can't we make Jiffies a new type as well? Then we can implement From<Jiffies> for Delta and From<Delta> for Jiffies, and then the API can just have Into<WhatEverTimeReprItNeed>?
Best,
Gary
Re: [PATCH v2 3/4] rust: workqueue: use Delta for enqueue_delayed's delay parameter
Quoted 53 lines · On Mon, 13 Jul 2026 12:55:36 +0100 "Gary Guo" <[email protected]> wrote:
Quoted 43 lines · FUJITA Tomonori
Quoted 21 lines · On Mon, 13 Jul 2026 12:07:30 +0300 Onur Özkan <[email protected]> wrote:
Quoted 18 lines · On Mon, 13 Jul 2026 08:59:56 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 16 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
enqueue_delayed()took a raw jiffies count (a plainc_ulongalias with no type safety), so callers had to know on their own that the value meant jiffies and convert to/from it themselves. This mirrors the issue already fixed for CondVar'swait_interruptible_timeout().Switch to Delta, the duration type already used elsewhere, so the unit is part of the type instead of a caller convention.
Use
as_jiffies_ceil()rather than a plain truncating conversion:queue_delayed_work_on()treats a delay of 0 jiffies as "enqueue immediately", so truncating a small nonzero Delta down to 0 would silently turn a requested delay into no delay at all.Signed-off-by FUJITA Tomonori <[email protected]>Quoted 7 lines
Quoted 4 lines
It seems unfortunate that a caller might be forced to convert jiffies -> nanos -> jiffies if they already have the value in jiffies.
Alice
Yeah that's not ideal. We can solve this by making the argument something like
impl Into<Delta>, right?With impl Into<Delta>, the argument type changes, but if Delta's internal representation stays a plain nanosecond count, then .into() still performs the jiffies -> nanos conversion. Then
enqueue_delayed()still callsas_jiffies_ceil()to convert back to jiffies afterwards.#[derive(Copy, Clone)]
enum Repr { Nanos(i64), Jiffies(u64), }Quoted 8 lines
#[derive(Copy, Clone)]
pub struct Delta {
repr: Repr,
}The enum representation like above works?
Delta::from_jiffies()just stores the jiffies count. APIs likeenqueue_delayed()that uses jiffies time-unit don't need to do any conversion.
Quoted 5 lines
I don't think using enums is the correct approach.
Why can't we make Jiffies a new type as well? Then we can implement
From<Jiffies>forDeltaandFrom<Delta>forJiffies, and then the API can just haveInto<WhatEverTimeReprItNeed>?
If the principle is "each API should accept whatever type matches the C function's native time unit", does that mean we'd also introduce other time units as types — e.g. a Micros type so that fsleep()/udelay() take impl Into<Micros>?
Or is Jiffies meant to be a special case here, distinct from those?
Andreas Hindborg
maintainerRe: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
In reply to FUJITA TomonoriQuoted 17 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Callers that hand a timeout to some C APIs need conversion between Delta and jiffies.
Signed-off-by FUJITA Tomonori <[email protected]>--- rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)rust/kernel/time.rs +0
-0@@ -377,6 +377,20 @@ impl Delta {/// A span of time equal to zero. pub const ZERO :Self =Self { nanos:0 };
rust/kernel/time.rs impl Delta { · line 388
Quoted 10 lines
rust/kernel/time.rs +9
-0+/// Create a new [`Delta`] from a number of jiffies. +/// +/// If `jiffies` is large enough that the corresponding number of nanoseconds +/// would overflow an `i64`, the result saturates to `i64::MAX` nanoseconds. +/// The exact threshold depends on `CONFIG_HZ`. +#[inline] +pub fn from_jiffies (jiffies:u64 ) ->Self { +let nanos = (u128::from (jiffies) *NSEC_PER_SEC as u128 / u128::from (bindings::HZ )) + .min (i64::MAX as u128 );
In general for this patch, why are some widening operations using from and others use as u128? Is it not possible to use into/form for all the widening operations?
For the narrowing operations, I think we need // CAST: annotations.
Best regards,
Andreas Hindborg
Re: [PATCH v2 4/4] rust: time: remove unused Jiffies/Msecs helpers
In reply to FUJITA TomonoriQuoted 8 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
CondVar's
wait_interruptible_timeout()and workqueue'senqueue_delayed()have both moved from raw jiffies counts to Delta, so nothing in the tree callsmsecs_to_jiffies()or uses the Jiffies and Msecs aliases anymore.Signed-off-by FUJITA Tomonori <[email protected]>
Best regards,
Andreas Hindborg
Re: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
In reply to Andreas HindborgQuoted 20 lines · On Wed, 15 Jul 2026 08:57:03 +0200 Andreas Hindborg <[email protected]>…
Quoted 18 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Callers that hand a timeout to some C APIs need conversion between Delta and jiffies.
Signed-off-by FUJITA Tomonori <[email protected]>--- rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)rust/kernel/time.rs +0
-0@@ -377,6 +377,20 @@ impl Delta {/// A span of time equal to zero. pub const ZERO :Self =Self { nanos:0 };
Quoted 13 lines
rust/kernel/time.rs impl Delta { · line 388
Quoted 9 lines
rust/kernel/time.rs +9
-0+/// Create a new [`Delta`] from a number of jiffies. +/// +/// If `jiffies` is large enough that the corresponding number of nanoseconds +/// would overflow an `i64`, the result saturates to `i64::MAX` nanoseconds. +/// The exact threshold depends on `CONFIG_HZ`. +#[inline] +pub fn from_jiffies (jiffies:u64 ) ->Self { +let nanos = (u128::from (jiffies) *NSEC_PER_SEC as u128 / u128::from (bindings::HZ )) + .min (i64::MAX as u128 );In general for this patch, why are some widening operations using
fromand others useas u128? Is it not possible to use into/form for all the widening operations?
When NSEC_PER_SEC % HZ != 0, we need to multiply jiffies * NSEC_PER_SEC before dividing by HZ.
What the C side does is:
u64 jiffies64_to_nsecs(u64 j)
{
#if !(NSEC_PER_SEC % HZ) return (NSEC_PER_SEC / HZ) * j; # else return div_u64(j * HZ_TO_NSEC_NUM, HZ_TO_NSEC_DEN); #endif }
We could replicate this with a cfg/the C side's const-eval computing. But I think using u128/i128 is simpler. What do you think?
Quoted 1 line
For the narrowing operations, I think we need
// CAST:annotations.
Ah, forgot about that - thanks.
Andreas Hindborg
maintainerRe: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
Quoted 51 lines · FUJITA Tomonori
Quoted 20 lines · On Wed, 15 Jul 2026 08:57:03 +0200 Andreas Hindborg <[email protected]>…
Quoted 18 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Callers that hand a timeout to some C APIs need conversion between Delta and jiffies.
Signed-off-by FUJITA Tomonori <[email protected]>--- rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)rust/kernel/time.rs +0
-0@@ -377,6 +377,20 @@ impl Delta {/// A span of time equal to zero. pub const ZERO :Self =Self { nanos:0 };Quoted 13 lines
rust/kernel/time.rs impl Delta { · line 388
Quoted 9 lines
rust/kernel/time.rs +9
-0+/// Create a new [`Delta`] from a number of jiffies. +/// +/// If `jiffies` is large enough that the corresponding number of nanoseconds +/// would overflow an `i64`, the result saturates to `i64::MAX` nanoseconds. +/// The exact threshold depends on `CONFIG_HZ`. +#[inline] +pub fn from_jiffies (jiffies:u64 ) ->Self { +let nanos = (u128::from (jiffies) *NSEC_PER_SEC as u128 / u128::from (bindings::HZ )) + .min (i64::MAX as u128 );In general for this patch, why are some widening operations using
fromand others useas u128? Is it not possible to use into/form for all the widening operations?When
NSEC_PER_SEC% HZ != 0, we need to multiply jiffies *NSEC_PER_SECbefore dividing by HZ.What the C side does is:
u64
jiffies64_to_nsecs(u64 j)
{#if !(NSEC_PER_SEC % HZ) return (NSEC_PER_SEC / HZ) * j; # else return div_u64(j * HZ_TO_NSEC_NUM, HZ_TO_NSEC_DEN); #endif }
Quoted 2 lines
We could replicate this with a cfg/the C side's const-eval computing. But I think using u128/i128 is simpler. What do you think?
I think widening to 128 bits is fine. My question is why NSEC_PER_SEC as u128 instead of u128::from(NSEC_PER_SEC)?
Best regards,
Andreas Hindborg
Re: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
Quoted 3 lines · Andreas Hindborg
I think widening to 128 bits is fine. My question is why
NSEC_PER_SEC as u128instead ofu128::from(NSEC_PER_SEC)?
Yes, please avoid casts if possible.
Regarding u128 -- please make sure it works in 32-bit architectures. It seems like you are doing a 128-bit multiplication there?
Thanks!
Cheers,
Miguel
Gary Guo
maintainerRe: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
Quoted 9 lines · Miguel Ojeda
Quoted 3 lines · Andreas Hindborg
I think widening to 128 bits is fine. My question is why
NSEC_PER_SEC as u128instead ofu128::from(NSEC_PER_SEC)?Yes, please avoid casts if possible.
Regarding
u128-- please make sure it works in 32-bit architectures. It seems like you are doing a 128-bit multiplication there?
This will also need a division when HZ is not a factor of NSEC_PER_SEC -- which will be the case for HZ_300.
This should just limit the precision by doing a multiplication with (USEC_PER_SEC / HZ) like jiffies_to_usecs.
Best,
Gary
Re: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
In reply to Miguel OjedaQuoted 9 lines · On Wed, 15 Jul 2026 16:22:02 +0200 Miguel Ojeda…
Quoted 3 lines · Andreas Hindborg
I think widening to 128 bits is fine. My question is why
NSEC_PER_SEC as u128instead ofu128::from(NSEC_PER_SEC)?Yes, please avoid casts if possible.
Regarding
u128-- please make sure it works in 32-bit architectures. It seems like you are doing a 128-bit multiplication there?
You're right, sorry. I hadn't considered 32-bit architectures. 128-bit integers cannot be used on 32-bit, so I will switch to a u64/i64-based implementation.
Re: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
In reply to Andreas HindborgQuoted 53 lines · On Wed, 15 Jul 2026 15:33:59 +0200 Andreas Hindborg <[email protected]>…
Quoted 51 lines · FUJITA Tomonori
Quoted 20 lines · On Wed, 15 Jul 2026 08:57:03 +0200 Andreas Hindborg <[email protected]>…
Quoted 18 lines · FUJITA Tomonori
From: FUJITA Tomonori <[email protected]>
Callers that hand a timeout to some C APIs need conversion between Delta and jiffies.
Signed-off-by FUJITA Tomonori <[email protected]>--- rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)rust/kernel/time.rs +0
-0@@ -377,6 +377,20 @@ impl Delta {/// A span of time equal to zero. pub const ZERO :Self =Self { nanos:0 };Quoted 13 lines
rust/kernel/time.rs impl Delta { · line 388
Quoted 9 lines
rust/kernel/time.rs +9
-0+/// Create a new [`Delta`] from a number of jiffies. +/// +/// If `jiffies` is large enough that the corresponding number of nanoseconds +/// would overflow an `i64`, the result saturates to `i64::MAX` nanoseconds. +/// The exact threshold depends on `CONFIG_HZ`. +#[inline] +pub fn from_jiffies (jiffies:u64 ) ->Self { +let nanos = (u128::from (jiffies) *NSEC_PER_SEC as u128 / u128::from (bindings::HZ )) + .min (i64::MAX as u128 );In general for this patch, why are some widening operations using
fromand others useas u128? Is it not possible to use into/form for all the widening operations?When
NSEC_PER_SEC% HZ != 0, we need to multiply jiffies *NSEC_PER_SECbefore dividing by HZ.What the C side does is:
u64
jiffies64_to_nsecs(u64 j)
{#if !(NSEC_PER_SEC % HZ) return (NSEC_PER_SEC / HZ) * j; # else return div_u64(j * HZ_TO_NSEC_NUM, HZ_TO_NSEC_DEN); #endif }
Quoted 5 lines
Quoted 2 lines
We could replicate this with a cfg/the C side's const-eval computing. But I think using u128/i128 is simpler. What do you think?
I think widening to 128 bits is fine. My question is why
NSEC_PER_SEC as u128instead ofu128::from(NSEC_PER_SEC)?
NSEC_PER_SEC is defined as i64 because Delta stores its value as i64 so the other constructors can compute directly without any cast.
u128: From<T> is only implemented for unsigned integer sources:
error[E0277]: the trait bound u128: core::convert::From<i64> is not satisfied
--> /linux/rust/kernel/time.rs:373:44
|
373 | let nanos = (u128::from(jiffies) * u128::from(NSEC_PER_SEC) / u128::from(bindings::HZ))
| ^^^^ the trait `core::convert::From<i64>` is not implemented for `u128`
|
= help: `u128` implements trait `core::convert::From<T>`:
core::convert::From<bool>
core::convert::From<char>
core::convert::From<core::ascii::Char>
core::convert::From<core::net::Ipv6Addr>
core::convert::From<u16>
core::convert::From<u32>
core::convert::From<u64>
core::convert::From<u8>
and 4 othersNote that the u128 division here does not work on 32-bit architectures so I will switch to a different implementation in v3.
Re: [PATCH v2 1/4] rust: time: add jiffies conversion helpers to Delta
In reply to Gary GuoQuoted 8 lines · On Wed, 15 Jul 2026 15:38:17 +0100 "Gary Guo" <[email protected]> wrote:
Quoted 7 lines · Miguel Ojeda
Quoted 3 lines · Andreas Hindborg
I think widening to 128 bits is fine. My question is why
NSEC_PER_SEC as u128instead ofu128::from(NSEC_PER_SEC)?Yes, please avoid casts if possible.
Quoted 8 lines
Quoted 2 lines
Regarding
u128-- please make sure it works in 32-bit architectures. It seems like you are doing a 128-bit multiplication there?This will also need a division when HZ is not a factor of
NSEC_PER_SEC-- which will be the case forHZ_300.This should just limit the precision by doing a multiplication with (
USEC_PER_SEC/ HZ) likejiffies_to_usecs.
Agreed.
Device drivers use jiffies_to_usecs() rather than jiffies64_to_nsecs(), so the microsecond precision from a plain (USEC_PER_SEC / HZ) multiplication should be sufficient here.
I'll implement it with that logic in v3.