From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A6D7E235042; Wed, 9 Jul 2025 17:53:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083617; cv=none; b=kbBlPIcIW30on2fbx0w8S5dGJs8al0GQzAI/t4b4ldf06x3YfbpXyLXZBhwo4u3f1eepZJBsgxcF/VlBWrtAlClM8HQjmaZ6VAMYOL1QVP8prM5PjlN+017xqSpL0uCrseL03CVCBumOMKjtZ4BU0xhRojzrgC5QrZlqzvPcCco= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083617; c=relaxed/simple; bh=ZRLjD2W6uhaXymWrGFzTIhA8R1ZIxNIhAh+LvZBB6fU=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=uqtjjW0dXkg6hJ60rvemhd/qvLEI8AGZlU/pNzgjtS87RPrNqqEyiKh8ikdIHxBoiNplCG/DoBj+uJX97nYThqVESn2tvWPrqf6TKNUIZMVaa20mRPUgXI8VfRzwMx+hHpBanjIy+BV5eP216ei/fgicacfh+vivcP2uqrdK6TE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Cqre8FAw; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Cqre8FAw" Received: by smtp.kernel.org (Postfix) with ESMTPSA id E77ABC4CEEF; Wed, 9 Jul 2025 17:53:28 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083615; bh=ZRLjD2W6uhaXymWrGFzTIhA8R1ZIxNIhAh+LvZBB6fU=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=Cqre8FAwHpU7XZdkZGEeKFTxM6L4ydZxBEiaBkgLAqEKZ5B7RrHCvIvyhZBgiowxN C+l0NdEhBZJj0A30ccSd1Qn0s3mzOCUKXjsC2/aY4dM2zH2v3KPC1syuTAiYheBLYj JGQUeM0RK5PfpUUh086VMMNruvO5YX0stGnQ+C1avZk4UDQIcd4oK2pyQsPuAIqv+A moXHDS8ddeVkyFfZU48gVyNMV7sJEkOpfk+e54y90d8XnZVHDDJPOhsnvkNdUhebAm NCTSTICm5h+OcLsE07dxX14ij5sca2LoguUXd7mBGsjMd8dV9PCLaQOBghp49up8rP oMhy0uj6lxfBQ== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:15 +0200 Subject: [PATCH v16 1/7] rust: sync: add `SetOnce` Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-1-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=5376; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=ZRLjD2W6uhaXymWrGFzTIhA8R1ZIxNIhAh+LvZBB6fU=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxZjoOXK9v/fIdnhE/vluSNmdrCUxFKMt/Np wp/G3xBQq+JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sWQAKCRDhuBo+eShj dxdOD/92wpNNbYWglvU96Xzbrqw+7p38RhiaIT1PO9KceKNswDDcTf/Bw4/PhQ7g4lYXx45w+97 4EuuIq+FpGJwgnDM5mUvzrmf3oV4wtQuig+dUIi5TrFTgMX0FSN/ue43xHSf5QO8gUB3L/c608x ySDGc67vrbduEAt9gKtMw/24Ph5sqrbJDH1oWj/xf7jHht7m3MsG8JOmYTyYi8Gu2LTkG5v18bg eeZbcBz3013Fi1Ma4XB3NzRoGb5itq8aY7eb8R0AUTL9AY6JiJbjblYYE86tiaJYYxzMAf1FFrQ DkAxma7nildRROUACTlgYnzXP2fb7Qzt0A8TNWNql0KVt9uOdy6RbDtC5+1LRImj1za10RRTAfJ /vKHOg0eJ6bFWJ4tEB4ZCG9YeC0Rmk7A2pjvEnerEB2kGVksKrVL3I4BloC4IGRNNE/ClPChPc0 LKig8f+Yk9GECbCZjY+h1Ane7E/4VWEJ+EIf5vpyT2tt7z7ngUeW19PFEvaBJ1xcuOuc7AWb1EQ L9g2LT3MxJYJwGZci8PcaUvO9Zlfdaj/YPGxqJmz2MbFR9KbF7m9XMkP+WN6UdMDHlaLAMVLb8w jcbHmtFn7Hbt8GF52JdmycHELXwIfcK8UoJo9UlfI0wlpP+4+EdKr+6zo5zSDt8fosWo/LdjXB0 T7E1dyTwzsUckgg== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Introduce the `SetOnce` type, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value. Reviewed-by: Alice Ryhl Signed-off-by: Andreas Hindborg Reviewed-by: Benno Lossin --- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 122 +++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 124 insertions(+) diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index 81e3a806e57e2..13e6bc7fa87ac 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -18,6 +18,7 @@ mod locked_by; pub mod poll; pub mod rcu; +mod set_once; =20 pub use arc::{Arc, ArcBorrow, UniqueArc}; pub use completion::Completion; @@ -26,6 +27,7 @@ pub use lock::mutex::{new_mutex, Mutex, MutexGuard}; pub use lock::spinlock::{new_spinlock, SpinLock, SpinLockGuard}; pub use locked_by::LockedBy; +pub use set_once::SetOnce; =20 /// Represents a lockdep class. It's a wrapper around C's `lock_class_key`. #[repr(transparent)] diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs new file mode 100644 index 0000000000000..73706abfe9991 --- /dev/null +++ b/rust/kernel/sync/set_once.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A container that can be initialized at most once. + +use super::atomic::{ + ordering::{Acquire, Relaxed, Release}, + Atomic, +}; +use core::{cell::UnsafeCell, mem::MaybeUninit, ptr::drop_in_place}; + +/// A container that can be populated at most once. Thread safe. +/// +/// Once the a [`SetOnce`] is populated, it remains populated by the same = object for the +/// lifetime `Self`. +/// +/// # Invariants +/// +/// - `init` may only increase in value. +/// - `init` may only assume values in the range `0..=3D2`. +/// - `init =3D=3D 0` if and only if the container is empty. +/// - `init =3D=3D 1` if and only if being initialized. +/// - `init =3D=3D 2` if and only if the container is populated and valid = for shared access. +/// +/// # Example +/// +/// ``` +/// # use kernel::sync::SetOnce; +/// let value =3D SetOnce::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status =3D value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status =3D value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct SetOnce { + init: Atomic, + value: UnsafeCell>, +} + +impl Default for SetOnce { + fn default() -> Self { + Self::new() + } +} + +impl SetOnce { + /// Create a new [`SetOnce`]. + /// + /// The returned instance will be empty. + pub const fn new() -> Self { + // INVARIANT: The container is empty and we initialize `init` to `= 0`. + Self { + value: UnsafeCell::new(MaybeUninit::uninit()), + init: Atomic::new(0), + } + } + + /// Get a reference to the contained object. + /// + /// Returns [`None`] if this [`SetOnce`] is empty. + pub fn as_ref(&self) -> Option<&T> { + if self.init.load(Acquire) =3D=3D 2 { + // SAFETY: By the type invariants of `Self`, `self.init =3D=3D= 2` means that `self.value` + // contains a valid value. + Some(unsafe { &*self.value.get().cast() }) + } else { + None + } + } + + /// Populate the [`SetOnce`]. + /// + /// Returns `true` if the [`SetOnce`] was successfully populated. + pub fn populate(&self, value: T) -> bool { + // INVARIANT: If the swap succeeds: + // - We increase `init`. + // - We write the valid value `1` to `init`. + // - Only one thread can succeed in this write, so we have exclus= ive access after the + // write. + if let Ok(0) =3D self.init.cmpxchg(0, 1, Relaxed) { + // SAFETY: By the type invariants of `Self`, the fact that we = succeeded in writing `1` + // to `self.init` means we obtained exclusive access to the co= ntained object. + unsafe { core::ptr::write(self.value.get().cast(), value) }; + // INVARIANT: + // - We increase `init`. + // - We write the valid value `2` to `init`. + // - We release our exclusive access to the contained object = and the object is now + // valid for shared access. + self.init.store(2, Release); + true + } else { + false + } + } + + /// Get a copy of the contained object. + /// + /// Returns [`None`] if the [`SetOnce`] is empty. + pub fn copy(&self) -> Option + where + T: Copy, + { + self.as_ref().copied() + } +} + +impl Drop for SetOnce { + fn drop(&mut self) { + if *self.init.get_mut() =3D=3D 2 { + // SAFETY: By the type invariants of `Self`, `self.init =3D=3D= 2` means that `self.value` + // contains a valid value. We have exclusive access, as we hol= d a `mut` reference to + // `self`. + unsafe { drop_in_place(self.value.get()) }; + } + } +} --=20 2.47.2 From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 251082367D5; Wed, 9 Jul 2025 17:53:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083603; cv=none; b=HJtnJoBK39O2WzyBsu4LsRQdGsTIE9PkHGJX8HuJqOelm4OutyQuJcAiAX1uqCkhLnWfOWCoBeemRuABQcAAmJAAeDwkux561Dn6xWRFBhLevx+PsQkx9pRmSB/vDqSnvEuh3FODMyZ6PcOmcUKKqePlSMu5PAPdCOmnqU3gguA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083603; c=relaxed/simple; bh=vnhrnZoqCOSxPZpKLyqXVV9GSxdxKUhjz/8U+E7/dOI=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=pPpCH+EKIb9pW8qElnGxo7oR3XirRToVX/eDtOx0GBLd4gkL4xKjud751k2kJG3GU7BVsZtvux3bLOAezfKeSvWbtQlaZ2Wks9f2LoAwJNhVWehiLFl3Apk+2Vqn6JfGzhEwiqMqpFJJLPUTeGRPmoRKgfwkLN444kWWyk87kB0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=q6BQKwH8; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="q6BQKwH8" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D764BC4CEF0; Wed, 9 Jul 2025 17:53:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083602; bh=vnhrnZoqCOSxPZpKLyqXVV9GSxdxKUhjz/8U+E7/dOI=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=q6BQKwH82X4k6gr3QxfuudfM6HDrNDg+q0+ZeIbSar/Ohn6UNwwpxbRgle2kG+1R4 EwRisjw+fC/FHXhXLe66wn4WU3V6+te1i2ooyB4UtEp81iWZjn4FUGoP1KbYj5fGgy e7YnkcoMA0hkIghOSAZ3WYrnndvfm0EZEKNCq6w9tr5rbYIMVocBDvM2qIRNRhP6Ov 3BMfID6nNR7aWpYf6BuKZw+iCKj9jChxVYYFDEyxP4K4St3DX2NQn5N1SZlz/0HxVT MWi1O2oj939wMWWg7pAXWHSaSyvi3xMcyftMOt56L/41uyF7O4OPSjRKVPmH+9ZHI0 t7rn/TWMbZL8A== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:16 +0200 Subject: [PATCH v16 2/7] rust: str: add radix prefixed integer parsing functions Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-2-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=7204; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=vnhrnZoqCOSxPZpKLyqXVV9GSxdxKUhjz/8U+E7/dOI=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxaGCRE05fxIu4Ev/s8nhJWIPjVkBv+9Nlpv H6HmZ6+xBaJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sWgAKCRDhuBo+eShj dzg3D/41dvf6TBzM9feVsRE6rDC5IE6lCjwjPy1armbw8+Icw+7enkitsKw1FDYxF1+ngQ/TZet VFwoJ3YKXIcxlXvfMZaM2oio+XuVd6Y3tfBjDnVCtGfVwBlHowu0s8TJEbk3X5wu90jjDMHQL2S DlXeOjGa8/mwwUfVINc0fXNoeWUy/p+/8KgKNRmk629KDcqnExjz9Mzl77sm1b/yZ951C6oV21T 3X21nhw/IIKUNZRKX5R4hcgCG32x5l6PYypNkyEWs+GHrYX40sbGFN3DlC38dqXQa1pfwI9KA0w Cu9eOLWoZX7iT51rZYdT5oOIIXo81xB7T3n3qV/Z7EbH0vKOkWZYoFtbIhy/ZbiZnEBsmYoLB6q vrsvp97y6g29p1PhmmTRRHFQjclh9oHJrviUc3+ilkpGXY8fK/H+YbO29zCuuHbZ3NEo7lxLw4l MoyWw5pkFIVVWtP57g5LzNDuafgKUvKdngE400MVCv4D/nmBbNbbMc7SIkiOPG/GjXLGdmpdi4f wUHPgCR4U/Jmq0WU0UhelGhU5vxX59X+CL+/IcKcK/jSxXRpB4YwTrMYO+pOi77wVr+I5+MIU9v lZ9wvjXfa5n5MftIQC/PBteps1+upB8OachT0ueQQaacqvwCqnV4v4Y9ZsNSTXAU9a+1PNHMvPj f8QewolJDr/xvLg== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add the trait `ParseInt` for parsing string representations of integers where the string representations are optionally prefixed by a radix specifier. Implement the trait for the primitive integer types. Suggested-by: Benno Lossin Tested-by: Daniel Gomez Reviewed-by: Greg Kroah-Hartman Reviewed-by: Benno Lossin Signed-off-by: Andreas Hindborg --- rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 150 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index a927db8e079c3..2b6c8b4a0ae4b 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -8,6 +8,8 @@ =20 use crate::prelude::*; =20 +pub mod parse_int; + /// Byte string without UTF-8 validity guarantee. #[repr(transparent)] pub struct BStr([u8]); diff --git a/rust/kernel/str/parse_int.rs b/rust/kernel/str/parse_int.rs new file mode 100644 index 0000000000000..48eb4c202984c --- /dev/null +++ b/rust/kernel/str/parse_int.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Integer parsing functions. +//! +//! Integer parsing functions for parsing signed and unsigned integers +//! potentially prefixed with `0x`, `0o`, or `0b`. + +use crate::prelude::*; +use crate::str::BStr; +use core::ops::Deref; + +// Make `FromStrRadix` a public type with a private name. This seals +// `ParseInt`, that is, prevents downstream users from implementing the +// trait. +mod private { + use crate::prelude::*; + use crate::str::BStr; + + /// Trait that allows parsing a [`&BStr`] to an integer with a radix. + pub trait FromStrRadix: Sized { + /// Parse `src` to [`Self`] using radix `radix`. + fn from_str_radix(src: &BStr, radix: u32) -> Result; + + /// Tries to convert `value` into [`Self`] and negates the resulti= ng value. + fn from_u64_negated(value: u64) -> Result; + } +} + +/// Extract the radix from an integer literal optionally prefixed with +/// one of `0x`, `0X`, `0o`, `0O`, `0b`, `0B`, `0`. +fn strip_radix(src: &BStr) -> (u32, &BStr) { + match src.deref() { + [b'0', b'x' | b'X', rest @ ..] =3D> (16, rest.as_ref()), + [b'0', b'o' | b'O', rest @ ..] =3D> (8, rest.as_ref()), + [b'0', b'b' | b'B', rest @ ..] =3D> (2, rest.as_ref()), + // NOTE: We are including the leading zero to be able to parse + // literal `0` here. If we removed it as a radix prefix, we would + // not be able to parse `0`. + [b'0', ..] =3D> (8, src), + _ =3D> (10, src), + } +} + +/// Trait for parsing string representations of integers. +/// +/// Strings beginning with `0x`, `0o`, or `0b` are parsed as hex, octal, or +/// binary respectively. Strings beginning with `0` otherwise are parsed as +/// octal. Anything else is parsed as decimal. A leading `+` or `-` is also +/// permitted. Any string parsed by [`kstrtol()`] or [`kstrtoul()`] will be +/// successfully parsed. +/// +/// [`kstrtol()`]: https://docs.kernel.org/core-api/kernel-api.html#c.kstr= tol +/// [`kstrtoul()`]: https://docs.kernel.org/core-api/kernel-api.html#c.kst= rtoul +/// +/// # Examples +/// +/// ``` +/// # use kernel::str::parse_int::ParseInt; +/// # use kernel::b_str; +/// +/// assert_eq!(Ok(0u8), u8::from_str(b_str!("0"))); +/// +/// assert_eq!(Ok(0xa2u8), u8::from_str(b_str!("0xa2"))); +/// assert_eq!(Ok(-0xa2i32), i32::from_str(b_str!("-0xa2"))); +/// +/// assert_eq!(Ok(-0o57i8), i8::from_str(b_str!("-0o57"))); +/// assert_eq!(Ok(0o57i8), i8::from_str(b_str!("057"))); +/// +/// assert_eq!(Ok(0b1001i16), i16::from_str(b_str!("0b1001"))); +/// assert_eq!(Ok(-0b1001i16), i16::from_str(b_str!("-0b1001"))); +/// +/// assert_eq!(Ok(127i8), i8::from_str(b_str!("127"))); +/// assert!(i8::from_str(b_str!("128")).is_err()); +/// assert_eq!(Ok(-128i8), i8::from_str(b_str!("-128"))); +/// assert!(i8::from_str(b_str!("-129")).is_err()); +/// assert_eq!(Ok(255u8), u8::from_str(b_str!("255"))); +/// assert!(u8::from_str(b_str!("256")).is_err()); +/// ``` +pub trait ParseInt: private::FromStrRadix + TryFrom { + /// Parse a string according to the description in [`Self`]. + fn from_str(src: &BStr) -> Result { + match src.deref() { + [b'-', rest @ ..] =3D> { + let (radix, digits) =3D strip_radix(rest.as_ref()); + // 2's complement values range from -2^(b-1) to 2^(b-1)-1. + // So if we want to parse negative numbers as positive and + // later multiply by -1, we have to parse into a larger + // integer. We choose `u64` as sufficiently large. + // + // NOTE: 128 bit integers are not available on all + // platforms, hence the choice of 64 bits. + let val =3D + u64::from_str_radix(core::str::from_utf8(digits).map_e= rr(|_| EINVAL)?, radix) + .map_err(|_| EINVAL)?; + Self::from_u64_negated(val) + } + _ =3D> { + let (radix, digits) =3D strip_radix(src); + Self::from_str_radix(digits, radix).map_err(|_| EINVAL) + } + } + } +} + +macro_rules! impl_parse_int { + ($($ty:ty),*) =3D> { + $( + impl private::FromStrRadix for $ty { + fn from_str_radix(src: &BStr, radix: u32) -> Result { + <$ty>::from_str_radix(core::str::from_utf8(src).map_er= r(|_| EINVAL)?, radix) + .map_err(|_| EINVAL) + } + + fn from_u64_negated(value: u64) -> Result { + const ABS_MIN: u64 =3D { + #[allow(unused_comparisons)] + if <$ty>::MIN < 0 { + 1u64 << (<$ty>::BITS - 1) + } else { + 0 + } + }; + + if value > ABS_MIN { + return Err(EINVAL); + } + + if value =3D=3D ABS_MIN { + return Ok(<$ty>::MIN); + } + + // SAFETY: The above checks guarantee that `value` fit= s into `Self`: + // - if `Self` is unsigned, then `ABS_MIN =3D=3D 0` an= d thus we have returned above + // (either `EINVAL` or `MIN`). + // - if `Self` is signed, then we have that `0 <=3D va= lue < ABS_MIN`. And since + // `ABS_MIN - 1` fits into `Self` by construction, `= value` also does. + let value: Self =3D unsafe { value.try_into().unwrap_u= nchecked() }; + + Ok((!value).wrapping_add(1)) + } + } + + impl ParseInt for $ty {} + )* + }; +} + +impl_parse_int![i8, u8, i16, u16, i32, u32, i64, u64, isize, usize]; --=20 2.47.2 From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5A7FA23A578; Wed, 9 Jul 2025 17:53:12 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083592; cv=none; b=vCoJta3jXMfhtu4USLutQxlB95b/inZBzxKi4w4HB/F9i5bUD1yN6KMcvTzrmpFPGJaxtsJBgQlKnWb3p9fs9IDn9It6qFTNrkye5LEPHDDmuKIL61eofHJvC9jpcBekiY1lKYVwsyUM7tj5L3eEw3OIWoBpp9oyNIYf+2zM7O8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083592; c=relaxed/simple; bh=IaejDxR65nfkpFtQKTy5h1EB3F8o0R9aHHtFm2+Kn0U=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=suB8j3HhtQthseSSd30ESD3vdwiPNzeua3vAAjayr+LxeWKk69VampkPyVh2ygHLg4iDCb6acVabMPy0ypEMOK/FTTmeXgdpGLAsRGs70NWCGafQCy7zcz55MWYHAwAF7JA+lGexrUAPaIAE9qRJRT49q1XiiUDLlMAnieZ05vg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=jfU/XrOE; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="jfU/XrOE" Received: by smtp.kernel.org (Postfix) with ESMTPSA id DF237C4CEEF; Wed, 9 Jul 2025 17:53:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083591; bh=IaejDxR65nfkpFtQKTy5h1EB3F8o0R9aHHtFm2+Kn0U=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=jfU/XrOEWKyrCb7wBo6eyS4OYFSnVO7enlwcWGDpyt5BYeiS86sCkY+3ujUjVpJeV om6LkmVnSscxB05kN+kEo4h6FFpmeZD0I/FXBfPgI9ytaQTDXc5kQTEwgkXEN0qHAx nkEh397d/J+lHCi6oweoEhlpkBTW6HV3fx7YXoZIkuqBtSyfQ/a/zXh3bghRn8dWtl i19K1hSSLN+AGpUirLDWmU/IvE0veQ7rfYGAk8mwFp0ceMYbdYQb7giId0N05zCtfR OC0ozQSWCpthDLJt6paMWTZgITeb3HNT+m2DIaV65udavTh/WGakh+lH24KyT8WHth C+qe1VyCIAErQ== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:17 +0200 Subject: [PATCH v16 3/7] rust: introduce module_param module Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-3-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=6945; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=IaejDxR65nfkpFtQKTy5h1EB3F8o0R9aHHtFm2+Kn0U=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxbxvtD6Y5BRYT77LvuDMdsqharPbLo77r6s sAlXqP4yeKJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sWwAKCRDhuBo+eShj d8DwD/oCecyk5hJidsgMMfDxKiUr2WwOdSPYXiuwS1tBI2zCp2x7gqayH3of7UBqwaQfESbRmh0 tjbO1TUBgoNiHdxdVA+swcWm4BSg1iFN1R1+M87iq8b1wGBrcH6BzBBd9kMnJIDPW7mguw3CBW4 nsZTh76L0t7tZifiRaPAeTSKywApD2oLWO2Ay7uHx37ixb5I3Uev23nPo+zIaM++LuEP8G2E+MV 7KCIpJ2QYP0Mv22Cu5gQw7nNk4IaNjK1FSzDYz9DeRoXsz9csKiTE2VRy0DgCEx5oWzOztF4c5A T2U2KUMZxYK8hqN1qHwJzIYHBoleXUK+EJLgs4OhmGSSpYL5CwU+AHvT/fJtB+YlNZNwpjRl6Sd v1yjccrIFQLI/hcGV/e+C9eC6ZEC9rqnwSKM5QfxdUkjWdkH1ug7eN0S1LwkOzicEzOnrMiYa2M f9clWDOVSu+pTYZfovfQy449KEUNLECAVVGENnzjz9yf/rGGkyhYQo+JpKhjL0u09vdmdSEbjUm ZMVnZtr984erJHNFSRqYq8JLTb3e9yfw9HyWtk+eitvaziQKNOV+YeJqRyXOMxhVPVMTjbXtLRR 649ppCZLgHj1cgYaHdotUsb2YjMT6bz1h3xVK07TkTe21TGpyAj6Xva1qPOmI0qdW0rMDRyeSbw MeflsNfvAyCzw/g== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add types and traits for interfacing the C moduleparam API. Reviewed-by: Benno Lossin Signed-off-by: Andreas Hindborg --- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 181 ++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 182 insertions(+) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 6b4774b2b1c37..2b439ea061850 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -87,6 +87,7 @@ pub mod list; pub mod miscdevice; pub mod mm; +pub mod module_param; #[cfg(CONFIG_NET)] pub mod net; pub mod of; diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs new file mode 100644 index 0000000000000..9b187ed1d3513 --- /dev/null +++ b/rust/kernel/module_param.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Support for module parameters. +//! +//! C header: [`include/linux/moduleparam.h`](srctree/include/linux/module= param.h) + +use crate::prelude::*; +use crate::str::BStr; +use bindings; +use kernel::sync::SetOnce; + +/// Newtype to make `bindings::kernel_param` [`Sync`]. +#[repr(transparent)] +#[doc(hidden)] +pub struct KernelParam(bindings::kernel_param); + +impl KernelParam { + #[doc(hidden)] + pub const fn new(val: bindings::kernel_param) -> Self { + Self(val) + } +} + +// SAFETY: C kernel handles serializing access to this type. We never acce= ss it +// from Rust module. +unsafe impl Sync for KernelParam {} + +/// Types that can be used for module parameters. +// NOTE: This trait is `Copy` because drop could produce unsoundness durin= g teardown. +pub trait ModuleParam: Sized + Copy { + /// Parse a parameter argument into the parameter value. + fn try_from_param_arg(arg: &BStr) -> Result; +} + +/// Set the module parameter from a string. +/// +/// Used to set the parameter value at kernel initialization, when loading +/// the module or when set through `sysfs`. +/// +/// See `struct kernel_param_ops.set`. +/// +/// # Safety +/// +/// - If `val` is non-null then it must point to a valid null-terminated s= tring that must be valid +/// for reads for the duration of the call. +/// - `param` must be a pointer to a `bindings::kernel_param` initialized = by the rust module macro. +/// The pointee must be valid for reads for the duration of the call. +/// +/// # Note +/// +/// - The safety requirements are satisfied by C API contract when this fu= nction is invoked by the +/// module subsystem C code. +/// - Currently, we only support read-only parameters that are not readabl= e from `sysfs`. Thus, this +/// function is only called at kernel initialization time, or at module = load time, and we have +/// exclusive access to the parameter for the duration of the function. +/// +/// [`module!`]: macros::module +unsafe extern "C" fn set_param(val: *const c_char, param: *const bindin= gs::kernel_param) -> c_int +where + T: ModuleParam, +{ + // NOTE: If we start supporting arguments without values, val _is_ all= owed + // to be null here. + if val.is_null() { + // TODO: Use pr_warn_once available. + crate::pr_warn!("Null pointer passed to `module_param::set_param`"= ); + return EINVAL.to_errno(); + } + + // SAFETY: By function safety requirement, val is non-null, null-termi= nated + // and valid for reads for the duration of this function. + let arg =3D unsafe { CStr::from_char_ptr(val) }; + + crate::error::from_result(|| { + let new_value =3D T::try_from_param_arg(arg)?; + + // SAFETY: By function safety requirements, this access is safe. + let container =3D unsafe { &*((*param).__bindgen_anon_1.arg as *mu= t SetOnce) }; + + container + .populate(new_value) + .then_some(0) + .ok_or(kernel::error::code::EEXIST) + }) +} + +macro_rules! impl_int_module_param { + ($ty:ident) =3D> { + impl ModuleParam for $ty { + fn try_from_param_arg(arg: &BStr) -> Result { + <$ty as crate::str::parse_int::ParseInt>::from_str(arg) + } + } + }; +} + +impl_int_module_param!(i8); +impl_int_module_param!(u8); +impl_int_module_param!(i16); +impl_int_module_param!(u16); +impl_int_module_param!(i32); +impl_int_module_param!(u32); +impl_int_module_param!(i64); +impl_int_module_param!(u64); +impl_int_module_param!(isize); +impl_int_module_param!(usize); + +/// A wrapper for kernel parameters. +/// +/// This type is instantiated by the [`module!`] macro when module paramet= ers are +/// defined. You should never need to instantiate this type directly. +/// +/// Note: This type is `pub` because it is used by module crates to access +/// parameter values. +pub struct ModuleParamAccess { + value: SetOnce, + default: T, +} + +// SAFETY: We only create shared references to the contents of this contai= ner, +// so if `T` is `Sync`, so is `ModuleParamAccess`. +unsafe impl Sync for ModuleParamAccess {} + +impl ModuleParamAccess { + #[doc(hidden)] + pub const fn new(default: T) -> Self { + Self { + value: SetOnce::new(), + default, + } + } + + /// Get a shared reference to the parameter value. + // Note: When sysfs access to parameters are enabled, we have to pass = in a + // held lock guard here. + pub fn value(&self) -> &T { + self.value.as_ref().unwrap_or(&self.default) + } + + /// Get a mutable pointer to `self`. + /// + /// NOTE: In most cases it is not safe deref the returned pointer. + pub const fn as_void_ptr(&self) -> *mut c_void { + core::ptr::from_ref(self).cast_mut().cast() + } +} + +#[doc(hidden)] +/// Generate a static [`kernel_param_ops`](srctree/include/linux/modulepar= am.h) struct. +/// +/// # Examples +/// +/// ```ignore +/// make_param_ops!( +/// /// Documentation for new param ops. +/// PARAM_OPS_MYTYPE, // Name for the static. +/// MyType // A type which implements [`ModuleParam`]. +/// ); +/// ``` +macro_rules! make_param_ops { + ($ops:ident, $ty:ty) =3D> { + #[doc(hidden)] + pub static $ops: $crate::bindings::kernel_param_ops =3D $crate::bi= ndings::kernel_param_ops { + flags: 0, + set: Some(set_param::<$ty>), + get: None, + free: None, + }; + }; +} + +make_param_ops!(PARAM_OPS_I8, i8); +make_param_ops!(PARAM_OPS_U8, u8); +make_param_ops!(PARAM_OPS_I16, i16); +make_param_ops!(PARAM_OPS_U16, u16); +make_param_ops!(PARAM_OPS_I32, i32); +make_param_ops!(PARAM_OPS_U32, u32); +make_param_ops!(PARAM_OPS_I64, i64); +make_param_ops!(PARAM_OPS_U64, u64); +make_param_ops!(PARAM_OPS_ISIZE, isize); +make_param_ops!(PARAM_OPS_USIZE, usize); --=20 2.47.2 From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 744722367D5; Wed, 9 Jul 2025 17:53:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083608; cv=none; b=UQyMNfCX84FRSzh3uftv5Ol0Emgt1Arb3rNu9DDiNloWlUQ/VB9u0gLUff21+kkWhPuN8TgCStdnOVtGYo4UiAteBZdG2J8Dl9cweP2x7SosMy2Y9uteZTU6HRkau+NjefUjQ4EOB2fmAPU+cfzSF1MBIFa5sNXmykc/1rWXFX4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083608; c=relaxed/simple; bh=K4Z3grvB4L1O4ywtrXjL9L/tEi3YiQY6qMjemNcyFag=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=K/mI/zvMbU+oh9tL7njq9HTWBWYoyzaTny0r6X4xwy9Jh2RckUwSXIYMs75HiQt7AF1KN6P/exhTjtz2cAj9cqepACLs6cbkCkEPtkL1yFXYWE+23SVEICRRpF2dWHQZh4vISmVlkDUwFW26PeoBgiNAPUbl+rVnO3t+TZo+zFg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=gDByGWqy; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="gDByGWqy" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 50C5AC4CEEF; Wed, 9 Jul 2025 17:53:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083608; bh=K4Z3grvB4L1O4ywtrXjL9L/tEi3YiQY6qMjemNcyFag=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=gDByGWqy4Pd2AbRVXbGO82Kx1MATnECI4uKMSPzF8as/7VPHFeF+qw81IgYtPgNf4 6HgUNqQb77vsvVoMPFjCtUF9YaIRIS6fgZWPmTKbmsTdZGqtEfVbqGTFUCz/8XVk3T 65cuN3VRHXWidp034CaAfAUpGd0YzcCwRWCYkTp6Bf7y+GO2gRRJxgoIM0P5PM/q3k 6IEjc5TOEbZXptVhvlucWDhG6lgMjZXyJhGOIgUKIu3E4uS0gtpP0cmwQHco0UfR9Y ZJTLm0ONZGSg7c9XOoRTR9695aiY1K79Ch5Rr19sDHpbPVnNZIpxyqk0TkbB1axm4Z 5bZ0WHGkUcUyQ== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:18 +0200 Subject: [PATCH v16 4/7] rust: module: use a reference in macros::module::module Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-4-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=2065; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=K4Z3grvB4L1O4ywtrXjL9L/tEi3YiQY6qMjemNcyFag=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxcHy/kWWAyrw6ui9lv70j5vOxZSf0ftzrFP CmvplqqarCJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sXAAKCRDhuBo+eShj d8mcD/4uWd0BkILOPTqHaLscHwXCRKmJ4jOFwmBxxR54Ns7ekwJjyMekCM4VPq76OEBklcX0/Y9 rEPWWSytfV4uLPwdXiPFJhz0zfgD4zxXLgpFGFGRahEWDJfcZc5tD6vzghSSoujXIxPt8RK1/Q2 iMxg2HK61PHf92bUA7QhXyNjjBx69aM/Vfzidf7O4/QoDRLCZ+5OGu2cL8CSWYf2cX7OoD8yI1+ waGp4faguOXnBpRmy/On4ON37Lnm99d1JAXEHHAmcYN3ZgdN3CsmKyUzjSGeE4NC+yEBvKMweWP nFjzWWeku+hPAEqtCGOnQveSuVStTDXxDUOa9WQ8A26B1AFHC1C03sfdeROkZb5SQnaN4/yfmGa 0LE3aGEq4eRJ/Pz1EZsssXKuyXUvIpNGDw3EPHA2mxqUHOy/nzRg5NJ0IAUBwP8pc6lX5TCg643 NZNnALWQ9D/hqYZapNJCgXx6DrxpINYw86Ic10A7UEuxZfsiViNiYeDdCYMdlyhLOdPWutYvKuy 371CnvkJEvQ4RFQEFSqrP3GqPD/f9TlmEJVF2GRPKimNkOUaFUL/f1n4BACjzIV4Y2UT4uuC/Y9 kTM57ZHg6E/2LRwmkjcZy3ou/+0v0YGtYC/VjAjvjw8KxjDkuI4d244hV4ERsIMQ+D7UXXOX/AG vPRXPv7F3VThMMQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 When we add parameter support to the module macro, we want to be able to pass a reference to `ModuleInfo` to a helper function. That is not possible when we move out of the local `modinfo`. So change the function to access the local via reference rather than value. Reviewed-by: Benno Lossin Signed-off-by: Andreas Hindborg --- rust/macros/module.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index 2ddd2eeb28521..1a867a1e787ed 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -179,26 +179,26 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { // Rust does not allow hyphens in identifiers, use underscore instead. let ident =3D info.name.replace('-', "_"); let mut modinfo =3D ModInfoBuilder::new(ident.as_ref()); - if let Some(author) =3D info.author { - modinfo.emit("author", &author); + if let Some(author) =3D &info.author { + modinfo.emit("author", author); } - if let Some(authors) =3D info.authors { + if let Some(authors) =3D &info.authors { for author in authors { - modinfo.emit("author", &author); + modinfo.emit("author", author); } } - if let Some(description) =3D info.description { - modinfo.emit("description", &description); + if let Some(description) =3D &info.description { + modinfo.emit("description", description); } modinfo.emit("license", &info.license); - if let Some(aliases) =3D info.alias { + if let Some(aliases) =3D &info.alias { for alias in aliases { - modinfo.emit("alias", &alias); + modinfo.emit("alias", alias); } } - if let Some(firmware) =3D info.firmware { + if let Some(firmware) =3D &info.firmware { for fw in firmware { - modinfo.emit("firmware", &fw); + modinfo.emit("firmware", fw); } } =20 --=20 2.47.2 From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DA87E2356D2; Wed, 9 Jul 2025 17:53:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083588; cv=none; b=O1G3ukKCLVaP1w6Vhsy/JTtGBN9j3+H8GEcdQjac5RqJS0UnHcQ1eJPIWGTa3bzxr+CdEvgZns7dn3PODEgBQgEzkiANeZ9SzM9l6Dl6AQNDM3PBxp4HIEK6HeyyTJMlbBcFIw8Pfj9bt5j6FEO1BUrr7HdU7iO7h6FNqJAdc3U= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083588; c=relaxed/simple; bh=2YIwwnFSN+fDOy0TmIgAKz1LQndsAk+izFq3MdUVAOE=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=ukpwenUP+rLCkExHJTLLp1aT0Trc1C1eqhqNU7miodb6qqg+HvOiGCqkCFg21YWK7J1t2C4xmHGntmDeHV6GNFUiqJ06kDmqNWB7Pu/xCssHSKYumDvkYAz6yfuM1oKIt+3RUsYG59psGeNvJFNcVECtLtyBYWAe8lwl1iGkpt4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=a/F8T658; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="a/F8T658" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6599BC4AF09; Wed, 9 Jul 2025 17:53:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083586; bh=2YIwwnFSN+fDOy0TmIgAKz1LQndsAk+izFq3MdUVAOE=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=a/F8T658C8fi0SOqn3zUBMavgWESPdqb7mNeVTA0Zfft4psjiBjdaNpNEUjA51B46 a8/0GHLgfxqBQX0VRT2TVFY3ng0TlmJ1ufgF0nbig6K1T+sSD6pASZ6mo76F+ScV1A 3ntlOi/1YPbVOqiTNcDm/MjJpp+0Bld6Q1gY7sSQ/VzW/rviRTq/yXFRz52dNCwf6o qe2z+ckt43Px4L2eptGP0+XOF+TVAy2Dy4tUJ0DivIPpNXZMxoZzWVnWBu+0Q1BpRt MYGsaVKG/0GeZ409/d5wYhvLe20/UL8gw5tMW19DzMdMjz64l+MjOKAQKq/WaUR6Kj C+DQOVKq0+cgw== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:19 +0200 Subject: [PATCH v16 5/7] rust: module: update the module macro with module parameter support Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-5-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=13520; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=2YIwwnFSN+fDOy0TmIgAKz1LQndsAk+izFq3MdUVAOE=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxdueBGrOnGVPUjoBYrJZN28rPJRM0CNk0ND ctVahP2r8WJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sXQAKCRDhuBo+eShj d9a2D/96a7t60ZOu/xb3egCMSokP7n548GbQMs9XJvoQocnvFNBpxP0b+JYAW1FFtGxk+PiPPAf T+PqrFVzYrrjjreaMiXiE4lVCFbzyrpp/U/svzTx6oFcNg6U7fIul5EIzL4ibyFz9iRqxwERUFD SH6jYgZFMtLkOjwkcy3TH4TQEkxVt+1OzHYsnhAOADUbENF2zfDoBxQnqQS7/bEybHfFbjTE0/2 SD12oV1d4918m+CrUQ+VE5Wa4ULqYnItAyoQAev1c9ndXgI8XFDBwxqmg6LTj1NPSEivcl//Fby kP7DQmROP85W08qfukgl/e7IHFlE27jmNhLheGocLc3AQ27MIoY3B0OMCAEFSpGoilob1DIvRD6 LGJsDPCaOsVSUubxwg1dz81ZywJF6Chh2oZHM7MFfDGpzuX2oaJfB4k0vY9Llicz4LSZ4jOiu5i x5OG/zQ65gh1CfUd7C/LLLI5U66No0szFF4ksdQXKGTKH/eukjan08bUybcs4g3JsfK7GiM4Xlk giq/lKkvnUagJNukac6v83khRwW4K7vRxzqMexWIhGK6MCgv0BMAkXWIh8nvIkQUJ/wQL1tFl+x b7IeTCD8EaYq6YoakwcSjGS4AnUlRAbAt7BNN6xozJrP9oSiM/9epA6Ff5PXz32xpK+a3gFKiSp FzlCXJinbySoZWQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Allow module parameters to be declared in the rust `module!` macro. Reviewed-by: Benno Lossin Signed-off-by: Andreas Hindborg --- rust/macros/helpers.rs | 25 +++++++ rust/macros/lib.rs | 31 +++++++++ rust/macros/module.rs | 178 +++++++++++++++++++++++++++++++++++++++++++++= +--- 3 files changed, 224 insertions(+), 10 deletions(-) diff --git a/rust/macros/helpers.rs b/rust/macros/helpers.rs index e2602be402c10..365d7eb499c08 100644 --- a/rust/macros/helpers.rs +++ b/rust/macros/helpers.rs @@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter)= -> Option { } } =20 +pub(crate) fn try_sign(it: &mut token_stream::IntoIter) -> Option { + let peek =3D it.clone().next(); + match peek { + Some(TokenTree::Punct(punct)) if punct.as_char() =3D=3D '-' =3D> { + let _ =3D it.next(); + Some(punct.as_char()) + } + _ =3D> None, + } +} + pub(crate) fn try_literal(it: &mut token_stream::IntoIter) -> Option { if let Some(TokenTree::Literal(literal)) =3D it.next() { Some(literal.to_string()) @@ -103,3 +114,17 @@ pub(crate) fn file() -> String { proc_macro::Span::call_site().file() } } + +/// Parse a token stream of the form `expected_name: "value",` and return = the +/// string in the position of "value". +/// +/// # Panics +/// +/// - On parse error. +pub(crate) fn expect_string_field(it: &mut token_stream::IntoIter, expecte= d_name: &str) -> String { + assert_eq!(expect_ident(it), expected_name); + assert_eq!(expect_punct(it), ':'); + let string =3D expect_string(it); + assert_eq!(expect_punct(it), ','); + string +} diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index fa847cf3a9b5f..2fb520dc930af 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -28,6 +28,30 @@ /// The `type` argument should be a type which implements the [`Module`] /// trait. Also accepts various forms of kernel metadata. /// +/// The `params` field describe module parameters. Each entry has the form +/// +/// ```ignore +/// parameter_name: type { +/// default: default_value, +/// description: "Description", +/// } +/// ``` +/// +/// `type` may be one of +/// +/// - [`i8`] +/// - [`u8`] +/// - [`i8`] +/// - [`u8`] +/// - [`i16`] +/// - [`u16`] +/// - [`i32`] +/// - [`u32`] +/// - [`i64`] +/// - [`u64`] +/// - [`isize`] +/// - [`usize`] +/// /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/module= param.h) /// /// [`Module`]: ../kernel/trait.Module.html @@ -44,6 +68,12 @@ /// description: "My very own kernel module!", /// license: "GPL", /// alias: ["alternate_module_name"], +/// params: { +/// my_parameter: i64 { +/// default: 1, +/// description: "This parameter has a default of 1", +/// }, +/// }, /// } /// /// struct MyModule(i32); @@ -52,6 +82,7 @@ /// fn init(_module: &'static ThisModule) -> Result { /// let foo: i32 =3D 42; /// pr_info!("I contain: {}\n", foo); +/// pr_info!("i32 param is: {}\n", module_parameters::my_paramete= r.read()); /// Ok(Self(foo)) /// } /// } diff --git a/rust/macros/module.rs b/rust/macros/module.rs index 1a867a1e787ed..c1400597774a5 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -26,6 +26,7 @@ struct ModInfoBuilder<'a> { module: &'a str, counter: usize, buffer: String, + param_buffer: String, } =20 impl<'a> ModInfoBuilder<'a> { @@ -34,10 +35,11 @@ fn new(module: &'a str) -> Self { module, counter: 0, buffer: String::new(), + param_buffer: String::new(), } } =20 - fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { + fn emit_base(&mut self, field: &str, content: &str, builtin: bool, par= am: bool) { let string =3D if builtin { // Built-in modules prefix their modinfo strings by `module.`. format!( @@ -51,8 +53,14 @@ fn emit_base(&mut self, field: &str, content: &str, buil= tin: bool) { format!("{field}=3D{content}\0") }; =20 + let buffer =3D if param { + &mut self.param_buffer + } else { + &mut self.buffer + }; + write!( - &mut self.buffer, + buffer, " {cfg} #[doc(hidden)] @@ -75,20 +83,119 @@ fn emit_base(&mut self, field: &str, content: &str, bu= iltin: bool) { self.counter +=3D 1; } =20 - fn emit_only_builtin(&mut self, field: &str, content: &str) { - self.emit_base(field, content, true) + fn emit_only_builtin(&mut self, field: &str, content: &str, param: boo= l) { + self.emit_base(field, content, true, param) } =20 - fn emit_only_loadable(&mut self, field: &str, content: &str) { - self.emit_base(field, content, false) + fn emit_only_loadable(&mut self, field: &str, content: &str, param: bo= ol) { + self.emit_base(field, content, false, param) } =20 fn emit(&mut self, field: &str, content: &str) { - self.emit_only_builtin(field, content); - self.emit_only_loadable(field, content); + self.emit_internal(field, content, false); + } + + fn emit_internal(&mut self, field: &str, content: &str, param: bool) { + self.emit_only_builtin(field, content, param); + self.emit_only_loadable(field, content, param); + } + + fn emit_param(&mut self, field: &str, param: &str, content: &str) { + let content =3D format!("{param}:{content}", param =3D param, cont= ent =3D content); + self.emit_internal(field, &content, true); + } + + fn emit_params(&mut self, info: &ModuleInfo) { + let Some(params) =3D &info.params else { + return; + }; + + for param in params { + let ops =3D param_ops_path(¶m.ptype); + + // Note: The spelling of these fields is dictated by the user = space + // tool `modinfo`. + self.emit_param("parmtype", ¶m.name, ¶m.ptype); + self.emit_param("parm", ¶m.name, ¶m.description); + + write!( + self.param_buffer, + " + pub(crate) static {param_name}: + ::kernel::module_param::ModuleParamAccess<{param_type}= > =3D + ::kernel::module_param::ModuleParamAccess::new({pa= ram_default}); + + const _: () =3D {{ + #[link_section =3D \"__param\"] + #[used] + static __{module_name}_{param_name}_struct: + ::kernel::module_param::KernelParam =3D + ::kernel::module_param::KernelParam::new( + ::kernel::bindings::kernel_param {{ + name: if ::core::cfg!(MODULE) {{ + ::kernel::c_str!(\"{param_name}\").as_= bytes_with_nul() + }} else {{ + ::kernel::c_str!(\"{module_name}.{para= m_name}\") + .as_bytes_with_nul() + }}.as_ptr(), + // SAFETY: `__this_module` is constructed = by the kernel at load + // time and will not be freed until the mo= dule is unloaded. + #[cfg(MODULE)] + mod_: unsafe {{ + core::ptr::from_ref(&::kernel::binding= s::__this_module) + .cast_mut() + }}, + #[cfg(not(MODULE))] + mod_: ::core::ptr::null_mut(), + ops: core::ptr::from_ref(&{ops}), + perm: 0, // Will not appear in sysfs + level: -1, + flags: 0, + __bindgen_anon_1: ::kernel::bindings::kern= el_param__bindgen_ty_1 {{ + arg: {param_name}.as_void_ptr() + }}, + }} + ); + }}; + ", + module_name =3D info.name, + param_type =3D param.ptype, + param_default =3D param.default, + param_name =3D param.name, + ops =3D ops, + ) + .unwrap(); + } + } +} + +fn param_ops_path(param_type: &str) -> &'static str { + match param_type { + "i8" =3D> "::kernel::module_param::PARAM_OPS_I8", + "u8" =3D> "::kernel::module_param::PARAM_OPS_U8", + "i16" =3D> "::kernel::module_param::PARAM_OPS_I16", + "u16" =3D> "::kernel::module_param::PARAM_OPS_U16", + "i32" =3D> "::kernel::module_param::PARAM_OPS_I32", + "u32" =3D> "::kernel::module_param::PARAM_OPS_U32", + "i64" =3D> "::kernel::module_param::PARAM_OPS_I64", + "u64" =3D> "::kernel::module_param::PARAM_OPS_U64", + "isize" =3D> "::kernel::module_param::PARAM_OPS_ISIZE", + "usize" =3D> "::kernel::module_param::PARAM_OPS_USIZE", + t =3D> panic!("Unsupported parameter type {}", t), } } =20 +fn expect_param_default(param_it: &mut token_stream::IntoIter) -> String { + assert_eq!(expect_ident(param_it), "default"); + assert_eq!(expect_punct(param_it), ':'); + let sign =3D try_sign(param_it); + let default =3D try_literal(param_it).expect("Expected default param v= alue"); + assert_eq!(expect_punct(param_it), ','); + let mut value =3D sign.map(String::from).unwrap_or_default(); + value.push_str(&default); + value +} + #[derive(Debug, Default)] struct ModuleInfo { type_: String, @@ -99,6 +206,50 @@ struct ModuleInfo { description: Option, alias: Option>, firmware: Option>, + params: Option>, +} + +#[derive(Debug)] +struct Parameter { + name: String, + ptype: String, + default: String, + description: String, +} + +fn expect_params(it: &mut token_stream::IntoIter) -> Vec { + let params =3D expect_group(it); + assert_eq!(params.delimiter(), Delimiter::Brace); + let mut it =3D params.stream().into_iter(); + let mut parsed =3D Vec::new(); + + loop { + let param_name =3D match it.next() { + Some(TokenTree::Ident(ident)) =3D> ident.to_string(), + Some(_) =3D> panic!("Expected Ident or end"), + None =3D> break, + }; + + assert_eq!(expect_punct(&mut it), ':'); + let param_type =3D expect_ident(&mut it); + let group =3D expect_group(&mut it); + assert_eq!(group.delimiter(), Delimiter::Brace); + assert_eq!(expect_punct(&mut it), ','); + + let mut param_it =3D group.stream().into_iter(); + let param_default =3D expect_param_default(&mut param_it); + let param_description =3D expect_string_field(&mut param_it, "desc= ription"); + expect_end(&mut param_it); + + parsed.push(Parameter { + name: param_name, + ptype: param_type, + default: param_default, + description: param_description, + }) + } + + parsed } =20 impl ModuleInfo { @@ -114,6 +265,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "license", "alias", "firmware", + "params", ]; const REQUIRED_KEYS: &[&str] =3D &["type", "name", "license"]; let mut seen_keys =3D Vec::new(); @@ -140,6 +292,7 @@ fn parse(it: &mut token_stream::IntoIter) -> Self { "license" =3D> info.license =3D expect_string_ascii(it), "alias" =3D> info.alias =3D Some(expect_string_array(it)), "firmware" =3D> info.firmware =3D Some(expect_string_array= (it)), + "params" =3D> info.params =3D Some(expect_params(it)), _ =3D> panic!("Unknown key \"{key}\". Valid keys are: {EXP= ECTED_KEYS:?}."), } =20 @@ -205,7 +358,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { // Built-in modules also export the `file` modinfo string. let file =3D std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE= environmental variable"); - modinfo.emit_only_builtin("file", &file); + modinfo.emit_only_builtin("file", &file, false); + + modinfo.emit_params(&info); =20 format!( " @@ -369,15 +524,18 @@ unsafe fn __exit() {{ __MOD.assume_init_drop(); }} }} - {modinfo} }} }} + mod module_parameters {{ + {params} + }} ", type_ =3D info.type_, name =3D info.name, ident =3D ident, modinfo =3D modinfo.buffer, + params =3D modinfo.param_buffer, initcall_section =3D ".initcall6.init" ) .parse() --=20 2.47.2 From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8C01E2343C7; Wed, 9 Jul 2025 17:53:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083622; cv=none; b=LVlKx29jf0QtYXdENL9Nmbj8KGDmxjeD7AuJBUIaOpPQHcSnIvqI7KYTLc9Yths+KD7Wg/6ZHo6FmRBaX8MMVFhwXCAEujJJyy/hDneYsSHlQisi8YpbkE/l4Ea/Ji1+/xGHMBGRwznIa7VWRNSibnLFcort5yw0fsUvsdtCjhg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083622; c=relaxed/simple; bh=4Rj9VzFcMjV2b2FKGGXgH+pSxDEnRIoZbc9nYVS6Nl0=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=YjD7vDTa8zDi3C49rsUx3WJouufOlpngwSsKxzqX42LBGBN85jS+i04t6eD6f4iyVieX7c4fNhvnMtUIv3q4XWxG+bMQPDYhlX1QRz/dWJydv1k2/lTpbZBWFYL5QKoJnJQPVkzuhCoOU22Qox0ZRDHSvBOl76P6XPSuj3RxbXA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=mq4ARsVn; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="mq4ARsVn" Received: by smtp.kernel.org (Postfix) with ESMTPSA id DB4FFC4CEF0; Wed, 9 Jul 2025 17:53:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083622; bh=4Rj9VzFcMjV2b2FKGGXgH+pSxDEnRIoZbc9nYVS6Nl0=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=mq4ARsVnKCc4ZTvmu6DgC1jdknoJqJmnMQuFWrcBEj8L9zCK6Lrreo8Jf0HrmFh8N VPCNozWMBR36KBo6+LeFz4rrOltl+PAAKo8PqwY5JULy+j0bPGu4HYPdepztOzacPf NrG9sEC5MLhhBkEaGSAwP8n7WRB/LmndSYF9wTTSCFZZmhToebp5ypCgs37RztDd4O iPzxRg3GatC0YgCHwtpwktiTz8oLg3/p/yve2bseYPBmiElwGaN5oJB1hCB338xD/7 GgcFzVkDP0JmDFlh3yzrgqpQGXiCXNhPAZU+GdKUcVrzJSDn7v8+DBg/qfjGndEJG0 lidilXLpoPXNQ== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:20 +0200 Subject: [PATCH v16 6/7] rust: samples: add a module parameter to the rust_minimal sample Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-6-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=1268; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=4Rj9VzFcMjV2b2FKGGXgH+pSxDEnRIoZbc9nYVS6Nl0=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxeKwvg9OxdRiD78ZWUFs4K0qRoKrC9WULjZ GgzlqjrEp+JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sXgAKCRDhuBo+eShj dyEHD/oDwHl342wS3vJSfmkcJ8x7dmzi66aQHpRZ66n3S1suxUPTLjkqaemVpUdMCF2VjaQtH7g 53Y0DrLT9+gy16qXnzFx4A/XSBVkZgUaeRtrvxhr49/NhU9/UhMGVwSOAdvxul/fRM52RJevCA3 5Hh2XcmfzvewlgnRneLUiHqAqxtsNRPbyVvbix0L6l957nrZvT0jc1Tfgg/7uyJ+UwhZ4ThIZru yWbm9m4vY/kEV2fa788npb9QVFAsanCGfp4+cnKSWJU8RT5tuKLK2IKqiz7NykEinLM+54mXSYT CgCqddGWk5DBXzvojCRV00EZIR0J9zhHCCIt3Ut7w8z3FS0MTY64fUDjZ+PNas8YI5P2EXz7YR/ Goj7KDHWYnKzEdW4jILPS9JfX29VwZ/7yH89Wr1Z76qedt6Z56DqpAoeWVALcB2TYleXg493FR3 ABcK9MMuB5XUEhosHcbMP8A3P0K1InGGe7ULvn0+mUklGb5lpl2YPu/8FKdk+OaN+3iF19Ei3qR s1CgOyp9YSx9nXbLSPcVBUXX4yhLvSd770pZy872zPKZ4sxoMhKurwBIJVuNS+tDJAswG/uWKvO G+30ZwDTTrEDAvk+5ImvVAod4IAyH+xIZ6K1ccfSIFVwaBqs7Q+3ZxYsTLsvw7BSDmChG/4WeGO 7kS8ZxnrIjHCBkQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Showcase the rust module parameter support by adding a module parameter to the `rust_minimal` sample. Reviewed-by: Benno Lossin Signed-off-by: Andreas Hindborg --- samples/rust/rust_minimal.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 1fc7a1be6b6d7..8eb9583571d72 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -10,6 +10,12 @@ authors: ["Rust for Linux Contributors"], description: "Rust minimal sample", license: "GPL", + params: { + test_parameter: i64 { + default: 1, + description: "This parameter has a default of 1", + }, + }, } =20 struct RustMinimal { @@ -20,6 +26,10 @@ impl kernel::Module for RustMinimal { fn init(_module: &'static ThisModule) -> Result { pr_info!("Rust minimal sample (init)\n"); pr_info!("Am I built-in? {}\n", !cfg!(MODULE)); + pr_info!( + "test_parameter: {}\n", + *module_parameters::test_parameter.value() + ); =20 let mut numbers =3D KVec::new(); numbers.push(72, GFP_KERNEL)?; --=20 2.47.2 From nobody Tue Oct 7 12:28:21 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B789F2356CB; Wed, 9 Jul 2025 17:53:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083598; cv=none; b=AUzrLCCBRLeiis9JHvJWsjlS8TQQqiO45YggHSMtyM5W2ASJJDgS92eSJuq1NBERrlF+jmkg1gM8jBI5ydruKgLU5CeaRFiLEyY3Mbf+bVl2qW4UL90O9hsQD5JLMjcBrWsR+ndcw6sMhT37YA12SwXSeQbO62mvswXACFCMV/g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752083598; c=relaxed/simple; bh=rC87q+cE6l79VfDDaP1rreH6c58LNoR3ApaI6m+XCGI=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=BieRlwuRZdKVkUDVQhLc+fcwoi8/n8XnnWaXfpSloV7ab3vtQf/TGrt/aJsg64eCjWJLU5ENNgSeluCTpVbcxIqMo6gF8aqkBAItRSq/6eksIa4UC9N4FgmY1epxQur0F8vYtj6rjCsajY2hRK3tiYauUAGnlyeMXOjqM7wikW0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=ehp0Ao9g; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="ehp0Ao9g" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DD13C4CEF8; Wed, 9 Jul 2025 17:53:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752083597; bh=rC87q+cE6l79VfDDaP1rreH6c58LNoR3ApaI6m+XCGI=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=ehp0Ao9gieyI+p6wXWhfYxKe3IuEX+eLG/ledHEVePjgN6Wwk8oksJXz7aJGqOR1+ MDr3h1bB8C9vYaULTMrUXGZrXy8FesVOLrvYpaSlSB3QDmTSqmsifjmqvRYR06UzKa 3Gh+V+/CS/IrBoVJfvOl8zeD+nJEhOdaXnMYDwODh+enxixGmukJKmMtEilpkoS8ig s1ElEqPO1PPE68xnCty7DigF4CXOGSy2m89AFRB5ic1MWKEWV3EhV0oC2MQ0Iwowyv QejJZQxfCKbyr13rmncyvOtJaEMJ8EtKvXlarT1AXbY1kD63HHrYVTaUgucD0M9GqA StuiMg6cVo6fg== From: Andreas Hindborg Date: Wed, 09 Jul 2025 19:52:21 +0200 Subject: [PATCH v16 7/7] modules: add rust modules files to MAINTAINERS Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250709-module-params-v3-v16-7-4f926bcccb50@kernel.org> References: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> In-Reply-To: <20250709-module-params-v3-v16-0-4f926bcccb50@kernel.org> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Alice Ryhl , Masahiro Yamada , Nathan Chancellor , Luis Chamberlain , Danilo Krummrich , Benno Lossin , Benno Lossin , Nicolas Schier Cc: Trevor Gross , Adam Bratschi-Kaye , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, Petr Pavlu , Sami Tolvanen , Daniel Gomez , Simona Vetter , Greg KH , Fiona Behrens , Daniel Almeida , linux-modules@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=810; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=rC87q+cE6l79VfDDaP1rreH6c58LNoR3ApaI6m+XCGI=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBobqxescsuQG7XGmqvzjOrq6qdItJE/OpG3PjV5 lCv3GctpzCJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaG6sXgAKCRDhuBo+eShj dznEEADFwbo5Hvcp7KUzr2hE1ebnvnKnreDa6tt++6zehg4ZxwnraAWS3jYLIa2LgUtw1N0DSBR PgGmWSvIL3zL0ZzUZT5cer8MZBU607zdR4HReZbemhzfHtJBNkOH3aaFsrNW28kYSu6+0bYtXkV hmWkxNiM76TDakUwPU7jAlnnOUiT7gpH3rNu5YwnfjRhl2n+ftrpJzNeGqZNqhXfeJlK6LHg6NK 5PQlLLGQjLaStAG2/UYB1vqlkn7VzO9iHe2RIlZnADwwouT45TdKAVSB0HSL2SfqQi+tD661A60 bB7Jo5ksUBm6SMxGGtrukrAgMg7Ll7JghwomLBfiTHEsXxBG1dUOjJbJeYpTpsDAcxX+6zeFism 8M+0JDbOy7147HcSwiFWY2Hi+aGg5UMwWM4+ne8iR7z+9ZlAXbq/q+Gp5CY0wJeJ1MwQGNaSZmq 2t9zEIEG55k4Cou8bz3Fa5IqH7/WeY3XPnNJoRDJRGuZ+PebITdaXrqpDLbet1oARoTWl0VKiev t8HH7RMBUKGZ6ka31GEV+yRLiCMOe+0zCiAqgfvsiQlp/1BYqYQ8oTTDOWgKvtfphX/oU8VyZuj SpvRuQh0Y5S05PpxkCtYeDYTTb0wIFa7qMhpxpA2jDR76aEcnSQFpddj6s9ZS6Q9X2aIfqRl8Hy 7O4SZTScX68ZJCQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 The module subsystem people agreed to maintain rust support for modules [1]. Thus, add entries for relevant files to modules entry in MAINTAINERS. Link: https://lore.kernel.org/all/0d9e596a-5316-4e00-862b-fd77552ae4b5@suse= .com/ [1] Acked-by: Daniel Gomez Signed-off-by: Andreas Hindborg --- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index d431320ed3b2a..afa385ecc5c4c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -16835,6 +16835,8 @@ F: include/linux/module*.h F: kernel/module/ F: lib/test_kmod.c F: lib/tests/module/ +F: rust/kernel/module_param.rs +F: rust/macros/module.rs F: scripts/module* F: tools/testing/selftests/kmod/ F: tools/testing/selftests/module/ --=20 2.47.2