Skip to contentSkip to conversation

rust: core abstractions for a USB display driver

PATCH Superseded Mike Lothian 5 participants 24 messages Aug 26 – Oct 31 2 messages not in the archive

Subsystems (5)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover rust: core abstractions for a USB display driver

Core Rust abstractions a USB display driver needs. They are separated from the driver because none of them are display specific: each one covers a kernel facility that has C callers today and no Rust binding

sync: single-shot and timed completions
hrtimer: restart an ArcHrTimerHandle, and read the interrupt state inside a
hard callback
random, xxhash, time: safe wrappers over get_random_bytes(), xxh64() and
ktime_get_real_seconds()
workqueue: make OwnedQueue thread safe
io: offset copy helpers that check the bounds they are given
error: expose EPROTO

None of these nine has been posted before, so this goes out unversioned even though the drivers it feeds are on their third round. A runtime platform-device creator and a root-device attribute group went out inside the rust: drm v2 series, where they did not belong, and they are not here either, because the consumer that needed them is not part of this posting

It is small on purpose. Every patch has a caller in the driver at the end of the chain, and nothing is here on the argument that it might be useful to somebody later

The rest of the posting, which is one series per subsystem:

rust-core, 9 patches, this one
rust-crypto, 2 patches, to linux-crypto and rust-for-linux, not sent yet rust-usb, 5 patches, to linux-usb and rust-for-linux, not sent yet rust-drm, 23 patches, to dri-devel and rust-for-linux, not sent yet rust-firmware, 1 patch, to linux-kernel and rust-for-linux, not sent yet drm-vino, 13 patches, to dri-devel, not sent yet

Vino is the user for all of them. The abstractions themselves are generic and carry no knowledge of DisplayLink

The whole thing is one branch, base and prerequisites included, which is the quickest way to read it:

  git clone -b vino-v3 https://github.com/FireBurn/linux
  cd linux
  make LLVM=1 rustavailable
  make LLVM=1 -j$(nproc)
  make LLVM=1 -j$(nproc) modules

CONFIG_RUST=y and CONFIG_DRM_VINO=m are the two to set; DRM_VINO selects the rest of what it needs

It is the exact tree these patches were generated from, at 4c9ba407018e, the drm-rust-next tip of 2026-08-06. drm-next has moved on since, and this follows drm-rust-next deliberately: the KMS layer underneath this work lives only there, and that tree picks up drm-next on its own schedule

Two commits on the branch are not in any of the series above, because they enable no part of Vino: a scheduler call site that stops compiling under the locking-guard series, and the Kms associated type Tyr needs once the KMS registration trait requires one

It applies to the base above plus this, and nothing else:

Alice Ryhl, Creation of workqueues in Rust, plus Onur Ozkan's cancel_sync
https://lore.kernel.org/r/[email protected]

The reference branch also carries Boqun Feng's counted interrupt disabling series, which SpinLockIrq needs. One patch of it is already in tip locking/core as e901c1510e24

Danilo Krummrich's OwnedQueue, ScopedQueue and ScopedWork series supersedes part of the workqueue work carried here, and is the better answer: Vino calls Work::cancel_sync() in seven places to make teardown wait for its own work items, and ScopedWork cancels on drop, which is that idiom done properly

https://lore.kernel.org/r/[email protected]

It was still moving when this was cut, so this uses what is available today. When it lands the swap goes in as one commit moving the prerequisites and the call sites together, since either half alone leaves the tree not building

These patches were written with the assistance of Claude (Anthropic), used through Claude Code as an interactive coding assistant, across the design, the implementation and the tests. Every patch it contributed to carries an Assisted-by trailer. The Signed-off-by is mine: I have reviewed and tested what is here and I stand behind it

Mike Lothian (9):
rust: sync: completion: add single-shot and timed operations
rust: hrtimer: add ArcHrTimerHandle::restart
rust: random: add a safe get_random_bytes wrapper
rust: xxhash: add a safe xxh64 wrapper
rust: workqueue: make OwnedQueue thread-safe
rust: io: add checked offset copy helpers
rust: hrtimer: expose interrupt state in hard callbacks
rust: error: expose EPROTO
rust: time: add ktime_get_real_seconds

 11 files changed, 243 insertions(+), 2 deletions(-)

base-commit: 4c9ba407018e8deb06dbc643112bac8f40404f95
prerequisite-message-id: <[email protected]>

#1 lore raw

PATCH 1/9 rust: sync: completion: add single-shot and timed operations

Expose complete() and wait_for_completion_timeout() so Rust drivers can coordinate asynchronous completions without open-coding access to struct completion.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/sync/completion.rs | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)
rust/kernel/sync/completion.rs +24 -1
index 35ff049ff078..df4f6e11ef37 100644
@@ -6,7 +6,12 @@
 //!
 //! C header: [`include/linux/completion.h`](srctree/include/linux/completion.h)
 
-use crate::{bindings, prelude::*, types::Opaque};
+use crate::{
+    bindings,
+    prelude::*,
+    time::Jiffies,
+    types::Opaque, //
+};
 
 /// Synchronization primitive to signal when a certain task has been completed.
 ///
@@ -90,6 +95,15 @@ fn as_raw(&self) -> *mut bindings::completion {
         self.inner.get()
     }
 
+    /// Signal one task waiting for this completion.
+    ///
+    /// If no task is waiting, the signal is retained and consumed by a future waiter.
+    #[inline]
+    pub fn complete(&self) {
+        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        unsafe { bindings::complete(self.as_raw()) };
+    }
+
     /// Signal all tasks waiting on this completion.
     ///
     /// This method wakes up all tasks waiting on this completion; after this operation the
@@ -111,4 +125,13 @@ pub fn wait_for_completion(&self) {
         // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
         unsafe { bindings::wait_for_completion(self.as_raw()) };
     }
+
+    /// Wait at most `timeout` jiffies for one completion signal.
+    ///
+    /// Returns `true` after consuming a signal and `false` when the timeout expires.
+    #[inline]
+    pub fn wait_for_completion_timeout(&self, timeout: Jiffies) -> bool {
+        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        unsafe { bindings::wait_for_completion_timeout(self.as_raw(), timeout) != 0 }
+    }
 }
#2 lore raw

PATCH 2/9 rust: hrtimer: add ArcHrTimerHandle::restart

In reply to Mike Lothian

Restarting an already-started timer through the safe API means dropping its handle and calling HrTimerPointer::start() again. Dropping the handle cancels, and cancelling blocks until a running callback returns, so this is unavailable to any caller that cannot sleep -- a driver re-arming its timer from a callback invoked with interrupts disabled, say. Such drivers fall back to the unsafe HasHrTimer::start() on a raw pointer.

Add restart() on the handle. It re-queues the timer in place without cancelling first. It is safe because the handle already owns the Arc that keeps the timer alive and still cancels it on drop, which is exactly what HasHrTimer::start() requires of its caller.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/time/hrtimer/arc.rs | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
rust/kernel/time/hrtimer/arc.rs +23 -0
index 7be82bcb352a..f7cd46dbd3d3 100644
@@ -39,6 +39,29 @@ fn cancel(&mut self) -> bool {
     }
 }
 
+impl<T> ArcHrTimerHandle<T>
+where
+    T: HasHrTimer<T>,
+{
+    /// Restart the timer with a new expiry time, without cancelling it first.
+    ///
+    /// If the timer is queued it is removed and re-inserted at the new expiry; if it has already
+    /// expired it is queued again. Unlike dropping the handle and calling
+    /// [`HrTimerPointer::start`] again, this never blocks waiting for a running callback, so it
+    /// can be used from contexts that cannot sleep -- re-arming a timer from a driver callback
+    /// invoked with interrupts disabled, for instance.
+    ///
+    /// This handle keeps its timer alive and still cancels it on drop, so the timer cannot outlive
+    /// the restart.
+    pub fn restart(&self, expires: <<T as HasHrTimer<T>>::TimerMode as HrTimerMode>::Expires) {
+        // SAFETY:
+        // - `self.inner` is a live `Arc<T>` held by this handle, so the pointer is valid.
+        // - The caller cannot leak past the timer's death: this handle owns the `Arc` and cancels
+        //   the timer when dropped, which is the requirement `HasHrTimer::start` places on us.
+        unsafe { T::start(Arc::as_ptr(&self.inner), expires) };
+    }
+}
+
 impl<T> Drop for ArcHrTimerHandle<T>
 where
     T: HasHrTimer<T>,
maintainer
#3 lore raw

Re: [PATCH 2/9] rust: hrtimer: add ArcHrTimerHandle::restart

Quoted 8 lines · Mike Lothian

Restarting an already-started timer through the safe API means dropping its handle and calling HrTimerPointer::start() again. Dropping the handle cancels, and cancelling blocks until a running callback returns, so this is unavailable to any caller that cannot sleep -- a driver re-arming its timer from a callback invoked with interrupts disabled, say. Such drivers fall back to the unsafe HasHrTimer::start() on a raw pointer.

Quoted 4 lines

Add restart() on the handle. It re-queues the timer in place without cancelling first. It is safe because the handle already owns the Arc that keeps the timer alive and still cancels it on drop, which is exactly what HasHrTimer::start() requires of its caller.

The intention is that handlers use the forward method on the context object in combination with return value HrTimerRestart::Restart to re arm the timer.

However, we found a data race in the face of concurrent start operations, so we are solving that over at [1].

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/rust-for-linux/[email protected]/T/#t

A message that is not in the archive (sent off-list or not yet received): 3-IkUMhanJhClxwXLNvuF1-ncsHt6uM6GRmW78t81tKgo_5IO80fRJ9HZROE5RwlmxZhufdPXswcExj5j65ejw==@protonmail.internalid

A message that is not in the archive (sent off-list or not yet received): CAHbf0-F-KNQu5NrFcUw1JOwaVQJq5hS+d9OHTmV3J2Pi+hfOqA@mail.gmail.com

maintainer
#6 lore raw

Re: [PATCH 2/9] rust: hrtimer: add ArcHrTimerHandle::restart

"Mike Lothian" <[email protected]> writes:

Hi Mike,

Please note that HTML messages are rejected by lore.

Quoted 11 lines · Andreas Hindborg
Quoted 6 lines

The intention is that handlers use the forward method on the context object in combination with return value HrTimerRestart::Restart to re arm the timer.

However, we found a data race in the face of concurrent start operations, so we are solving that over at [1].

You are right, and checking properly, the driver that motivated this does not need it: its callback already ends with

Quoted 8 lines

ctx.forward_now(Delta::from_nanos(interval));
HrTimerRestart::Restart

and nothing anywhere calls the handle's restart(). I will drop this patch rather than carry an API with no user, and rebase the rest on your expires-v2 series.

Thanks for the pointer.

You are welcome :)

Best regards,
Andreas Hindborg

#7 lore raw

Re: [PATCH 2/9] rust: hrtimer: add ArcHrTimerHandle::restart

Sorry, I take that back - it does have a caller, I grepped for ".restart()", vino calls it in enable_vblank:

    h.restart(Delta::from_nanos(interval));

I'd like to keep it for v4 or does expires-v2 change it? If the concurrent-start race is fixed there I'd rather rebase onto that than carry something that races

Mike

#8 lore raw

PATCH 3/9 rust: random: add a safe get_random_bytes wrapper

In reply to Mike Lothian

Expose a slice-based wrapper around get_random_bytes() so Rust callers can fill key, nonce, and other random buffers without touching raw pointers.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/lib.rs    |  1 +
 rust/kernel/random.rs | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 35 insertions(+)
 create mode 100644 rust/kernel/random.rs
rust/kernel/lib.rs +1 -0
index 08e5730753eb..f39648246271 100644
@@ -116,6 +116,7 @@
 pub mod ptr;
 #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)]
 pub mod pwm;
+pub mod random;
 pub mod rbtree;
 pub mod regulator;
 pub mod revocable;
rust/kernel/random.rs new file +34 -0
new file mode 100644
index 000000000000..5f2288969dbf
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Random number generation.
+//!
+//! C header: [`include/linux/random.h`](srctree/include/linux/random.h)
+
+use crate::bindings;
+
+/// Fills `buf` with cryptographically secure random bytes from the kernel's CSPRNG.
+///
+/// This is the in-kernel equivalent of reading from `/dev/urandom`, and is suitable for generating
+/// keys, nonces and other secrets. It never blocks: once the CSPRNG has been seeded during boot it
+/// stays seeded, and callers running that early should use
+/// [`wait_for_random_bytes()`] instead of assuming otherwise.
+///
+/// [`wait_for_random_bytes()`]: srctree/include/linux/random.h
+///
+/// # Examples
+///
+/// ```
+/// use kernel::random;
+///
+/// let mut key = [0u8; 16];
+/// random::fill_bytes(&mut key);
+///
+/// // A zero-length request is valid and does nothing.
+/// random::fill_bytes(&mut []);
+/// ```
+#[inline]
+pub fn fill_bytes(buf: &mut [u8]) {
+    // SAFETY: `buf` is a valid slice, so its pointer is valid for writes of `buf.len()` bytes, and
+    // `get_random_bytes()` writes exactly that many.
+    unsafe { bindings::get_random_bytes(buf.as_mut_ptr().cast(), buf.len()) };
+}
#9 lore raw

PATCH 4/9 rust: xxhash: add a safe xxh64 wrapper

In reply to Mike Lothian

Expose xxh64() through a slice-based Rust API for non-cryptographic hashing such as framebuffer damage detection.

Assisted-by Claude:claude-opus-5
---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/lib.rs              |  1 +
 rust/kernel/xxhash.rs           | 68 +++++++++++++++++++++++++++++++++
 3 files changed, 70 insertions(+)
 create mode 100644 rust/kernel/xxhash.rs
rust/bindings/bindings_helper.h +1 -0
index 1124785e210b..2d079f278a04 100644
@@ -93,6 +93,7 @@
 #include <linux/wait.h>
 #include <linux/workqueue.h>
 #include <linux/xarray.h>
+#include <linux/xxhash.h>
 #include <trace/events/rust_sample.h>
 
 /*
rust/kernel/lib.rs +1 -0
index f39648246271..d7ced2a4c11f 100644
@@ -141,6 +141,7 @@
 pub mod usb;
 pub mod workqueue;
 pub mod xarray;
+pub mod xxhash;
 
 #[doc(hidden)]
 pub use bindings;
rust/kernel/xxhash.rs new file +68 -0

68 lines not on this page · raw message

#10 lore raw

PATCH 5/9 rust: workqueue: make OwnedQueue thread-safe

In reply to Mike Lothian

OwnedQueue only owns a pointer to Queue, whose operations are already Send and Sync. Propagate those guarantees so drivers can keep an owned queue in shared device state.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/workqueue/mod.rs | 6 ++++++
 1 file changed, 6 insertions(+)
rust/kernel/workqueue/mod.rs +6 -0
index e30c21214a81..000a29c9dc1a 100644
@@ -380,6 +380,12 @@ pub struct OwnedQueue {
     queue: NonNull<Queue>,
 }
 
+// SAFETY: `Queue` operations are thread-safe and ownership may be transferred
+// between threads.
+unsafe impl Send for OwnedQueue {}
+// SAFETY: Shared access only exposes the thread-safe `Queue` API.
+unsafe impl Sync for OwnedQueue {}
+
 impl Deref for OwnedQueue {
     type Target = Queue;
     fn deref(&self) -> &Queue {
#11 lore raw

PATCH 6/9 rust: io: add checked offset copy helpers

In reply to Mike Lothian

I/O mappings often need to copy a bounded byte range rather than the complete mapping. Add checked helpers that project the requested range before using the backend copy operation. This keeps raw backend pointers out of consumers and reports invalid ranges instead.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/io.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 50 insertions(+)
rust/kernel/io.rs +50 -0
index 95f46bb75f9e..aea346b8b79e 100644
@@ -225,6 +225,30 @@ fn io_view<'a, IO: Io<'a>, U>(
     Ok(unsafe { IO::Backend::project_view(view, projected_ptr) })
 }
 
+/// Returns a byte-slice view for a given range, performing runtime bounds checks.
+#[inline]
+fn io_byte_slice<'a, IO>(
+    this: IO,
+    offset: usize,
+    len: usize,
+) -> Result<<IO::Backend as IoBackend>::View<'a, [u8]>>
+where
+    IO: Io<'a, Target = [u8]>,
+{
+    let view = this.as_view();
+    let ptr = IO::Backend::as_ptr(view);
+    let end = offset.checked_add(len).ok_or(EINVAL)?;
+
+    if end > ptr.len() {
+        return Err(EINVAL);
+    }
+
+    let projected_ptr =
+        core::ptr::slice_from_raw_parts_mut(ptr.cast::<u8>().wrapping_add(offset), len);
+    // SAFETY: The bounds check above proves that `projected_ptr` is a sub-slice of `ptr`.
+    Ok(unsafe { IO::Backend::project_view(view, projected_ptr) })
+}
+
 /// I/O backends.
 ///
 /// This is an abstract representation to be implemented by arbitrary I/O
@@ -640,6 +664,32 @@ fn copy_to_slice(self, data: &mut [u8])
         }
     }
 
+    /// Copy bytes from `data` to a range of I/O memory.
+    ///
+    /// Returns [`EINVAL`] if `offset..offset + data.len()` is outside the I/O region.
+    #[inline]
+    fn try_copy_from_slice(self, offset: usize, data: &[u8]) -> Result
+    where
+        Self::Backend: IoCopyable,
+        Self: Io<'a, Target = [u8]>,
+    {
+        io_byte_slice(self, offset, data.len())?.copy_from_slice(data);
+        Ok(())
+    }
+
+    /// Copy a range of I/O memory to `data`.
+    ///
+    /// Returns [`EINVAL`] if `offset..offset + data.len()` is outside the I/O region.
+    #[inline]
+    fn try_copy_to_slice(self, offset: usize, data: &mut [u8]) -> Result
+    where
+        Self::Backend: IoCopyable,
+        Self: Io<'a, Target = [u8]>,
+    {
+        io_byte_slice(self, offset, data.len())?.copy_to_slice(data);
+        Ok(())
+    }
+
     /// Fallible 8-bit read with runtime bounds check.
     #[inline(always)]
     fn try_read8(self, offset: usize) -> Result<u8>
#12 lore raw

PATCH 7/9 rust: hrtimer: expose interrupt state in hard callbacks

In reply to Mike Lothian

Hard hrtimer modes guarantee that their callbacks run with local interrupts disabled. Carry that guarantee through HrTimerCallbackContext so users of IRQ-aware locks do not need to assert the callback context themselves.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/time/hrtimer.rs | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
rust/kernel/time/hrtimer.rs +20 -1
index 2d7f1131a813..a55b3ce53735 100644
@@ -404,7 +404,7 @@
 //! [`Arc`]: kernel::sync::Arc
 
 use super::{ClockSource, Delta, Instant};
-use crate::{prelude::*, types::Opaque};
+use crate::{interrupt::LocalInterruptDisabled, prelude::*, types::Opaque};
 use core::{marker::PhantomData, ptr::NonNull};
 use pin_init::PinInit;
 
@@ -900,6 +900,11 @@ pub trait HrTimerMode: private::Sealed {
     type Expires: HrTimerExpires;
 }
 
+/// A timer mode whose callback runs with local interrupts disabled.
+///
+/// This trait is sealed by [`HrTimerMode`].
+pub trait HardHrTimerMode: HrTimerMode {}
+
 /// Timer that expires at a fixed point in time.
 pub struct AbsoluteMode<C: ClockSource>(PhantomData<C>);
 
@@ -982,6 +987,7 @@ impl<C: ClockSource> HrTimerMode for AbsoluteHardMode<C> {
     type Clock = C;
     type Expires = Instant<C>;
 }
+impl<C: ClockSource> HardHrTimerMode for AbsoluteHardMode<C> {}
 
 /// Timer with relative expiration, handled in hard irq context.
 pub struct RelativeHardMode<C: ClockSource>(PhantomData<C>);
@@ -991,6 +997,7 @@ impl<C: ClockSource> HrTimerMode for RelativeHardMode<C> {
     type Clock = C;
     type Expires = Delta;
 }
+impl<C: ClockSource> HardHrTimerMode for RelativeHardMode<C> {}
 
 /// Timer with absolute expiration, pinned to CPU and handled in hard irq context.
 pub struct AbsolutePinnedHardMode<C: ClockSource>(PhantomData<C>);
@@ -1000,6 +1007,7 @@ impl<C: ClockSource> HrTimerMode for AbsolutePinnedHardMode<C> {
     type Clock = C;
     type Expires = Instant<C>;
 }
+impl<C: ClockSource> HardHrTimerMode for AbsolutePinnedHardMode<C> {}
 
 /// Timer with relative expiration, pinned to CPU and handled in hard irq context.
 pub struct RelativePinnedHardMode<C: ClockSource>(PhantomData<C>);
@@ -1009,6 +1017,7 @@ impl<C: ClockSource> HrTimerMode for RelativePinnedHardMode<C> {
     type Clock = C;
     type Expires = Delta;
 }
+impl<C: ClockSource> HardHrTimerMode for RelativePinnedHardMode<C> {}
 
 /// Privileged smart-pointer for a [`HrTimer`] callback context.
 ///
@@ -1065,6 +1074,16 @@ pub fn forward(&mut self, now: HrTimerInstant<T>, interval: Delta) -> u64 {
     pub fn forward_now(&mut self, duration: Delta) -> u64 {
         self.forward(HrTimerInstant::<T>::now(), duration)
     }
+
+    /// Returns proof that local interrupts are disabled for a hard timer callback.
+    pub fn local_interrupt_disabled(&self) -> &LocalInterruptDisabled
+    where
+        T::TimerMode: HardHrTimerMode,
+    {
+        // SAFETY: `Self` can only be constructed while running this timer's callback, and the
+        // `HardHrTimerMode` bound guarantees that the callback runs in hard interrupt context.
+        unsafe { LocalInterruptDisabled::assume_disabled() }
+    }
 }
 
 /// Use to implement the [`HasHrTimer<T>`] trait.
maintainer
#13 lore raw

Re: [PATCH 7/9] rust: hrtimer: expose interrupt state in hard callbacks

Quoted 4 lines · Mike Lothian

Hard hrtimer modes guarantee that their callbacks run with local interrupts disabled. Carry that guarantee through HrTimerCallbackContext so users of IRQ-aware locks do not need to assert the callback context themselves.

This looks good to me. We were pondering on removing the context type though [1]. We might have to keep it around for this to work.

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

#14 lore raw

PATCH 8/9 rust: error: expose EPROTO

In reply to Mike Lothian

Add the named protocol-error constant so Rust protocol drivers can return the same specific errno as their C counterparts without constructing it from a raw integer.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/error.rs | 1 +
 1 file changed, 1 insertion(+)
rust/kernel/error.rs +1 -0
index a56ba6309594..9492471c2677 100644
@@ -64,6 +64,7 @@ macro_rules! declare_err {
     declare_err!(EPIPE, "Broken pipe.");
     declare_err!(EDOM, "Math argument out of domain of func.");
     declare_err!(ERANGE, "Math result not representable.");
+    declare_err!(EPROTO, "Protocol error.");
     declare_err!(EOVERFLOW, "Value too large for defined data type.");
     declare_err!(EMSGSIZE, "Message too long.");
     declare_err!(ETIMEDOUT, "Connection timed out.");
#15 lore raw

Re: [PATCH 8/9] rust: error: expose EPROTO

Quoted 7 lines · Mike Lothian

Add the named protocol-error constant so Rust protocol drivers can return the same specific errno as their C counterparts without constructing it from a raw integer.

Assisted-by Claude:claude-opus-5

This is already in mainline, please see commit b93fb6e76ec1 ("rust:
error: add remaining error codes").

Cheers,
Miguel

#16 lore raw

PATCH 9/9 rust: time: add ktime_get_real_seconds

In reply to Mike Lothian

Reading an Instant<RealTime> is the wrong tool for a caller that only wants a calendar time in seconds: it takes a full nanosecond timestamp and then needs a 64-bit division to get back to what the timekeeping core already maintains as a plain seconds field.

Wrap ktime_get_real_seconds(), which is that field. Document the property that matters at the call site and that the type cannot express: the value follows CLOCK_REALTIME, so it is not monotonic and can move in either direction.

Assisted-by Claude:claude-opus-5
---
 rust/kernel/time.rs | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
rust/kernel/time.rs +14 -0
index 363e93cbb139..a9922f1b493d 100644
@@ -129,6 +129,20 @@ fn ktime_get() -> bindings::ktime_t {
     }
 }
 
+/// Returns the coarse wall-clock time in whole seconds since the Unix epoch.
+///
+/// This is the cheap counterpart to reading an [`Instant<RealTime>`]: it reads the seconds field
+/// the timekeeping core maintains, with no 64-bit division, and is what a caller that only needs a
+/// calendar time should use.
+///
+/// The value follows CLOCK_REALTIME, so it is not monotonic: settimeofday(2), NTP steps and leap
+/// second handling can move it in either direction.
+pub fn ktime_get_real_seconds() -> i64 {
+    // SAFETY: reading the timekeeping core's seconds field has no preconditions and is safe from
+    // any context.
+    unsafe { bindings::ktime_get_real_seconds() }
+}
+
 /// A monotonic that ticks while system is suspended.
 ///
 /// A nonsettable system-wide clock that is identical to CLOCK_MONOTONIC,
maintainer
#17 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 9 lines · Mike Lothian

Reading an Instant<RealTime> is the wrong tool for a caller that only wants a calendar time in seconds: it takes a full nanosecond timestamp and then needs a 64-bit division to get back to what the timekeeping core already maintains as a plain seconds field.

Wrap ktime_get_real_seconds(), which is that field. Document the property that matters at the call site and that the type cannot express: the value follows CLOCK_REALTIME, so it is not monotonic and can move in either direction.

We recently added the concept of TimeUnit. For now it is exposed via Delta<U: TimeUnit>. We could extend this to Instant as well to have a seconds based Instant.

Best regards,
Andreas Hindborg

#18 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 7 lines · On Thu, 27 Aug 2026 15:39:53 +0200 Andreas Hindborg <[email protected]>…
Quoted 5 lines · Mike Lothian

Reading an Instant<RealTime> is the wrong tool for a caller that only wants a calendar time in seconds: it takes a full nanosecond timestamp and then needs a 64-bit division to get back to what the timekeeping core already maintains as a plain seconds field.

Quoted 8 lines
Quoted 4 lines

Wrap ktime_get_real_seconds(), which is that field. Document the property that matters at the call site and that the type cannot express: the value follows CLOCK_REALTIME, so it is not monotonic and can move in either direction.

We recently added the concept of TimeUnit. For now it is exposed via Delta<U: TimeUnit>. We could extend this to Instant as well to have a seconds based Instant.

I don't think that is a good idea.

Instant is a point in time that exists to produce a Delta: now() is its only constructor, and what you do with it is elapsed() or Instant - Instant. So a seconds based Instant has to define what Instant - Instant returns, and Delta<Sec> would have no consumer. Every interface that takes a span takes a Delta<Nsec>: fsleep(), udelay(), HrTimer::forward(), read_poll_timeout(). Delta also already treats seconds as an input format rather than a unit, since Delta::from_secs() returns a Delta<Nsec>. That is the difference from Delta<Jiffy>, which earned a type because the C side takes jiffies at the boundary and the conversion is lossy; time64_t is an i64 and seconds to nanoseconds is exact.

And that is not how ktime_get_real_seconds() is used in the first place. Its callers need a calendar value in seconds because something outside the kernel fixes the format: an on-disk field, a value passed to firmware, or a userspace ABI field. Many of them compare it against an expiry time that came from the wire or from disk.

Does that make sense?

maintainer
#19 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 15 lines · FUJITA Tomonori
Quoted 12 lines · On Thu, 27 Aug 2026 15:39:53 +0200 Andreas Hindborg <[email protected]>…
Quoted 9 lines · Mike Lothian

Reading an Instant<RealTime> is the wrong tool for a caller that only wants a calendar time in seconds: it takes a full nanosecond timestamp and then needs a 64-bit division to get back to what the timekeeping core already maintains as a plain seconds field.

Wrap ktime_get_real_seconds(), which is that field. Document the property that matters at the call site and that the type cannot express: the value follows CLOCK_REALTIME, so it is not monotonic and can move in either direction.

Quoted 8 lines
Quoted 3 lines

We recently added the concept of TimeUnit. For now it is exposed via Delta<U: TimeUnit>. We could extend this to Instant as well to have a seconds based Instant.

I don't think that is a good idea.

Instant is a point in time that exists to produce a Delta: now() is its only constructor,

Instant is a point in time. ktime_get_real_seconds return a point in time. Whether the constructor is Delta::now or should be Instant::now could be discussed.

Quoted 1 line

and what you do with it is elapsed()

I don't see the issue with Instant<RealSeconds>::elapsed(). You would get a duration of seconds that has elapsed since the instant? Of course you get all the inaccuracy that comes with using seconds resolution.

Quoted 2 lines

or `Instant -
Instant`.

Same.

Quoted 2 lines

So a seconds based Instant has to define what Instant - Instant returns,

A Delta<Seconds> would be the obvious choice? I perfer Seconds and NanoSeconds, but the abbreviated pattern is already prevalent, so probably best to go with that.

Quoted 1 line

and Delta<Sec> would have no consumer.

True, but OK I guess.

Quoted 3 lines

Every interface that takes a
span takes a Delta<Nsec>: fsleep(), udelay(), HrTimer::forward(), read_poll_timeout().

That is fine. Those APIs do not have to take Delta<Seconds>, they can keep taking Delta<Nsec>

Quoted 3 lines

Delta also already treats seconds as an input format rather than a unit, since Delta::from_secs() returns a Delta<Nsec>.

That is fine. In the context of Delta::from_secs the argument is a duration. Instant<Seconds> is a logically different concept. It is a point in time, not a duration.

Quoted 4 lines

That is
the difference from Delta<Jiffy>, which earned a type because the C side takes jiffies at the boundary and the conversion is lossy; time64_t is an i64 and seconds to nanoseconds is exact.

Yes, we made Delta<Jiffy> from a need to pass a jiffy based duration to C code. That should not prevent us from having a seconds based Instant.

If you are concerned about the dead code in a seconds based Delta, we can gate the impls.

Quoted 5 lines

And that is not how ktime_get_real_seconds() is used in the first place. Its callers need a calendar value in seconds because something outside the kernel fixes the format: an on-disk field, a value passed to firmware, or a userspace ABI field. Many of them compare it against an expiry time that came from the wire or from disk.

Again, sure, that is why we originally introduced these types. But I don't think we should gate our time representing types on the rationale of the first use case. We should represent points in time and duration of time with a single set of types.

Quoted 1 line

Does that make sense?

I think I understand your concern, but I do not share it.

I would appreciate others to chime in on this - in either direction. How should we represent time in general.

Best regards,
Andreas Hindborg

#20 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 2 lines · Andreas Hindborg

We should represent points in time and duration of time with a single set of types.

Quoted 4 lines · FUJITA Tomonori

I could not find a user of this in the posted series, including the drm/vino v3 one, which looks like it uses Instant<Monotonic> everywhere. Where can I see the code that calls this, and what does it do with the value?

Sorry, the user wasn't in anything I'd posted when you asked. It's in the drm/vino series that sits on top of this one, 7/14 in the new posting, which I haven't sent yet

The dock has a real-time clock and the DisplayLink driver sets it during session bring-up. The message carries the calendar date and time in broken-down form, so the code takes the seconds, adds a UTC offset that comes from a module parameter, and works out year, month, day, hour, minute, second, weekday and day of year. That's the only use, it's read once per bring-up and nothing is compared against it

So it's the case you described, Tomonori: the format is fixed outside the kernel, by the dock's firmware, and what the caller wants is an i64 of seconds since the epoch. It never gets subtracted from anything, so a seconds based Instant would only be there to be converted straight back

I don't have a strong view on Instant<Seconds> versus the plain function. If you two settle on the Instant, I'll respin on it, but I'd rather not block the rest of rust-core on that, and the function is small enough to change when the types land

Mike

#21 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 4 lines · On Fri, 30 Oct 2026 07:57:50 +0000 Mike Lothian <[email protected]> wrote:

So it's the case you described, Tomonori: the format is fixed outside the kernel, by the dock's firmware, and what the caller wants is an i64 of seconds since the epoch. It never gets subtracted from anything, so a seconds based Instant would only be there to be converted straight back

Right, you only need an i64 of seconds since the epoch and do no arithmetic or comparison on it. A type is useful when it guards those operations, and there are none here. So the plain function is fine with me. If a caller that needs them shows up later, we can add a type then.

maintainer
#22 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 7 lines · FUJITA Tomonori
Quoted 4 lines · On Fri, 30 Oct 2026 07:57:50 +0000 Mike Lothian <[email protected]> wrote:

So it's the case you described, Tomonori: the format is fixed outside the kernel, by the dock's firmware, and what the caller wants is an i64 of seconds since the epoch. It never gets subtracted from anything, so a seconds based Instant would only be there to be converted straight back

Even that, I think Instant<Sec> would still be more clear than returning an i64. Also regarding Tomo's concern:

| So a seconds based Instant has to define what Instant - Instant | returns, and Delta<Sec> would have no consumer.

We can probably only impl ops::Sub for Instant<C, NSec>, then we don't have to deal with Delta<Sec> until there is a user. (We probably want to avoid a from_ktime() for Instant<Sec> as well, so separate impl blocks make sense).

Quoted 4 lines

Right, you only need an i64 of seconds since the epoch and do no arithmetic or comparison on it. A type is useful when it guards those operations, and there are none here. So the plain function is fine

The way I see it is from kernel::time perspective, we still want to make sure the APIs are still in the same abstraction layer, a ktime_get_real_seconds() co-exists with Instant::now() as the public interface layer breaks that in my opinion. And the generic type parameter should be flexible enough to avoid introduce anything we don't have a user yet.

Thoughts?

Regards,
Boqun

Quoted 2 lines

with me. If a caller that needs them shows up later, we can add a type then.

#23 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

Quoted 6 lines · On Fri, 30 Oct 2026 11:59:24 -0700 Boqun Feng <[email protected]> wrote:

The way I see it is from kernel::time perspective, we still want to make sure the APIs are still in the same abstraction layer, a ktime_get_real_seconds() co-exists with Instant::now() as the public interface layer breaks that in my opinion. And the generic type parameter should be flexible enough to avoid introduce anything we don't have a user yet.

OK. I sent a series that adds a unit parameter to Instant and a seconds based Instant on top of it, with Sub and the other arithmetic on Instant<C, Nsec> only:

https://lore.kernel.org/rust-for-linux/[email protected]/

What it costs is a new trait InstantUnit with a read function, a second method on ClockId, and per-unit invariants on Instant. Please take a look and tell me if this is fine.

#24 lore raw

Re: [PATCH 9/9] rust: time: add ktime_get_real_seconds

In reply to Mike Lothian
Quoted 10 lines · On Wed, 26 Aug 2026 17:28:43 +0100 Mike Lothian <[email protected]> wrote:

Reading an Instant<RealTime> is the wrong tool for a caller that only wants a calendar time in seconds: it takes a full nanosecond timestamp and then needs a 64-bit division to get back to what the timekeeping core already maintains as a plain seconds field.

Wrap ktime_get_real_seconds(), which is that field. Document the property that matters at the call site and that the type cannot express: the value follows CLOCK_REALTIME, so it is not monotonic and can move in either direction.

Quoted 5 lines
Assisted-by Claude:claude-opus-5
---
 rust/kernel/time.rs | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

I could not find a user of this in the posted series, including the drm/vino v3 one, which looks like it uses Instant<Monotonic> everywhere. Where can I see the code that calls this, and what does it do with the value? I would like to see the use case before judging what this should return.

#25 lore raw
In reply to Mike Lothian
Quoted 8 lines · Mike Lothian

Core Rust abstractions a USB display driver needs. They are separated from the driver because none of them are display specific: each one covers a kernel facility that has C callers today and no Rust binding

The rest of the posting, which is one series per subsystem:

rust-core, 9 patches, this one

Just in case it helps: these patches touch different subsystems, not only one -- some of them may want that you split things up accordingly.

I hope that clarifies.

Cheers,
Miguel