Skip to contentSkip to conversation

rust: time: fix Delta arithmetic and add math helpers

PATCH Applied chenhan 3 participants 11 messages Oct 31 – Nov 12

Subsystems (3)
lore
Share & tools
lore

chenhan

author
#0 lore raw

v5 cover rust: time: fix Delta arithmetic and add math helpers

This series fixes the architecture-dependent handling of invalid Delta division and remainder inputs, then moves the integer operations into a math module with Delta as its initial user.

V5 addresses Andreas's review [2] of v4 [1]:
- In patch 2, make the SAFETY comments cite the preceding zero-divisor check as establishing the non-zero divisor required by the C call.
- Keep the remainder output-pointer explanation and carry the same comments into the math helpers in patch 3.

The MIN/-1 checks remain for Rust's panic semantics. There are no changes to executable code, public APIs or panic conditions relative to v4. Patch 1 is unchanged and retains Tomonori's Reviewed-by. Patch 3 still awaits review of the tuple-returning interface introduced in v4. A range-diff against v4 follows below.

Patches 1 and 2 form the stable candidate pair: the parameter rename is a prerequisite for the behavior fix. Patch 3 introduces the math module separately and is not intended for stable.

The base remains timekeeping-next at 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38, unchanged on October 31. On rust-next at d89e1d186ec9271bf78e62771779e9fc03bf0fc3, patches 1 and 2 apply unchanged; patch 3 needs its lib.rs registration placed between maple_tree and mem. This was checked for application only; the runtime validation below used the declared base.

Tomonori's PWM series [3] also introduces rust/kernel/math.rs, with unsigned helpers. The module header is shared, and the signed and unsigned helpers are complementary. Whichever series is applied later will need a small rebase to keep one module declaration and header. Neither series is present in the above branch tips as of this posting.

V5 passes rustfmt and whitespace checks. Applying the exported patches reproduces each commit tree; the affected source at each series prefix is identical to v4 after excluding comments. QEMU was not rerun for this comment-only revision. V4 validation on x86-64 and ARMv7, with Rust overflow checks enabled and disabled, passed all 36 boots, 400 valid calls, 496 scalar comparisons and 32 expected panics. V4 also passed rustdoc generation on both architectures. Those results are unchanged evidence from v4, not new v5 runs; details are in [1].

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

chenhan (3):
rust: time: rename the rem_nanos() divisor
rust: time: make Delta division and remainder fail consistently
rust: math: add signed division and remainder helpers

 rust/kernel/lib.rs  |  1 +
 rust/kernel/math.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/time.rs | 47 ++++++++++--------------------
 3 files changed, 88 insertions(+), 31 deletions(-)
 create mode 100644 rust/kernel/math.rs

base-commit: 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38

Range-diff against v4:

1:  ed93030078ac = 1:  ed93030078ac rust: time: rename the rem_nanos() divisor
2:  ff344561eebb ! 2:  fdbb042d5743 rust: time: make Delta division and remainder fail consistently
    @@ rust/kernel/time.rs: fn div(self, rhs: Self) -> Self::Output {
              #[cfg(not(CONFIG_64BIT))]
              {
     -            // SAFETY: This function is always safe to call regardless of the input values
    -+            // SAFETY: The checks above exclude a zero divisor and `i64::MIN / -1`.
    ++            // SAFETY: `rhs.value` is non-zero due to the check above.
                  unsafe { bindings::div64_s64(self.value, rhs.value) }
              }
          }
    @@ rust/kernel/time.rs: pub fn rem_nanos(self, divisor: i32) -> Self {
                  let mut rem = 0;
      
     -            // SAFETY: `rem` is in the stack, so we can always provide a valid pointer to it.
    -+            // SAFETY: The checks above exclude a zero divisor and `i64::MIN / -1`.
    ++            // SAFETY: `divisor` is non-zero due to the check above.
     +            // `&mut rem` provides a valid, aligned, writable pointer for this call.
                  unsafe { bindings::div_s64_rem(self.as_nanos(), divisor, &mut rem) };

3: 63d7f5dd76f7 ! 3: 79891109d486 rust: math: add signed division and remainder helpers
@@ rust/kernel/math.rs (new)
+
+ #[cfg(not(CONFIG_64BIT))]
+ {
-+ // SAFETY: The checks above exclude a zero divisor and i64::MIN / -1.
++ // SAFETY: divisor is non-zero due to the check above.
+ unsafe { bindings::div64_s64(dividend, divisor) }
+ }
+}
@@ rust/kernel/math.rs (new)
+ {
+ let mut remainder = 0;
+
-+ // SAFETY: The checks above exclude a zero divisor and i64::MIN / -1.
++ // SAFETY: divisor is non-zero due to the check above.
+ // &mut remainder provides a valid, aligned, writable pointer for this call.
+ let quotient = unsafe { bindings::div_s64_rem(dividend, divisor, &mut remainder) };
+
@@ rust/kernel/time.rs: impl ops::Div for Delta {
-
- #[cfg(not(CONFIG_64BIT))]
- {
-- // SAFETY: The checks above exclude a zero divisor and i64::MIN / -1.
+- // SAFETY: rhs.value is non-zero due to the check above.
- unsafe { bindings::div64_s64(self.value, rhs.value) }
- }
+ math::div64_s64(self.value, rhs.value)
@@ rust/kernel/time.rs: pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {
- {
- let mut rem = 0;
-
-- // SAFETY: The checks above exclude a zero divisor and i64::MIN / -1.
+- // SAFETY: divisor is non-zero due to the check above.
- // &mut rem provides a valid, aligned, writable pointer for this call.
- unsafe { bindings::div_s64_rem(self.as_nanos(), divisor, &mut rem) };
-

Signature · 1 line
2.34.1
author
#1 lore raw

PATCH v5 1/3 rust: time: rename the rem_nanos() divisor

The argument to rem_nanos() is the divisor, while self holds the dividend. Rename the argument and correct the documentation. Drop the architecture-specific implementation explanation from the public API documentation; the argument type already states the divisor's width.

This does not change the function's type or behavior. It is a preparation for documenting and checking the invalid divisors in the next patch.

Cc [email protected] # prerequisite for the Delta division/remainder fix
Assisted-by LLM

---
Changes since v4: none.

 rust/kernel/time.rs | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
rust/kernel/time.rs +4 -7
index 5ae377e70dd8..16b44e82d2ac 100644
@@ -614,16 +614,13 @@ pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {
         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
-    /// limited to 32 bit dividends.
+    /// Return `self % divisor` where `divisor` is in nanoseconds.
     #[inline]
-    pub fn rem_nanos(self, dividend: i32) -> Self {
+    pub fn rem_nanos(self, divisor: i32) -> Self {
         #[cfg(CONFIG_64BIT)]
         {
             Self {
-                value: self.as_nanos() % i64::from(dividend),
+                value: self.as_nanos() % i64::from(divisor),
             }
         }
 
@@ -632,7 +629,7 @@ pub fn rem_nanos(self, dividend: i32) -> Self {
             let mut rem = 0;
 
             // SAFETY: `rem` is in the stack, so we can always provide a valid pointer to it.
-            unsafe { bindings::div_s64_rem(self.as_nanos(), dividend, &mut rem) };
+            unsafe { bindings::div_s64_rem(self.as_nanos(), divisor, &mut rem) };
 
             Self {
                 value: i64::from(rem),
Signature · 1 line
2.34.1
maintainer Reviewed-by on v5 1/3
#2 lore raw

Re: [PATCH v5 1/3] rust: time: rename the rem_nanos() divisor

Quoted 5 lines · chenhan

The argument to rem_nanos() is the divisor, while self holds the dividend. Rename the argument and correct the documentation. Drop the architecture-specific implementation explanation from the public API documentation; the argument type already states the divisor's width.

Quoted 7 lines

This does not change the function's type or behavior. It is a preparation for documenting and checking the invalid divisors in the next patch.

Cc [email protected] # prerequisite for the Delta division/remainder fix
Assisted-by LLM

Best regards,
Andreas Hindborg

maintainer Applied
#3 lore raw

Re: [PATCH v5 1/3] rust: time: rename the rem_nanos() divisor

In reply to chenhan
Quoted 9 lines · chenhan

The argument to rem_nanos() is the divisor, while self holds the dividend. Rename the argument and correct the documentation. Drop the architecture-specific implementation explanation from the public API documentation; the argument type already states the divisor's width.

This does not change the function's type or behavior. It is a preparation for documenting and checking the invalid divisors in the next patch.

[...]

Applied, thanks!

[1/3] rust: time: rename the rem_nanos() divisor

      commit: c6dce610f733d16849e5a8d491ddf080b839237c

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
author
#4 lore raw

PATCH v5 2/3 rust: time: make Delta division and remainder fail consistently

In reply to chenhan

Delta's division and rem_nanos() use Rust operators on 64-bit and C helpers on 32-bit. The report shows that rem_nanos(0) can return 10 for a 10 ns dividend on ARMv7, while the same call panics on x86-64. The i64::MIN / -1 case also differs, and neither API documents these inputs.

Check for zero divisors and i64::MIN with -1 before the architecture- specific code, and document the panic conditions on each method. This matches Rust's signed division and remainder operators, including when overflow checks are disabled. Valid-input results and API signatures are unchanged; invalid inputs now panic on 32-bit too.

No in-tree calls to either API were found at the base commit. The checks stay in the existing methods so the fix does not depend on introducing a math module.

Fixes 4521438fb076 ("rust: time: Implement basic arithmetic operations for Delta")
Assisted-by LLM

---
Changes since v4:
- Explain that the preceding zero-divisor check establishes the C call precondition; keep MIN/-1 checks for Rust panic semantics.
- Retain the output-pointer validity explanation for the remainder call.

 rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++--
 1 file changed, 28 insertions(+), 2 deletions(-)
rust/kernel/time.rs +28 -2
index 16b44e82d2ac..c9a2dc50ff4c 100644
@@ -412,8 +412,20 @@ fn mul_assign(&mut self, rhs: i64) {
 impl ops::Div for Delta {
     type Output = i64;
 
+    /// # Panics
+    ///
+    /// Panics if `rhs` is zero, or if `self` represents [`i64::MIN`] nanoseconds
+    /// and `rhs` represents `-1` nanosecond.
     #[inline]
     fn div(self, rhs: Self) -> Self::Output {
+        if rhs.value == 0 {
+            panic!("attempt to divide by zero");
+        }
+
+        if self.value == i64::MIN && rhs.value == -1 {
+            panic!("attempt to divide with overflow");
+        }
+
         #[cfg(CONFIG_64BIT)]
         {
             self.value / rhs.value
@@ -421,7 +433,7 @@ fn div(self, rhs: Self) -> Self::Output {
 
         #[cfg(not(CONFIG_64BIT))]
         {
-            // SAFETY: This function is always safe to call regardless of the input values
+            // SAFETY: `rhs.value` is non-zero due to the check above.
             unsafe { bindings::div64_s64(self.value, rhs.value) }
         }
     }
@@ -615,8 +627,21 @@ pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {
     }
 
     /// Return `self % divisor` where `divisor` is in nanoseconds.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `divisor` is zero, or if `self` represents [`i64::MIN`]
+    /// nanoseconds and `divisor` is `-1`.
     #[inline]
     pub fn rem_nanos(self, divisor: i32) -> Self {
+        if divisor == 0 {
+            panic!("attempt to calculate the remainder with a divisor of zero");
+        }
+
+        if self.value == i64::MIN && divisor == -1 {
+            panic!("attempt to calculate the remainder with overflow");
+        }
+
         #[cfg(CONFIG_64BIT)]
         {
             Self {
@@ -628,7 +653,8 @@ pub fn rem_nanos(self, divisor: i32) -> Self {
         {
             let mut rem = 0;
 
-            // SAFETY: `rem` is in the stack, so we can always provide a valid pointer to it.
+            // SAFETY: `divisor` is non-zero due to the check above.
+            // `&mut rem` provides a valid, aligned, writable pointer for this call.
             unsafe { bindings::div_s64_rem(self.as_nanos(), divisor, &mut rem) };
 
             Self {
Signature · 1 line
2.34.1
Reviewed-by on v5 2/3
#5 lore raw

Re: [PATCH v5 2/3] rust: time: make Delta division and remainder fail consistently

Quoted 15 lines · On Sat, 31 Oct 2026 18:32:05 +0800 chenhan <[email protected]> wrote:

Delta's division and rem_nanos() use Rust operators on 64-bit and C helpers on 32-bit. The report shows that rem_nanos(0) can return 10 for a 10 ns dividend on ARMv7, while the same call panics on x86-64. The i64::MIN / -1 case also differs, and neither API documents these inputs.

Check for zero divisors and i64::MIN with -1 before the architecture- specific code, and document the panic conditions on each method. This matches Rust's signed division and remainder operators, including when overflow checks are disabled. Valid-input results and API signatures are unchanged; invalid inputs now panic on 32-bit too.

No in-tree calls to either API were found at the base commit. The checks stay in the existing methods so the fix does not depend on introducing a math module.

Quoted 6 lines
Fixes 4521438fb076 ("rust: time: Implement basic arithmetic operations for Delta")
Assisted-by LLM
maintainer
#6 lore raw

Re: [PATCH v5 2/3] rust: time: make Delta division and remainder fail consistently

In reply to chenhan
Quoted 56 lines · chenhan

Delta's division and rem_nanos() use Rust operators on 64-bit and C helpers on 32-bit. The report shows that rem_nanos(0) can return 10 for a 10 ns dividend on ARMv7, while the same call panics on x86-64. The i64::MIN / -1 case also differs, and neither API documents these inputs.

Check for zero divisors and i64::MIN with -1 before the architecture- specific code, and document the panic conditions on each method. This matches Rust's signed division and remainder operators, including when overflow checks are disabled. Valid-input results and API signatures are unchanged; invalid inputs now panic on 32-bit too.

No in-tree calls to either API were found at the base commit. The checks stay in the existing methods so the fix does not depend on introducing a math module.

Fixes 4521438fb076 ("rust: time: Implement basic arithmetic operations for Delta")
Assisted-by LLM

---
Changes since v4:
- Explain that the preceding zero-divisor check establishes the C call precondition; keep MIN/-1 checks for Rust panic semantics.
- Retain the output-pointer validity explanation for the remainder call.

 rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++--
 1 file changed, 28 insertions(+), 2 deletions(-)
rust/kernel/time.rs +12 -0
index 16b44e82d2ac..c9a2dc50ff4c 100644
@@ -412,8 +412,20 @@ fn mul_assign(&mut self, rhs: i64) {
 impl ops::Div for Delta {
     type Output = i64;
 
+    /// # Panics
+    ///
+    /// Panics if `rhs` is zero, or if `self` represents [`i64::MIN`] nanoseconds
+    /// and `rhs` represents `-1` nanosecond.
     #[inline]
     fn div(self, rhs: Self) -> Self::Output {
+        if rhs.value == 0 {
+            panic!("attempt to divide by zero");
+        }
+
+        if self.value == i64::MIN && rhs.value == -1 {
+            panic!("attempt to divide with overflow");
+        }
+
         #[cfg(CONFIG_64BIT)]
         {
             self.value / rhs.value

rust/kernel/time.rs fn div(self, rhs: Self) -> Self::Output { · line 436

Quoted 5 lines
rust/kernel/time.rs +1 -1
@@ -421,7 +433,7 @@ fn div(self, rhs: Self) -> Self::Output {
 
         #[cfg(not(CONFIG_64BIT))]
         {
-            // SAFETY: This function is always safe to call regardless of the input values
+            // SAFETY: `rhs.value` is non-zero due to the check above.

Please add to the commit message that this safety requirement was wrong, and the commit fixes it.

Quoted 26 lines
rust/kernel/time.rs +13 -0
             unsafe { bindings::div64_s64(self.value, rhs.value) }
         }
     }
@@ -615,8 +627,21 @@ pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {
     }
 
     /// Return `self % divisor` where `divisor` is in nanoseconds.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `divisor` is zero, or if `self` represents [`i64::MIN`]
+    /// nanoseconds and `divisor` is `-1`.
     #[inline]
     pub fn rem_nanos(self, divisor: i32) -> Self {
+        if divisor == 0 {
+            panic!("attempt to calculate the remainder with a divisor of zero");
+        }
+
+        if self.value == i64::MIN && divisor == -1 {
+            panic!("attempt to calculate the remainder with overflow");
+        }
+
         #[cfg(CONFIG_64BIT)]
         {
             Self {

rust/kernel/time.rs pub fn rem_nanos(self, divisor: i32) -> Self { · line 657

Quoted 6 lines
rust/kernel/time.rs +2 -1
@@ -628,7 +653,8 @@ pub fn rem_nanos(self, divisor: i32) -> Self {
         {
             let mut rem = 0;
 
-            // SAFETY: `rem` is in the stack, so we can always provide a valid pointer to it.
+            // SAFETY: `divisor` is non-zero due to the check above.
+            // `&mut rem` provides a valid, aligned, writable pointer for this call.

Same.

Why did you change the wording of the original line?

Best regards,
Andreas Hindborg

maintainer Applied
#7 lore raw

Re: [PATCH v5 2/3] rust: time: make Delta division and remainder fail consistently

In reply to chenhan
Quoted 5 lines · chenhan

Delta's division and rem_nanos() use Rust operators on 64-bit and C helpers on 32-bit. The report shows that rem_nanos(0) can return 10 for a 10 ns dividend on ARMv7, while the same call panics on x86-64. The i64::MIN / -1 case also differs, and neither API documents these inputs.

Quoted 7 lines

Check for zero divisors and i64::MIN with -1 before the architecture- specific code, and document the panic conditions on each method. This matches Rust's signed division and remainder operators, including when overflow checks are disabled. Valid-input results and API signatures are unchanged; invalid inputs now panic on 32-bit too.

[...]

Applied, thanks!

[2/3] rust: time: make Delta division and remainder fail consistently

      commit: 9687257afe8c2c2c257e2168bc6c44e5145dc73a

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
author
#8 lore raw

PATCH v5 3/3 rust: math: add signed division and remainder helpers

In reply to chenhan

Delta's division and remainder implementations operate on integers and do not depend on time units. Move them into a math module to provide a common home for arithmetic helpers, with Delta as the initial user.

Expose div64_s64() for an i64 dividend and divisor, and div_s64_rem() for an i64 dividend and an i32 divisor. The latter returns an i64 quotient and an i32 remainder, matching the results of the C helper without exposing its output pointer. Delta's rem_nanos() uses the remainder and converts it to i64. Both helpers retain Rust's signed operator semantics and unconditional panic checks, using the existing C helpers on 32-bit.

Keep the Delta API and its panic conditions unchanged. Document the quotient and remainder semantics and link to the corresponding C header. This is separate from the preceding behavior fix so that introducing the math module is not required for a backport.

Assisted-by LLM

---
Changes since v4:
- Explain that the preceding zero-divisor check establishes the C call precondition; keep MIN/-1 checks for Rust panic semantics.
- Retain the output-pointer validity explanation for the remainder call.

 rust/kernel/lib.rs  |  1 +
 rust/kernel/math.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/time.rs | 50 ++++---------------------------
 3 files changed, 78 insertions(+), 44 deletions(-)
 create mode 100644 rust/kernel/math.rs
rust/kernel/lib.rs +1 -0
index 4d5c96ddc49c..60c2af705b47 100644
@@ -98,6 +98,7 @@
 pub mod kunit;
 pub mod list;
 pub mod maple_tree;
+pub mod math;
 pub mod miscdevice;
 pub mod mm;
 pub mod module;
rust/kernel/math.rs new file +71 -0

71 lines not on this page · raw message

rust/kernel/time.rs +6 -44

68 lines not on this page · raw message

Signature · 1 line
2.34.1
Reviewed-by on v5 3/3
#9 lore raw

Re: [PATCH v5 3/3] rust: math: add signed division and remainder helpers

Quoted 11 lines · On Sat, 31 Oct 2026 18:32:06 +0800 chenhan <[email protected]> wrote:

Delta's division and remainder implementations operate on integers and do not depend on time units. Move them into a math module to provide a common home for arithmetic helpers, with Delta as the initial user.

Expose div64_s64() for an i64 dividend and divisor, and div_s64_rem() for an i64 dividend and an i32 divisor. The latter returns an i64 quotient and an i32 remainder, matching the results of the C helper without exposing its output pointer. Delta's rem_nanos() uses the remainder and converts it to i64. Both helpers retain Rust's signed operator semantics and unconditional panic checks, using the existing C helpers on 32-bit.

Quoted 7 lines

Keep the Delta API and its panic conditions unchanged. Document the quotient and remainder semantics and link to the corresponding C header. This is separate from the preceding behavior fix so that introducing the math module is not required for a backport.

Assisted-by LLM

Two nits, only if you respin for other reasons:

The second sentence of the SAFETY comment in div_s64_rem() could be shorter. The old comment in time.rs said enough:

    // SAFETY: `rem` is in the stack, so we can always provide a valid
    // pointer to it.

The helpers have no examples. A doctest for each would also run as a KUnit test for the valid inputs on both 32-bit and 64-bit.

maintainer
#10 lore raw

Re: [PATCH v5 3/3] rust: math: add signed division and remainder helpers

In reply to chenhan
Quoted 11 lines · chenhan

Delta's division and remainder implementations operate on integers and do not depend on time units. Move them into a math module to provide a common home for arithmetic helpers, with Delta as the initial user.

Expose div64_s64() for an i64 dividend and divisor, and div_s64_rem() for an i64 dividend and an i32 divisor. The latter returns an i64 quotient and an i32 remainder, matching the results of the C helper without exposing its output pointer. Delta's rem_nanos() uses the remainder and converts it to i64. Both helpers retain Rust's signed operator semantics and unconditional panic checks, using the existing C helpers on 32-bit.

Quoted 7 lines

Keep the Delta API and its panic conditions unchanged. Document the quotient and remainder semantics and link to the corresponding C header. This is separate from the preceding behavior fix so that introducing the math module is not required for a backport.

Assisted-by LLM

Please add a doctest with a few asserts that demonstrate the use.

Best regards,
Andreas Hindborg