Re: [PATCH v6 4/7] rust: time: add Delta::to_jiffies_timeout() for timeout conversion

"Gary Guo" <[email protected]>
Newsgroups org.kernel.vger.rust-for-linux
Message-ID <[email protected]>
On Sat Aug 8, 2026 at 7:28 AM BST, FUJITA Tomonori wrote:
> 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(+)
>
> diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
> index af144d251f47..83891dab3aa7 100644
> --- a/rust/kernel/time.rs
> +++ b/rust/kernel/time.rs
> @@ -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(jiffies as 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


> +
>      /// 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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.