Skip to contentSkip to conversation

Add Delta::to_jiffies_timeout()

PATCH Superseded FUJITA Tomonori 3 participants 7 messages Sep 8 – Sep 24

Subsystems (2)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 cover Add Delta::to_jiffies_timeout()

From: FUJITA Tomonori <[email protected]>

The first patch makes bindings::HZ resolve to CONFIG_HZ.

The second patch was previously posted as patch 4 of [1]; patches 1-3 of that series have been applied. It has been reworked.

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

---
v3:
- Add the first patch to set bindings::HZ to CONFIG_HZ.
- Drop the CONFIG_HZ workaround.
v2: https://lore.kernel.org/rust-for-linux/[email protected]/
- Use mul_u64_add_u64_div_u64() instead of __msecs_to_jiffies().
- Dropped the as_millis_ceil() example and KUnit test patch; the conversion no longer uses as_millis_ceil(). Will send it separately.
v1: https://lore.kernel.org/rust-for-linux/[email protected]/

FUJITA Tomonori (2):
rust: bindings: set HZ to CONFIG_HZ
rust: time: add Delta::to_jiffies_timeout() for timeout conversion

 rust/bindings/lib.rs     |   5 ++
 rust/helpers/helpers.c   |   1 +
 rust/helpers/math.c      |   8 +++
 rust/kernel/Kconfig.test |  10 ++++
 rust/kernel/time.rs      | 105 +++++++++++++++++++++++++++++++++++++++
 5 files changed, 129 insertions(+)
 create mode 100644 rust/helpers/math.c

base-commit: 28924df2a08f440c73991b83028032c901de2ae4

Signature · 1 line
2.43.0
#1 lore raw

PATCH v3 1/2 rust: bindings: set HZ to CONFIG_HZ

From: FUJITA Tomonori <[email protected]>

include/uapi/asm-generic/param.h defines HZ as __USER_HZ and include/asm-generic/param.h then sets it to CONFIG_HZ. bindgen keeps the first definition of a macro and ignores a later #undef, so the generated binding is __USER_HZ.

Redefine HZ in rust/bindings/lib.rs, the same way compat_ptr_ioctl is redefined there. Nothing in the tree reads bindings::HZ today, so this prevents accidental misuse rather than fixing a bug.

---
 rust/bindings/lib.rs | 5 +++++
 1 file changed, 5 insertions(+)
rust/bindings/lib.rs +5 -0
index 812f8e5a08d5..c17e6c2b775f 100644
@@ -81,3 +81,8 @@ mod bindings_helper {
         None
     }
 };
+
+// `bindgen` keeps the first definition of a macro and ignores a later `#undef`.
+// The generated `HZ` is therefore `__USER_HZ` from
+// `include/uapi/asm-generic/param.h`, not `CONFIG_HZ`.
+pub const HZ: u32 = CONFIG_HZ;
Signature · 1 line
2.43.0
reviewer Reviewed-by on v3 1/2
#2 lore raw

Re: [PATCH v3 1/2] rust: bindings: set HZ to CONFIG_HZ

Quoted 7 lines · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

include/uapi/asm-generic/param.h defines HZ as __USER_HZ and include/asm-generic/param.h then sets it to CONFIG_HZ. bindgen keeps the first definition of a macro and ignores a later #undef, so the generated binding is __USER_HZ.

Quoted 6 lines

Redefine HZ in rust/bindings/lib.rs, the same way compat_ptr_ioctl is redefined there. Nothing in the tree reads bindings::HZ today, so this prevents accidental misuse rather than fixing a bug.

Quoted 3 lines
---
 rust/bindings/lib.rs | 5 +++++
 1 file changed, 5 insertions(+)
#3 lore raw

PATCH v3 2/2 rust: time: add Delta::to_jiffies_timeout() for timeout conversion

In reply to FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

The boundaries of __msecs_to_jiffies() and nsecs_to_jiffies64() depend on which HZ branch is compiled. With CONFIG_HZ_300 nsecs_to_jiffies64() overflows after 64.99 years, which is less than the 292 years a Delta can hold. With HZ=1000 a jiffy is a millisecond, so __msecs_to_jiffies() returns its argument unchanged and never caps it at MAX_JIFFY_OFFSET.

Compute the conversion in Rust with mul_u64_add_u64_div_u64() instead. It returns (a * b + c) / d, computing a * b internally in 128 bits, so ceil(nanos * HZ / NSEC_PER_SEC) needs no input clamp and rounds once. The bound then follows from the arithmetic: with HZ <= NSEC_PER_SEC, which a static_assert() checks, the result is at most the nanosecond count.

Unless the result saturates, the value is rounded up, so the timeout is never shorter than the requested span. It saturates at zero jiffies for a negative span, i.e. an immediate timeout, and at MAX_JIFFY_OFFSET, the upper bound the kernel uses for a jiffies span. Since MAX_JIFFY_OFFSET is derived from long, only 32 bit can reach it, and a saturated timeout there is finite, so it can be shorter than the requested span.

---
 rust/helpers/helpers.c   |   1 +
 rust/helpers/math.c      |   8 +++
 rust/kernel/Kconfig.test |  10 ++++
 rust/kernel/time.rs      | 105 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 124 insertions(+)
 create mode 100644 rust/helpers/math.c
rust/helpers/helpers.c +1 -0
index 440fb7638e3c..08374b163774 100644
@@ -73,6 +73,7 @@
 #include "kunit.c"
 #include "list.c"
 #include "maple_tree.c"
+#include "math.c"
 #include "mm.c"
 #include "mutex.c"
 #include "net/genetlink.c"
rust/helpers/math.c new file +8 -0
new file mode 100644
index 000000000000..e2ee29bcce0f
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/math64.h>
+
+__rust_helper u64 rust_helper_mul_u64_add_u64_div_u64(u64 a, u64 b, u64 c, u64 d)
+{
+	return mul_u64_add_u64_div_u64(a, b, c, d);
+}
rust/kernel/Kconfig.test +10 -0
index e6a5c7a795f0..0087749995d2 100644
@@ -83,4 +83,14 @@ config RUST_BITFIELD_KUNIT_TEST
 
 	  If unsure, say N.
 
+config RUST_TIME_KUNIT_TEST
+	bool "KUnit tests for the Rust time API" if !KUNIT_ALL_TESTS
+	default KUNIT_ALL_TESTS
+	help
+	  This option enables KUnit tests for the Rust time API.
+	  These are only for development and testing, not for regular
+	  kernel use cases.
+
+	  If unsure, say N.
+
 endif
rust/kernel/time.rs +105 -0

120 lines not on this page · raw message

Signature · 1 line
2.43.0
reviewer Reviewed-by on v3 2/2
#4 lore raw

Re: [PATCH v3 2/2] rust: time: add Delta::to_jiffies_timeout() for timeout conversion

Quoted 15 lines · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

The boundaries of __msecs_to_jiffies() and nsecs_to_jiffies64() depend on which HZ branch is compiled. With CONFIG_HZ_300 nsecs_to_jiffies64() overflows after 64.99 years, which is less than the 292 years a Delta can hold. With HZ=1000 a jiffy is a millisecond, so __msecs_to_jiffies() returns its argument unchanged and never caps it at MAX_JIFFY_OFFSET.

Compute the conversion in Rust with mul_u64_add_u64_div_u64() instead. It returns (a * b + c) / d, computing a * b internally in 128 bits, so ceil(nanos * HZ / NSEC_PER_SEC) needs no input clamp and rounds once. The bound then follows from the arithmetic: with HZ <= NSEC_PER_SEC, which a static_assert() checks, the result is at most the nanosecond count.

Quoted 8 lines

Unless the result saturates, the value is rounded up, so the timeout is never shorter than the requested span. It saturates at zero jiffies for a negative span, i.e. an immediate timeout, and at MAX_JIFFY_OFFSET, the upper bound the kernel uses for a jiffies span. Since MAX_JIFFY_OFFSET is derived from long, only 32 bit can reach it, and a saturated timeout there is finite, so it can be shorter than the requested span.

With a nit below.

Quoted 96 lines
---
 rust/helpers/helpers.c   |   1 +
 rust/helpers/math.c      |   8 +++
 rust/kernel/Kconfig.test |  10 ++++
 rust/kernel/time.rs      | 105 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 124 insertions(+)
 create mode 100644 rust/helpers/math.c
rust/helpers/helpers.c +1 -0
index 440fb7638e3c..08374b163774 100644
@@ -73,6 +73,7 @@
 #include "kunit.c"
 #include "list.c"
 #include "maple_tree.c"
+#include "math.c"
 #include "mm.c"
 #include "mutex.c"
 #include "net/genetlink.c"
rust/helpers/math.c new file +8 -0
new file mode 100644
index 000000000000..e2ee29bcce0f
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/math64.h>
+
+__rust_helper u64 rust_helper_mul_u64_add_u64_div_u64(u64 a, u64 b, u64 c, u64 d)
+{
+	return mul_u64_add_u64_div_u64(a, b, c, d);
+}
rust/kernel/Kconfig.test +10 -0
index e6a5c7a795f0..0087749995d2 100644
@@ -83,4 +83,14 @@ config RUST_BITFIELD_KUNIT_TEST
 
 	  If unsure, say N.
 
+config RUST_TIME_KUNIT_TEST
+	bool "KUnit tests for the Rust time API" if !KUNIT_ALL_TESTS
+	default KUNIT_ALL_TESTS
+	help
+	  This option enables KUnit tests for the Rust time API.
+	  These are only for development and testing, not for regular
+	  kernel use cases.
+
+	  If unsure, say N.
+
 endif
rust/kernel/time.rs +28 -0
index 6c0a5e8090d0..9e66c39f823c 100644
@@ -39,6 +39,10 @@
 /// The number of nanoseconds per second.
 pub const NSEC_PER_SEC: i64 = bindings::NSEC_PER_SEC as i64;
 
+/// The C side `MAX_JIFFY_OFFSET`, i.e. `((LONG_MAX >> 1) - 1)`. It is the upper
+/// bound the kernel uses for a jiffies span, not a wait-forever value.
+const MAX_JIFFY_OFFSET: isize = (isize::MAX >> 1) - 1;
+
 /// The time unit of Linux kernel. One jiffy equals (1/HZ) second.
 pub type Jiffies = crate::ffi::c_ulong;
 
@@ -554,6 +558,62 @@ pub fn as_millis_ceil(self) -> i64 {
         }
     }
 
+    /// Convert this span to a [`Delta<Jiffy>`] suitable for use as a timeout.
+    ///
+    /// Unless the result saturates, the value is rounded up to the next whole
+    /// jiffy, so the resulting timeout is never shorter than `self`.
+    ///
+    /// A negative span saturates at zero jiffies, i.e. an immediate timeout.
+    ///
+    /// A span that does not fit saturates at the kernel's [`MAX_JIFFY_OFFSET`],
+    /// the upper bound for a jiffies span. That is a finite timeout, so a
+    /// saturated result can be shorter than the requested span. It is derived
+    /// from `long`, so only 32 bit can reach it, at about 12 days with `HZ=1000`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::time::Delta;
+    ///
+    /// // A negative span is an immediate timeout.
+    /// assert_eq!(Delta::from_millis(-1).to_jiffies_timeout().as_jiffies(), 0);
+    ///
+    /// // A span shorter than a jiffy still waits, i.e. the timeout is never
+    /// // shorter than the span.
+    /// assert!(Delta::from_nanos(1).to_jiffies_timeout().as_jiffies() >= 1);
+    /// ```

rust/kernel/time.rs pub fn as_millis_ceil(self) -> i64 { · line 594

Quoted 10 lines
rust/kernel/time.rs +10 -0
+    ///
+    /// [`MAX_JIFFY_OFFSET`]: srctree/include/linux/jiffies.h
+    #[inline]
+    pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {
+        const HZ: u64 = bindings::HZ as u64;
+
+        // The quotient `(nsecs * HZ + NSEC_PER_SEC - 1) / NSEC_PER_SEC` has to fit in
+        // `u64`; `nsecs * HZ` does not. With `HZ <= NSEC_PER_SEC` the numerator is at
+        // most `(nsecs + 1) * NSEC_PER_SEC - 1`, so the quotient is at most `nsecs`.
+        crate::static_assert!(HZ <= NSEC_PER_SEC as u64);

I'm pretty sure we'll never want to a tick per ns, but hey maybe that'll not be true for a future 5000000 GHz processor :)

rust/kernel/time.rs pub fn as_millis_ceil(self) -> i64 { · line 597

Quoted 3 lines
rust/kernel/time.rs +3 -0
+
+        // CAST: `max()` makes the value non-negative, so the cast keeps it.
+        let nsecs = self.as_nanos().max(0) as u64;

Please use fn syntax and have core::cmp::max(self.as_nanos(), 0) or u64::max(..). Due to the method syntax hinting some action is taking place, many people find it confusing, because you can easily understand .max it as "clamp to a max of" while it actually means "clamp to a min of".

See https://internals.rust-lang.org/t/am-i-the-only-one-confused-by-a-min-b-and-a-max-b/13252

I'm somewhat surprised that Clippy doesn't have a restriction lint for this, though.

Best,
Gary

Quoted 22 lines
rust/kernel/time.rs +19 -0
+
+        // SAFETY: `mul_u64_add_u64_div_u64()` must not be called with a zero divisor,
+        // and its result must fit in `u64`. `NSEC_PER_SEC` is a non-zero constant, and
+        // the assertion above bounds the quotient by `nsecs`.
+        let jiffies = unsafe {
+            bindings::mul_u64_add_u64_div_u64(
+                nsecs,
+                HZ,
+                (NSEC_PER_SEC - 1) as u64,
+                NSEC_PER_SEC as u64,
+            )
+        };
+
+        // CAST: `jiffies` is clamped to `MAX_JIFFY_OFFSET`, which is `<= isize::MAX`.
+        let jiffies = jiffies.min(MAX_JIFFY_OFFSET as u64) as isize;
+
+        Delta::<Jiffy>::from_jiffies(jiffies)
+    }
+
     /// 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
#5 lore raw

Re: [PATCH v3 2/2] rust: time: add Delta::to_jiffies_timeout() for timeout conversion

Quoted 9 lines · On Wed, 23 Sep 2026 11:22:47 +0100 "Gary Guo" <[email protected]> wrote:

rust/kernel/time.rs pub fn as_millis_ceil(self) -> i64 { · line 597

Quoted 2 lines
rust/kernel/time.rs +2 -0
+        // CAST: `max()` makes the value non-negative, so the cast keeps it.
+        let nsecs = self.as_nanos().max(0) as u64;

Please use fn syntax and have core::cmp::max(self.as_nanos(), 0) or u64::max(..). Due to the method syntax hinting some action is taking place, many people find it confusing, because you can easily understand .max it as "clamp to a max of" while it actually means "clamp to a min of".

See https://internals.rust-lang.org/t/am-i-the-only-one-confused-by-a-min-b-and-a-max-b/13252

Makes sense. Fixed in v4:

https://lore.kernel.org/all/[email protected]/

Thanks for reviewing the patches!

maintainer
#6 lore raw
In reply to FUJITA Tomonori

Hi Tomo,

Quoted 8 lines · FUJITA Tomonori

From: FUJITA Tomonori <[email protected]>

The first patch makes bindings::HZ resolve to CONFIG_HZ.

The second patch was previously posted as patch 4 of [1]; patches 1-3 of that series have been applied. It has been reworked.

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

I'm waiting for some review tags on this series so that I can stage it.

Best regards,
Andreas Hindborg