All of lore.kernel.org
 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>,
	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 v2] rust: time: keep Instant invariant when adding/subtracting Delta
Date: Wed,  2 Dec 2026 16:02:27 +0800	[thread overview]
Message-ID: <20261202080227.898512-1-yusq77@gmail.com> (raw)

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, saturate the
arithmetic and clamp a negative result to 0, printing a warning once, 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 v2:
- Follow Andreas' and Miguel's review: panic only with CONFIG_RUST_OVERFLOW_CHECKS (as before);
  without it, saturate the arithmetic, clamp a negative result to 0 and pr_warn_once() instead of
  crashing the kernel.
- Without overflow checks, an addition past KTIME_MAX now saturates to KTIME_MAX instead of
  wrapping to a negative value (which would otherwise have been clamped to 0).
- Update the rustdoc `# Panics` sections and the commit message to match.
- Tested in QEMU with a small test module (x86_64, KASAN): with CONFIG_RUST_OVERFLOW_CHECKS=n,
  the out-of-range cases are clamped/saturated and in-range arithmetic is unchanged; with
  CONFIG_RUST_OVERFLOW_CHECKS=y, the out-of-range cases panic as before. Without this patch and
  with checks disabled, the same cases produce an out-of-range Instant.

v1: https://lore.kernel.org/rust-for-linux/179610727734.137620.3884652165779521586@gmail.com/

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

diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index b6a2aab12a50..c344bfbaecdf 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -241,6 +241,39 @@ pub(crate) unsafe fn from_ktime(ktime: bindings::ktime_t) -> Self {
             _c: PhantomData,
         }
     }
+
+    /// Create an [`Instant`] from the result of an arithmetic operation.
+    ///
+    /// `res` must already have been computed without wrapping, i.e. an overflow above
+    /// `KTIME_MAX` must have panicked or saturated to `KTIME_MAX`.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and `res` is negative.
+    ///
+    /// Otherwise, a negative `res` is clamped to 0 and a warning is printed once.
+    #[inline]
+    fn from_arithmetic(res: bindings::ktime_t) -> Self {
+        // INVARIANT: With overflow checks enabled, we verify here that the value is >= 0.
+        #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
+        assert!(res >= 0);
+
+        // INVARIANT: Without overflow checks, a negative value is clamped to 0.
+        #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))]
+        let res = if res < 0 {
+            crate::pr_warn_once!("Instant arithmetic produced a negative value, clamping to 0\n");
+            0
+        } else {
+            res
+        };
+
+        // INVARIANT: By the above, `res` is in the range from 0 to `KTIME_MAX`: the upper bound
+        // holds since `res` is an `i64` that did not wrap.
+        Self {
+            inner: res,
+            _c: PhantomData,
+        }
+    }
 }
 
 impl<C: ClockId> ops::Sub for Instant<C> {
@@ -258,40 +291,44 @@ fn sub(self, other: Instant<C>) -> Delta {
 impl<T: ClockId> ops::Add<Delta> for Instant<T> {
     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
+        // With overflow checks enabled, this panics if we overflow (e.g. go above `KTIME_MAX`).
         #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
-        assert!(res >= 0);
+        let res = self.inner + rhs.value;
+        #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))]
+        let res = self.inner.saturating_add(rhs.value);
 
-        Self {
-            inner: res,
-            _c: PhantomData,
-        }
+        Self::from_arithmetic(res)
     }
 }
 
 impl<T: ClockId> ops::Sub<Delta> for Instant<T> {
     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
+        // With overflow checks enabled, this panics if we overflow (e.g. go above `KTIME_MAX`).
         #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
-        assert!(res >= 0);
+        let res = self.inner - rhs.value;
+        #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))]
+        let res = self.inner.saturating_sub(rhs.value);
 
-        Self {
-            inner: res,
-            _c: PhantomData,
-        }
+        Self::from_arithmetic(res)
     }
 }
 

base-commit: 82d8023ec40420ed61d7a96a173ef862741f1753
-- 
2.55.0


             reply	other threads:[~2026-12-02  8:03 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02  8:02 Franklin-Qi [this message]
2026-12-02 11:27 ` [PATCH v2] rust: time: keep Instant invariant when adding/subtracting Delta 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   ` [PATCH v3 1/2] " Franklin-Qi
2026-12-03  9:21   ` [PATCH v3 2/2] rust: time: add KUnit tests for Instant Delta clamping Franklin-Qi
2026-12-03 12:34     ` Miguel Ojeda

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=20261202080227.898512-1-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 \
    /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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.