Rust for Linux List
 help / color / mirror / Atom feed
From: Franklin-Qi <yusq77@gmail.com>
To: Andreas Hindborg <a.hindborg@kernel.org>,
	Lyude Paul <lyude@redhat.com>, Miguel Ojeda <ojeda@kernel.org>,
	Alice Ryhl <aliceryhl@google.com>
Cc: FUJITA Tomonori <fujita.tomonori@gmail.com>,
	FUJITA Tomonori <tomo@flapping.org>,
	Boqun Feng <boqun@kernel.org>, Danilo Krummrich <dakr@kernel.org>,
	rust-for-linux@vger.kernel.org, Thomas Gleixner <tglx@kernel.org>,
	John Stultz <jstultz@google.com>, Stephen Boyd <sboyd@kernel.org>,
	Frederic Weisbecker <frederic@kernel.org>,
	Anna-Maria Behnsen <anna-maria@linutronix.de>,
	Georgios Androutsopoulos <georgeandrout13@gmail.com>,
	stable@vger.kernel.org, Franklin-Qi <yusq77@gmail.com>
Subject: [PATCH v3 1/2] rust: time: keep Instant invariant when adding/subtracting Delta
Date: Thu,  3 Dec 2026 17:21:00 +0800	[thread overview]
Message-ID: <20261203092101.63850-2-yusq77@gmail.com> (raw)
In-Reply-To: <20261203092101.63850-1-yusq77@gmail.com>

Instant documents inner in 0..=KTIME_MAX, but Add/Sub<Delta> only
asserted non-negativity under CONFIG_RUST_OVERFLOW_CHECKS. With checks
disabled, a negative result can be returned, and an addition past
KTIME_MAX silently wraps. A later Instant-Instant subtraction relies on
the invariant and may no longer be overflow-safe.

Keep the existing behaviour under CONFIG_RUST_OVERFLOW_CHECKS and panic
if the result is out of range. Without overflow checks, use saturating
arithmetic and clamp into 0..=KTIME_MAX, printing a warning once for both
a negative result and a saturation at KTIME_MAX, so the invariant is
preserved without crashing the kernel.

Document the panic and clamping conditions in the operators' rustdoc.

Fixes: 22b65a40574e ("rust: time: Implement Add<Delta>/Sub<Delta> for Instant")
Cc: stable@vger.kernel.org
Reported-by: Georgios Androutsopoulos <georgeandrout13@gmail.com>
Closes: https://github.com/Rust-for-Linux/linux/issues/1272

Signed-off-by: Franklin-Qi <yusq77@gmail.com>
---
Changes in v3:
- Rebased onto timekeeping-next (Instant is now Instant<C, Nsec>).
- Without overflow checks, also warn once when saturating to KTIME_MAX,
  not only when clamping a negative result (Tomonori).
- Update the rustdoc to match.

v2: https://lore.kernel.org/rust-for-linux/20261202080227.898512-1-yusq77@gmail.com/

 rust/kernel/time.rs | 101 +++++++++++++++++++++++++++++++++++---------
 1 file changed, 81 insertions(+), 20 deletions(-)

diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index 0782fdb06bfc..4ff65c74b5b5 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -256,6 +256,51 @@ pub fn elapsed(&self) -> Delta {
     pub(crate) fn as_nanos(&self) -> i64 {
         self.inner
     }
+
+    /// Create an [`Instant`] from the result of an arithmetic operation.
+    ///
+    /// With overflow checks disabled, `sat` is the saturating result and `wrap` is the wrapping
+    /// result of the same operation. A mismatch means the `i64` range was exceeded; a negative
+    /// `sat` means the result fell below 0. Both cases print a warning once and clamp into
+    /// `0..=KTIME_MAX` (`KTIME_MAX` equals `i64::MAX`).
+    ///
+    /// # Panics
+    ///
+    /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and `sat` is negative.
+    #[inline]
+    fn from_arithmetic(sat: bindings::ktime_t, wrap: bindings::ktime_t) -> Self {
+        #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
+        {
+            let _ = wrap;
+            // INVARIANT: With overflow checks enabled, we verify here that the value is >= 0.
+            // An overflow above `KTIME_MAX` already panicked in the caller.
+            assert!(sat >= 0);
+
+            Self {
+                inner: sat,
+                _c: PhantomData,
+            }
+        }
+
+        #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))]
+        {
+            // INVARIANT: Without overflow checks, clamp into `0..=KTIME_MAX` and warn once when
+            // the raw operation would have left that range.
+            let inner = if sat != wrap || sat < 0 {
+                crate::pr_warn_once!(
+                    "Instant arithmetic produced an out-of-range value, clamping\n"
+                );
+                if sat < 0 { 0 } else { sat }
+            } else {
+                sat
+            };
+
+            Self {
+                inner,
+                _c: PhantomData,
+            }
+        }
+    }
 }
 
 impl<C: ClockId> ops::Sub for Instant<C, Nsec> {
@@ -273,40 +318,56 @@ fn sub(self, other: Instant<C>) -> Delta {
 impl<T: ClockId> ops::Add<Delta> for Instant<T, Nsec> {
     type Output = Self;
 
+    /// # Panics
+    ///
+    /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and the result is negative or greater
+    /// than `KTIME_MAX`.
+    ///
+    /// Otherwise, the result is clamped to the range from 0 to `KTIME_MAX` and a warning is
+    /// printed once.
     #[inline]
     fn add(self, rhs: Delta) -> Self::Output {
-        // INVARIANT: With arithmetic over/underflow checks enabled, this will panic if we overflow
-        // (e.g. go above `KTIME_MAX`)
-        let res = self.inner + rhs.value;
-
-        // INVARIANT: With overflow checks enabled, we verify here that the value is >= 0
         #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
-        assert!(res >= 0);
+        // With overflow checks enabled, this panics if we overflow (e.g. go above `KTIME_MAX`).
+        let (sat, wrap) = {
+            let res = self.inner + rhs.value;
+            (res, res)
+        };
+        #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))]
+        let (sat, wrap) = (
+            self.inner.saturating_add(rhs.value),
+            self.inner.wrapping_add(rhs.value),
+        );
 
-        Self {
-            inner: res,
-            _c: PhantomData,
-        }
+        Self::from_arithmetic(sat, wrap)
     }
 }
 
 impl<T: ClockId> ops::Sub<Delta> for Instant<T, Nsec> {
     type Output = Self;
 
+    /// # Panics
+    ///
+    /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and the result is negative or greater
+    /// than `KTIME_MAX`.
+    ///
+    /// Otherwise, the result is clamped to the range from 0 to `KTIME_MAX` and a warning is
+    /// printed once.
     #[inline]
     fn sub(self, rhs: Delta) -> Self::Output {
-        // INVARIANT: With arithmetic over/underflow checks enabled, this will panic if we overflow
-        // (e.g. go above `KTIME_MAX`)
-        let res = self.inner - rhs.value;
-
-        // INVARIANT: With overflow checks enabled, we verify here that the value is >= 0
         #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
-        assert!(res >= 0);
+        // With overflow checks enabled, this panics if we overflow (e.g. go above `KTIME_MAX`).
+        let (sat, wrap) = {
+            let res = self.inner - rhs.value;
+            (res, res)
+        };
+        #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))]
+        let (sat, wrap) = (
+            self.inner.saturating_sub(rhs.value),
+            self.inner.wrapping_sub(rhs.value),
+        );
 
-        Self {
-            inner: res,
-            _c: PhantomData,
-        }
+        Self::from_arithmetic(sat, wrap)
     }
 }
 
-- 
2.55.0


  reply	other threads:[~2026-12-03  9:21 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02  8:02 [PATCH v2] rust: time: keep Instant invariant when adding/subtracting Delta Franklin-Qi
2026-12-02 11:27 ` FUJITA Tomonori
2026-12-03  9:20   ` Franklin-Qi
2026-12-03  9:20 ` [PATCH v3 0/2] " Franklin-Qi
2026-12-03  9:21   ` Franklin-Qi [this message]
2026-12-03  9:21   ` [PATCH v3 2/2] rust: time: add KUnit tests for Instant Delta clamping Franklin-Qi

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261203092101.63850-2-yusq77@gmail.com \
    --to=yusq77@gmail.com \
    --cc=a.hindborg@kernel.org \
    --cc=aliceryhl@google.com \
    --cc=anna-maria@linutronix.de \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=frederic@kernel.org \
    --cc=fujita.tomonori@gmail.com \
    --cc=georgeandrout13@gmail.com \
    --cc=jstultz@google.com \
    --cc=lyude@redhat.com \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=sboyd@kernel.org \
    --cc=stable@vger.kernel.org \
    --cc=tglx@kernel.org \
    --cc=tomo@flapping.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox