From ec90dfcf05f02206c280bb59af660bbb3ae177d0 Mon Sep 17 00:00:00 2001 From: FUJITA Tomonori Date: Fri, 7 Aug 2026 22:05:31 +0900 Subject: rust: time: fix as_micros_ceil() rounding near i64::MAX The ceiling adjustment used saturating_add(NSEC_PER_USEC - 1) before dividing. Once the nanosecond value gets within NSEC_PER_USEC - 1 of i64::MAX the addition saturates to i64::MAX, which drops the ceiling bias and can yield a result one microsecond too small. Fixes: fae0cdc12340 ("rust: time: Introduce Delta type") Reported-by: Miguel Ojeda Closes: https://lore.kernel.org/rust-for-linux/CANiq72mtS0ABA2JnT5tpz6J9c_mnxY+vyPvghV_ukngWvN8F2w@mail.gmail.com/ Signed-off-by: FUJITA Tomonori Acked-by: Andreas Hindborg Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20260807130531.1056209-1-tomo@flapping.org Signed-off-by: Miguel Ojeda --- rust/kernel/time.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to 'rust/kernel') diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index b8463823aed9..54fc46d460b6 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -441,22 +441,25 @@ impl Delta { /// to the value in the [`Delta`]. #[inline] pub fn as_micros_ceil(self) -> i64 { + // Only positive values need to be rounded up: truncating division already + // rounds towards zero, i.e. up, for negative values. + // + // The usual `(nanos + d - 1) / d` is not used because the addition overflows + // once `nanos` exceeds `i64::MAX - (d - 1)`; saturating the addition instead + // would drop the rounding bias and return a result one unit too small. let n = self.as_nanos(); - let n = if n >= 0 { - n.saturating_add(NSEC_PER_USEC - 1) - } else { - n - }; + + let (n, add) = if n > 0 { (n - 1, 1) } else { (n, 0) }; #[cfg(CONFIG_64BIT)] { - n / NSEC_PER_USEC + n / NSEC_PER_USEC + add } #[cfg(not(CONFIG_64BIT))] // SAFETY: It is always safe to call `ktime_to_us()` with any value. unsafe { - bindings::ktime_to_us(n) + bindings::ktime_to_us(n) + add } } -- cgit v1.2.3