rust: time: fix Delta arithmetic and add math helpers
Subsystems (3)
v4 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.
V4 addresses Tomonori's follow-up review [1]:
- Add the math64.h link to the module documentation.
- Replace rem_s64() with div_s64_rem(i64, i32) -> (i64, i32), returning both quotient and remainder. Document the semantics and the i32 cast.
- Update Delta::rem_nanos() to use the remainder. Keep div64_s64() for full-width divisors and retain unconditional invalid-input checks.
- Extend local validation to call both public helpers directly and check both tuple elements, including i64::MIN / i32::MIN = (4294967296, 0).
Patches 1 and 2 have unchanged code. Patch 1 carries Tomonori's Reviewed-by; patch 2 is otherwise unchanged from v3. Patch 3 does not carry its v3 Reviewed-by because the public interface has changed. A range-diff against v3 [2] follows below.
Patches 1 and 2 form the stable candidate pair: the parameter rename is a prerequisite for the behavior fix. Patch 3 is separate and is not intended for stable. The caller recheck found no additional production users for the helpers; each still has one caller in Delta. No PWM or unsigned arithmetic changes are included.
The base remains timekeeping-next at 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38, unchanged on October 23. On rust-next at 7be4bc52fd9e0e55dc9a2e0232b89427d2c4b614, patches 1 and 2 apply unchanged. Patch 3 needs only the lib.rs module registration placed between maple_tree and the newly added mem module; the remaining changes apply unchanged. That integration was checked for application only; the runtime tests use the declared base.
Validation on x86-64 and ARMv7 QEMU passed with Rust overflow checks both enabled and disabled. A standalone built-in test module passes operands through black_box, calls Delta and the public math helpers, and compares results with literal expected values. Each configuration runs 100 valid calls (124 scalar comparisons) and eight separate boots for zero-divisor and MIN/-1 panics. All 36 boots passed, covering 400 valid calls, 496 scalar comparisons and 32 expected panics. The test module is local validation scaffolding, outside this series.
Both architectures also passed rustdoc generation, including the C header link. The fix-only validation from v3 remains applicable because the base and both prefix trees are identical; it was not rerun for v4 and is not included in the counts above.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] 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
Range-diff against v3:
1: 67c2d61e47da ! 1: ed93030078ac rust: time: rename the rem_nanos() divisor
@@ Commit message
for documenting and checking the invalid divisors in the next patch.
Cc: [email protected] # prerequisite for the Delta division/remainder fix
+ Reviewed-by: FUJITA Tomonori <[email protected]>
2: 25000522fc46 = 2: ff344561eebb rust: time: make Delta division and remainder fail consistently 3: 69a07812a676 ! 3: 63d7f5dd76f7 rust: math: add signed division and remainder helpers
@@ Commit message
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() and rem_s64() so driver crates can use these operations
- without constructing time values. The division helper takes two i64
- operands; the remainder helper takes an i64 dividend and an i32 divisor
- and returns an i64. Both keep Rust's signed operator semantics, including
- the unconditional panic checks, and use the existing C helpers on 32-bit.
+ 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 documentation unchanged. This is separate
- from the preceding behavior fix so that introducing the math module is
- not required for a backport.
+ 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.
@@ rust/kernel/math.rs (new)
+// SPDX-License-Identifier: GPL-2.0
+
+//! Integer arithmetic helpers.
++//!
++//! C header: [include/linux/math64.h](srctree/include/linux/math64.h).
+
+/// Divides an [i64] dividend by an [i64] divisor, rounding towards zero. +///
@@ rust/kernel/math.rs (new)
+ }
+}
+
-+/// Returns the remainder of an [i64] dividend divided by an [i32] divisor. ++/// Divides an [i64] dividend by an [i32] divisor, returning (quotient, remainder).
+///
-+/// A non-zero remainder has the sign of dividend.
++/// The quotient is rounded towards zero. A non-zero remainder has the sign of dividend.
+///
+/// # Panics
+///
+/// Panics if divisor is zero, or if dividend is [i64::MIN] and divisor is -1. +#[inline]
-+pub fn rem_s64(dividend: i64, divisor: i32) -> i64 {
++pub fn div_s64_rem(dividend: i64, divisor: i32) -> (i64, i32) {
+ if divisor == 0 {
-+ panic!("attempt to calculate the remainder with a divisor of zero");
++ panic!("attempt to divide by zero");
+ }
+
+ if dividend == i64::MIN && divisor == -1 {
-+ panic!("attempt to calculate the remainder with overflow");
++ panic!("attempt to divide with overflow");
+ }
+
+ #[cfg(CONFIG_64BIT)]
+ {
-+ dividend % i64::from(divisor)
++ let divisor = i64::from(divisor);
++ let quotient = dividend / divisor;
++ let remainder = dividend % divisor;
++
++ // CAST: |remainder| < |divisor| <= 2^31, so the remainder fits in i32.
++ (quotient, remainder as i32)
+ }
+
+ #[cfg(not(CONFIG_64BIT))]
+ {
-+ let mut rem = 0;
++ let mut remainder = 0;
+
+ // SAFETY: The checks above exclude a zero divisor and i64::MIN / -1.
-+ // &mut rem provides a valid, aligned, writable pointer for this call.
-+ unsafe { bindings::div_s64_rem(dividend, divisor, &mut rem) };
++ // &mut remainder provides a valid, aligned, writable pointer for this call.
++ let quotient = unsafe { bindings::div_s64_rem(dividend, divisor, &mut remainder) };
+
-+ i64::from(rem)
++ (quotient, remainder)
+ }
+}
@@ rust/kernel/time.rs: pub fn to_jiffies_timeout(self) -> Delta<Jiffy> {
- Self {
- value: i64::from(rem),
- }
++ let (_, remainder) = math::div_s64_rem(self.as_nanos(), divisor);
+ Self {
-+ value: math::rem_s64(self.as_nanos(), divisor),
++ value: i64::from(remainder),
}
}
}
base-commit: 2ea0119f72dba597aa8a98cbdb72c564bfc5cb38
Signature · 1 line
2.34.1
PATCH v4 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.
---
Changes since v3:
- Carry FUJITA Tomonori's Reviewed-by; code unchanged.
rust/kernel/time.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-)
rust/kernel/time.rs +4 -7
@@ -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
PATCH v4 2/3 rust: time: make Delta division and remainder fail consistently
In reply to chenhanDelta'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.
---
Changes since v3: none.
rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-)
rust/kernel/time.rs +28 -2
@@ -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: The checks above exclude a zero divisor and `i64::MIN / -1`. 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: The checks above exclude a zero divisor and `i64::MIN / -1`. +// `&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
Andreas Hindborg
maintainerRe: [PATCH v4 2/3] rust: time: make Delta division and remainder fail consistently
Quoted 53 lines · chenhan
Delta's division and
rem_nanos()use Rust operators on 64-bit and C helpers on 32-bit. The report shows thatrem_nanos(0)can return 10 for a 10 ns dividend on ARMv7, while the same call panics on x86-64. Thei64::MIN/ -1 case also differs, and neither API documents these inputs.Check for zero divisors and
i64::MINwith -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")Reported-by Georgios Androutsopoulos <[email protected]>Assisted-by LLMSigned-off-by chenhan <[email protected]>---
Changes since v3: none.rust/kernel/time.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-)rust/kernel/time.rs +12
-0@@ -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: The checks above exclude a zero divisor and `i64::MIN / -1`.
Why change the safety comment here? If the function is always safe to call, the exclusion is not relevant. Was the old comment wrong?
Quoted 26 lines
rust/kernel/time.rs +13
-0unsafe { 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: The checks above exclude a zero divisor and `i64::MIN / -1`. +// `&mut rem` provides a valid, aligned, writable pointer for this call.
Again, was the old safety comment wrong?
Once kunit supports the #[should_panic] attribute, we can assert the behavior on all platforms.
Best regards,
Andreas Hindborg
Re: [PATCH v4 2/3] rust: time: make Delta division and remainder fail consistently
Hi Andreas,
Thanks for asking. I should have distinguished the non-zero-divisor requirement from the MIN/-1 check in those comments.
Quoted 2 lines
Why change the safety comment here? If the function is always safe to call, the exclusion is not relevant. Was the old comment wrong?
The old "regardless of the input values" statement is too broad. In the generic 32-bit implementation, div64_s64() goes through div64_u64() and div_u64_rem() to do_div(). The latter contains C division and remainder operations which require a non-zero divisor. The kernel's -fno-strict-overflow does not define division by zero. An architecture's divide-by-zero handling therefore does not establish that the C call is safe for every input across implementations.
The zero-divisor check above the call supplies that precondition. I have updated the local comments for the next revision to cite that check explicitly, without grouping it with MIN/-1. For the division call:
// SAFETY: `rhs.value` is non-zero due to the check above.
The MIN/-1 check preserves Rust's panic semantics; the generic 32-bit helpers use unsigned magnitude division and wrapping sign arithmetic, so I should not present its rejection as a necessary safety precondition of those implementations.
Quoted 1 line
Again, was the old safety comment wrong?
The old pointer explanation was correct: the local rem supplies valid storage for the output. I expanded it to make the validity, alignment and writability of &mut rem explicit. The signed remainder helper also reaches the division path above, so the comment should explain both the non-zero divisor, established by the check, and the valid output pointer. The updated comments keep these separate from the MIN/-1 behavior check; both runtime checks are unchanged.
I have made the corresponding comment changes in the math helpers in patch 3 as well, so the explanation remains consistent after extraction.
Quoted 2 lines
Once kunit supports the
#[should_panic]attribute, we can assert the behavior on all platforms.
Agreed; that would let us keep these panic cases as in-tree regression tests when the support is available.
Best regards,
chenhan
PATCH v4 3/3 rust: math: add signed division and remainder helpers
In reply to chenhanDelta'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.
---
Changes since v3:
- Link the module documentation to include/linux/math64.h.
- Replace rem_s64() with div_s64_rem(), returning (i64, i32).
- Document quotient/remainder semantics and explain the i32 cast.
- Adapt Delta and directly test both public helpers.
FUJITA provided a Reviewed-by for v3. It is not carried here because this revision changes the public API to return both results; a fresh review of that change is requested.
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
@@ -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