Repository navigation
rust: time: keep Instant invariant when adding/subtracting Delta - #1273
Open
Franklin-Qi wants to merge 14 commits into
Open
Franklin-Qi wants to merge 14 commits into
Franklin-Qi wants to merge 14 commits into
Conversation
Add a type parameter `U` to `Instant`, with `Nsec` as the default, so that an `Instant` in seconds can be added later. The value is stored as `U::Repr`, like `Delta<U>`. `U` is bound by a new trait `InstantUnit` rather than `TimeUnit`. It reads the clock in its unit, and jiffies is not a clock, so `Instant<C, Jiffy>` must not exist. `now()` stays one function on `Instant<C, U>`. With two inherent `now()`, one per unit, the existing `Instant::now()` calls do not compile (E0034, multiple applicable items). The other methods and operators are implemented for `Instant<C, Nsec>` only. `Instant<C>` still means `Instant<C, Nsec>`, so no user changes. No functional change. Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Acked-by: Boqun Feng <boqun@kernel.org> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://msgid.link/20261031003334.4161188-2-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Add `Sec` as a time unit for `Instant`. `Instant<C, Sec>::now()` reads the clock in seconds through a new `ClockId::ktime_get_seconds()`, which wraps `ktime_get_seconds()`, `ktime_get_real_seconds()`, `ktime_get_boottime_seconds()` and `ktime_get_clocktai_seconds()`. `as_secs()` returns the value. `Instant<C, Sec>` has only `now()` and `as_secs()`, and it cannot be compared. There is no `Delta<Sec>`. One can be added when a user needs it. The first user is the drm/vino driver, which passes the wall clock time in seconds to the firmware of a DisplayLink dock. Link: https://lore.kernel.org/rust-for-linux/20260826162851.2497-10-mike@fireburn.co.uk/ Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Acked-by: Boqun Feng <boqun@kernel.org> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://msgid.link/20261031003334.4161188-3-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Commit 6a8e2c6 ("rust: time: rename ClockSource trait to ClockId") renamed the trait because it represents a `clockid_t`, not the C `struct clocksource`. Two doc comments still say "clock source". Replace them with "clock". This matches the `ClockId` doc ("Get the current time from the clock") and the C hrtimer_setup() kerneldoc ("@clock_id: the clock to be used"). No functional change. Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Reviewed-by: Alexandre Courbot <acourbot@nvidia.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://msgid.link/20261030044803.3863267-1-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
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: stable@vger.kernel.org # prerequisite for the Delta division/remainder fix Reviewed-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Assisted-by: LLM Signed-off-by: chenhan <chenhan0017.work@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://msgid.link/20261031103206.24051-2-chenhan0017.work@gmail.com Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
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. The safety comment on the calls to `div64_s64` and `div_s64_rem` are not sufficient, as these functions require a nonzero divisor. Update the safety comments to indicate the caller satisfies the requirement Fixes: 4521438 ("rust: time: Implement basic arithmetic operations for Delta") Reported-by: Georgios Androutsopoulos <georgeandrout13@gmail.com> Closes: Rust-for-Linux#1254 Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: chenhan <chenhan0017.work@gmail.com> Reviewed-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Link: https://msgid.link/20261031103206.24051-3-chenhan0017.work@gmail.com [ Andreas: update commit message to mention safety comment rewrite. ] Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
A hrtimer can be started while its callback runs. hrtimer_forward() writes the expiry without the base lock, so the caller has to serialize it against a concurrent hrtimer_start(). Otherwise the write can change the sort key of a queued timer. Add a variant which does the check and the update with the base lock held. If the timer is already queued, the expiry is left alone and the expiry set by hrtimer_start() wins. The first user is the Rust hrtimer abstraction. Safe Rust code can start a timer while its callback runs, so forward() in the callback can only be a safe API if the core handles a concurrent start. Suggested-by: Thomas Gleixner <tglx@kernel.org> Link: https://lore.kernel.org/all/877bk3ixp5.ffs@fw13/ Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Reviewed-by: Thomas Gleixner <tglx@kernel.org> Link: https://msgid.link/20261101232829.593680-2-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Safe Rust code can start a timer while its callback runs. A timer started through Arc<T> or Pin<&T> can be started again from another clone or copy of the pointer. HrTimerCallbackContext::forward() calls hrtimer_forward(), which writes the expiry without the base lock, so the write can race with the concurrent hrtimer_start(). Call hrtimer_forward_safe_from_callback() instead. It does the update with the base lock held. If the timer is already queued by a concurrent start, the expiry is left alone and 0 is returned. HrTimer::forward() keeps calling hrtimer_forward(). It takes Pin<&mut Self>, so no other reference to the timer exists and no concurrent start is possible. Narrow the safety requirement of raw_forward() to exclusive access, since the callback context no longer uses it. Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://msgid.link/20261101232829.593680-3-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
HrTimer::expires() reads node.expires without the base lock. The hrtimer core writes node.expires in hrtimer_start() and hrtimer_forward(). A timer started through Arc<T> or Pin<&T> can be started or forwarded while expires() runs. The read then races with the write. That is a data race, which is undefined behavior in Rust. The volatile read does not help. Even if the read were done under the base lock, the value would be a snapshot. Another CPU can start the timer right after the read and change the expiry. A driver that needs to know the expiry should start the timer in absolute mode. Then the driver already knows the expiry. A callback that forwards the timer gets the overrun count from forward(). If a driver still needs the remaining time, a binding for hrtimer_get_remaining(), which takes the base lock, should be used instead. HrTimer::expires() has no users. It is safe to remove it. Remove Instant::from_ktime() too. HrTimer::expires() was its only user. Fixes: 4b01474 ("rust: hrtimer: Add HrTimer::expires()") Reported-by: Boqun Feng <boqun@kernel.org> Closes: https://lore.kernel.org/rust-for-linux/aV5IwaxcIF4XJvg3@tardis-2.local/ Cc: Lyude Paul <lyude@redhat.com> Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Link: https://msgid.link/20261102000102.603124-1-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Add examples to the following Delta methods: from_micros(), from_millis(), from_secs(), as_micros_ceil(), as_millis(), as_millis_ceil() and rem_nanos(). The examples show positive and negative values, and how the methods saturate or round. Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Link: https://msgid.link/20261118035723.2380960-2-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Add KUnit tests for the boundary values of from_micros(), from_millis(), from_secs(), as_micros_ceil() and as_millis_ceil(). The boundary values are defined as constants in the test module, so they are not part of the API. Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Link: https://msgid.link/20261118035723.2380960-3-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Delta's div() and rem_nanos() panic if the divisor is zero, or if i64::MIN is divided by -1. In these cases the caller passed a wrong value, but the panic message shows a line in time.rs. Add #[track_caller] so that the panic message shows the caller's location instead. Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://msgid.link/20261118230708.2599659-1-tomo@flapping.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Add an `active()` method to HrTimer that returns true if the timer is in the started or running states. This wraps the kernel's hrtimer_active() function. Unlike a direct read of `node.expires`, this does not race with a concurrent start operation. hrtimer_active() reads the timer state inside a seqcount retry loop and re-reads `timer->base` with READ_ONCE(), and the core documents that it must not return a false negative. No exclusive access to the timer is therefore required, and the SAFETY comment reflects that. The returned value is still only a snapshot: a concurrent event can change the state right after the call. Callers that need a stable answer have to serialize against such events themselves, exactly as C callers of hrtimer_active() do. This is documented on the method. Also add documentation clarifying the definition of an active timer. Introduce the term `active` as a set of timer states composed of `started` and `running`. Reviewed-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Link: https://msgid.link/20261125-hrtimer-active-v4-1-415a37b74d67@kernel.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Franklin-Qi
force-pushed
the
fix/instant-delta-invariant
branch
from
December 2, 2026 08:16
64858e0 to
60c6b49
Compare
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: 22b65a4 ("rust: time: Implement Add<Delta>/Sub<Delta> for Instant") Cc: stable@vger.kernel.org Reported-by: Georgios Androutsopoulos <georgeandrout13@gmail.com> Closes: Rust-for-Linux#1272 Signed-off-by: Franklin-Qi <yusq77@gmail.com>
Add KUnit coverage for Instant + Delta and Instant - Delta after the invariant-preserving arithmetic change. Test an in-range add/sub path, and the clamping paths used when CONFIG_RUST_OVERFLOW_CHECKS is disabled: a result below 0 clamps to 0, and a result above KTIME_MAX (i64::MAX) saturates at KTIME_MAX. The out-of-range panic paths under overflow checks are left for later should_panic support. Suggested-by: Andreas Hindborg <a.hindborg@kernel.org> Suggested-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Franklin-Qi <yusq77@gmail.com>
Franklin-Qi
force-pushed
the
fix/instant-delta-invariant
branch
from
December 3, 2026 09:23
60c6b49 to
e698e6a
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Instant documents inner in 0..=KTIME_MAX, but Add/Sub only asserted non-negativity under CONFIG_RUST_OVERFLOW_CHECKS. With checks disabled, a negative result can be returned and later Instant-Instant subtraction may no longer be overflow-safe.
Always assert the result is non-negative, and document the panic in the operators' rustdoc.
Fixes: 22b65a4 ("rust: time: Implement Add/Sub for Instant")
Cc: stable@vger.kernel.org
Reported-by: Georgios Androutsopoulos georgeandrout13@gmail.com
Closes: #1272
URL: https://lore.kernel.org/rust-for-linux/179610727734.137620.3884652165779521586@gmail.com/