From nobody Tue Oct 7 08:52:32 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 385A81DED57; Fri, 11 Jul 2025 06:37:07 +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=1752215828; cv=none; b=YZv4jSt7Pd7bbdKeXfabDT4iEXbQFy9VHGCQI1kKYy0DAotpENaGWoo9aSAiD86QzMNb4cZZ3T137fM7e3D8PX8Dm8k1E9A1ItNgbpe96V9ztW1C+gfF9YKthRV2F2pJswYMF2umUUuPREMSZla0RbFl0oxVpRLcAQcvjlurUt0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215828; c=relaxed/simple; bh=3Z10rATub/nmoS28YjcVnjle0PnnDL4yejK+SVcFUi4=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=cDO4SUOUhWNFF3sqoSKQnc6LfWT7Fllr2atxNmlFTdnVW8FUu4un5giYX3MQ7lF/lnGwkdzY3oWmA3w9BcjY3kOENcQcqoWQvQGlrD6XptXUOgTyGtAA7uhR0YI2IzitX+tSdp7FtarkKYs296JUA3O48IoUaFDO/VjJmtG79kY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=XXnHay2l; 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="XXnHay2l" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 590FCC4CEED; Fri, 11 Jul 2025 06:37:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215827; bh=3Z10rATub/nmoS28YjcVnjle0PnnDL4yejK+SVcFUi4=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=XXnHay2lhglrp6BFbGiL6tOONKf1MIsv+83sXzGzqoi29wkzJB6rkH4BPUYcYGLpx Hc4Ugc91vZzUzqtBLq407TjsGspqPgVB6ZIE7MxOEX1SdM2W/V3zBydwiUFCoA1fck 5g7CIb7++4B1eCJZBPLgOp+52/HUNYrWdFOYjKWr7Znfne92q8FzeYURxwm5VcyxgI 1k81DuLKOBn0CopBkELXpM/L67QH8QFv0hHqBN3esJwHZJ56y3ApiIkx6OyDZc6pMt iz9OXme8SskFjLyd46xTvIb4P6xq91tmjR+ZxA9wg0ywgJei4b8tnyxM3CqI6jU7SK owQuRSiJoJPmA== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:43 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-1-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=5498; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=3Z10rATub/nmoS28YjcVnjle0PnnDL4yejK+SVcFUi4=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDV4zgv5/LodT2i6qgI1uaBZn6oyx1mXbwA+ eexWZjaD82JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw1QAKCRDhuBo+eShj dzn4D/9VZiJ0s73aKqos/NqArgIZgETaVh1WS8emNJllgsqcED8UWYiuFd7a8+oEVJPHMcZRosO SEOHda0Jbn5fn/QKX7kiA4UnuafwOgKD053nYt8sa0ECXMuW6Cc+B91q87fEbZ1ghYssKn7Yp7N cMpMznh0uENWP1HknQOAwNBQ3Sk23Ehc0X7iHh2HWn44MT6eIYk0WEee7KQ8YDdtWdvImqwTnHA imEqPiaQL0Z9DoII3PcxVbSsB26WvAKMd1lpUhV/MHqrdVnoBdcdkEt99bCvkY3po6f1EJfl4QA OpllES0JtItydu4zAqsJNoVRB8NjrMvsvsjWx3XpjYWQlMLxuuy1Tqjk7M48DvCr1M3GV6SJp6I COqmIe0J4XO5XGX+gBfYlNhjt3XYf7NHSqsjM71JRRPA5MoOZ6YjPkG51v2VUM7WL+4mh5cK3NS KFjmnWVM/9APFaANKMbqAz434u60Psiq5WAZW5P4JuPMYrzYgwCux2a/tRaC/CHC2QywgzWeugK fco5Yt72b3mua25v3mVeyE8V7b9Ps9vRRMxM7cUlW0lb/ZZvCx4O5oAocDyctk/opKCzHspPlSk Jbk4S6xFhOZgUm891uyTLifnW+QCZUPQ1dkmEr4W8QcFWPFQOOx1eW6BYvX+kkBwA0u+6EBS+xV Rm/P2T3OSJ9aZEA== 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 Reviewed-by: Benno Lossin Signed-off-by: Andreas Hindborg --- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 127 insertions(+) diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index 81e3a806e57e..13e6bc7fa87a 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 000000000000..bdba601807d8 --- /dev/null +++ b/rust/kernel/sync/set_once.rs @@ -0,0 +1,125 @@ +// 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}; + +/// 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 `value` is uninitialized. +/// - `init =3D=3D 1` if and only if there is exactly one thread with excl= usive +/// access to `self.value`. +/// - `init =3D=3D 2` if and only if `value` is initialized 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` + // is initialized and valid for shared access. + 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 `self.= value`. + 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 `self.value` and it i= s 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 { + let value =3D self.value.get_mut(); + // 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 { value.assume_init_drop() }; + } + } +} --=20 2.47.2 From nobody Tue Oct 7 08:52:32 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 2D0941E3775; Fri, 11 Jul 2025 06:36:37 +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=1752215798; cv=none; b=AXW5m6dSvsInH4aRF1xX49gWQWSATFnyDvnn7f/8Vkjxh3hfetOJtztXjWrqGpnzF1utxQp1DEzooUdnkG1yExRkd38Qxx3MwNt95jKwj4VH1IA/20O8oRsWHY4T06UlI1lJJyxkQ0Npg/zJhXh3qQve1xB+qcmdIbFYxmeMX/I= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215798; c=relaxed/simple; bh=2/ANc9BU+Hx5oFEmj6yR/AmSIMnSY5f2zxLXAZPt+BQ=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=O/TFOu7qF0YeXCW/P9AvUwgyQrNbTsNVEwhVcRL/cu4Z8lQL2tODcr7+8NNDLp2g7/Jbltu6cZireyQcdicua/NqZV9pE1hAcUnTPo6nQp2+/E0rGijzSk3UimKF0H1muUa88ragoI5+zWxKux2iPPq1Fjua41ElJxC2VhrM1LI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=UNEt0ai7; 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="UNEt0ai7" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 68D6CC4CEF5; Fri, 11 Jul 2025 06:36:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215797; bh=2/ANc9BU+Hx5oFEmj6yR/AmSIMnSY5f2zxLXAZPt+BQ=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=UNEt0ai7CWl7vt0UUvy/R3VzFjs6ATOg1lBXf6pmiR3aphSoqAXDu30KQ476+HlmB sWrqs9PIKI81BKD28hS520KceamlJ/p8bM1LZn4nBuZMPMr/20Ubu0WRqxmWOej6yW vFnJJFD2xEWhLSvIW9wA3unz3FHsAKQRqX8SjMuEdWPL+uHnWSVaDzCP44vSbEJn2d IWRUrqQTCGy3fRDWYZfYlGPE7D4MNYmJyrKyHjUxvrwwFi6Ln9SSUf6fB7l0GIas8L 63qIAs8HVSHF+onlNzFuX0iG7AA7tYHadvFOfOsOonnDNlC2oOm/Tx3v8Nirj4tb6/ bVsmLYu+NrlSQ== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:44 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-2-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=7200; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=2/ANc9BU+Hx5oFEmj6yR/AmSIMnSY5f2zxLXAZPt+BQ=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDWgTexbizkQ2nNpFHAnQzlSmxojyUwa/JRR xGpkj/3g96JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw1gAKCRDhuBo+eShj d5ikEACkP8Msj/GRC9QKEh4TKK/rtos/5incDVse1LS6qgPJFg1qptEWYdL9ULNjySTBq4fLYnm W3XhBrx9fjQlnF5yuQBO6pTf1FJJ8Lz/9+A9YPvu4Sw3nQCaSVG2Wx0Wxw/DSzSvl/KwWd7N1Rd jVNuf+4mLlIEePGhwh/FxKhPrrPyuuOs+P2c1oK4Qd13K/1qtvzh2Adp+Hw08WLif+9lsJTtsOg S65UdJc973ZMv9BThWhoL5gnUnhJvQ2LhWk0PztmOn8s5rf0QIO3VSllNe8dJTdhIwICJfN1o0w kWQ0RpP+TCdeU7uTImILdEOI1J2avK3HZKO8iLYxoWfB/U/WDJVv5WTh6CqB/ts1rc3R99DW5bD HxbGqWvzTlshT+7hTgv5jn4cTduFoFq+/m3MwV6+mYeohOft8FLYqeYqwE7FtQU9GvPkjCCMS6S pka75090y0NLw+fOZyHZmWBoF/wbw1Yh/+LTqC81BewYP8NBNn6aG9p0rukyfbotJID371a0Pe2 s54VRUyC92kw6B5Mx3L7y8gW7imY5TUHerSCWsDAZrol0lv806Bgt0joCoPWc0iLLLaruRnBCes wWUQlmUtQS042T4lFuxpmLjvM7BbCxR/HcMrG51p38zmaQqb1O9FJaVu8KbJZel5JPXCUq2wa6N ZnnYlv5sr/HTP1g== 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 a927db8e079c..2b6c8b4a0ae4 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 000000000000..48eb4c202984 --- /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 08:52:32 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 1EDA01E2848; Fri, 11 Jul 2025 06:37:00 +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=1752215821; cv=none; b=jnBjryWRLvHE2xPreSvmc2PB5Hdq0hGyKDudFKV54TAfTrJ7v9k490qPCRfkqRSW5I2QVcIKX6Z+3fz4sA4fSv8nHGN5kWmV3p66XbR5m0nqcc5aYEqAXmLMTl3EcpDpGwpBojlqUG6ds3PNlRrpy3dmAn3x2ecmBAQ60s+GAWw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215821; c=relaxed/simple; bh=TlAjPotz8Sb0FWgUhcPvYx426jVyn0WEt+3nHsg7uUk=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=EYsf8vQ51s1YR1j9eKTMgMzLQXzxhHnsGAGY/bL5Lm44dKIC+FO1i1gJ6hrTfuWqFtV4cqblEp1rvoyZ+d1SRtzFfqc56UOvQEELQqGVIuTPjdFt3XmBudkwZJr0GOPq3KCqWyRCBowqxihQFxDX0nEqbmWtinviJnMGujzZKsA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=M5j80dnn; 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="M5j80dnn" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 79BFFC4CEEF; Fri, 11 Jul 2025 06:36:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215820; bh=TlAjPotz8Sb0FWgUhcPvYx426jVyn0WEt+3nHsg7uUk=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=M5j80dnnsIntjguqTn2B29pIbkAAgxa4JsiuV95kZLKoLZfeR5YqiQ7fSNgSnLfj3 J5zqS3hBrbWdkyJl0MZw+0hoYemMjE3UQvBc2kUlrtpnH3I+ljfke5NDAlgn3w0U6n RQlc2x88L2lotIVm/72M8AmSrUJSsEZNceKuSRqskBKKNPaXBIJmUA+1AsK6mv/tv+ xPxWcLaRzf0elsTp88TpaKuDx9zAVAy12rHiNelHFyFD8r+9ll+P1IM8XM+eW6P3vq SUG6mGJRKeTH38cYet+n06+G84+9w3Rf5alClV/k2KdxbVlDIbiZDxw08lb2YmZJFC T02oxpM2ySiAg== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:45 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-3-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=6941; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=TlAjPotz8Sb0FWgUhcPvYx426jVyn0WEt+3nHsg7uUk=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDW1oiqVCpXRZzKrgCvQa74TQwEEtPNtZPUN 4B2u+hLg4SJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw1gAKCRDhuBo+eShj d0vKD/4ycM9mSBe341k1ph0lB+O4Tag8z1hNjwSzr+UBMJmPoYHEW4lnRzZ3Eo14W3sP0ji9fzG MG9fG/Futz2dQNo7U9iSsTg3rtzIljbjoFBceluFfuEvCrmctdWFCFOIO6Pj0d6VuTysEqLdTlJ +8zL/J7wqujktxcZzlqeZJrFY/0SZTPMJ23paddyXPBpVbGByj/43vLVUZBK32VXZv6Xhzk1db4 4pj+qx6PtkSYdslt5rPXVqNlMZo+a5Vz2sBlnpAtdb5+ths7hd6PamlbBGNVQApCHNX/VDkNrqK q99U9HngV4SDkYfVBHisnNQSVQxZ7FjRqQbVGizHRiqOVsK8aveuWGZ4uRskutjPen29FXeS/Xw R2pwp7NlszbFuvxi3uA+q8IsF5XKrPRim60F8IlTL6QHCWv7MulAct1DS6zMZivSAymdN6eG82M wMDJNT+d6ASs8iyOh0QKCWFWyeYGYSKv3G0D2nN5Mz/Ew2H3wq3YXodMPNd3i9PFpAGWcrfQF+7 zDCciQYs1b6iwCJEbx9WpAf3U3EuyXqj0wy6PMmBr1XoLDcM7BOU/sY8ZO8GvdZaTuLfIRTxKaE ebs0jK1Yl8l8hUxagcHdcETDTzv8fzIQlZdjdTCC/NFledWEfUVKElA83YDKCBPbeUrJkfv5Rq9 0n2/c+IxHsru13g== 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 6b4774b2b1c3..2b439ea06185 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 000000000000..9b187ed1d351 --- /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 08:52:32 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 011E51F03D7; Fri, 11 Jul 2025 06:37:14 +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=1752215835; cv=none; b=M1jGrJA6SwXXDqKGn+yeXb7T89YWQH2tyq+S0esapVaabVLcy/PywaQ7EX1IYlvP9PWzVITBzOOqHu94kOONc+zp7m82SnFFSN2utnNSHJCP+ogtdLsUOSW2W8pBp8z8gXmwSZi83A3+AliBXLWC338blWlYZ0mc+i8rrfrgoh4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215835; c=relaxed/simple; bh=6Qq3JEPyfCyEUyFmISVDX2MQupJGcEbRE4c1O1T+mok=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=PEkSddzQDwG8prTnqg94+jk5/3TFi142nqEoNqQtqqjuZoaBiMr4mE+tY3PGBKsn/YmAPsinHJFpFWnYNvI2MBIzTNzyh/5sPZB1QP0k2WDar25TwPBGGjDGUe4iVJGz6hJBoWkd2SAeVyRjgEBmfq8QSUb5DFrAc7/qcV9IwWg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=j7XVrsgu; 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="j7XVrsgu" Received: by smtp.kernel.org (Postfix) with ESMTPSA id AE872C4CEED; Fri, 11 Jul 2025 06:37:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215834; bh=6Qq3JEPyfCyEUyFmISVDX2MQupJGcEbRE4c1O1T+mok=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=j7XVrsguwepmw8ZjfASZccTjN6QZkNUIznz3wLK9S/8jEI+UNrFG0r874OCRZRUbS 2Dy8HCnoTc4IgsI7lbvndC8vBd1Evkm2ANMMYU2tSL4OkTFy0GVAvb3P0p/pIUrS63 j2a990ngwqXsp9PIc0UnWdH2GKhS2B1F4cKiu1ns+0svwYbYZOfeY3Dsod7XCLHp4u kwqFo/l+1kaaZp88rlny6gyysN9PY8mMq5xa+UA897gl/rV/ejBjdi9vkbfFr/04ip L78cGG0+sxpg7opQi3NpifgNg+8mt9BgRJ8Q7RPHnBntsRsaNG34u0+8JWzIQvOPy5 XUfOn9KpOaUww== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:46 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-4-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=2063; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=6Qq3JEPyfCyEUyFmISVDX2MQupJGcEbRE4c1O1T+mok=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDXTwiKgisxAT1UbAUOHYJRwdFdGswVZLInN PH6b2B5QW2JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw1wAKCRDhuBo+eShj d+AkD/9MBoT2PmyzLR/lq2CJYH+uXNw3liZLoSpKh1/Wgz3PSYbnyvn67EFFkaqYOihsmhpuL0d BzNvvHIAksNrDWvn73MuabTRpvI1yn7/O4Fc6E4mZdWIIxvFLqJCfzWfrDI6/hXeQ8y6pcSuLOg s1UKKYu1MNHMPhBOvC7i9disi4AST34uKSrFFEfgKAut6b0ZJbYkb2NFRpsIoaQ3T1OZX2J6uFh CMqVAozelLfna40h3YMC8Zenjhb+hmL1JfOXTKUn/xPuWJCa+JlAGwGtCbkwrWvkP70iAmPAcAO f3YTDQ5cOqD8JGVOWQT8pXZxv2/tZ7PXhaGNdP0HEINoM6Dq9WEYSxIHUrBb7gHk51ZXM4wbMA3 2ZaI5NFp7uQ9TfSBhCwRoit4xWGDEbsN+YuRYpwD9Cbgt2aM6jQdJy2TzrjOm5L6iYRty+FxnL2 cWCtdOuO2W8MI1QmihBSY7H0Ibn3q0OKPOEv3U9EoM7zlffnRzJgRRNBY68TrFn/t5IY+HoLp0A uJZLyNssXpT5cKoXCTh3ZOH4FwdQTXDTIPrMLD20bICVCz8L7aGScliWeP9ub/7zgJqXMudtCtd NYYrJiPIq9sLUPediDkALiQzFozsMmAT7w4erisv2TJ18OiRZDgB3KxmNTHDq/o/+xzNoUiPkHX mduuJWeA59+Ex6w== 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 2ddd2eeb2852..1a867a1e787e 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 08:52:32 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 0F2AF1E1A3F; Fri, 11 Jul 2025 06:36:31 +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=1752215792; cv=none; b=T1TWwDpx8VJHkiM8teUNHxVolk7z4rQl0B8KfT5QwkpahtiWaHssYGfoDhflB6u+TRfSM+aGL9JmNdly4oEbx0xlCTcz5Tl+XI6ytmlJVRN5tzEwva3Mg6JiBQtRObK021A/uYp/M0/V8A3TYY1Sk4Ss3yjf3OTcWIxoI2ZL12w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215792; c=relaxed/simple; bh=LxaN+hjdvCM/xzwPbqcEZTawPEEcX1egLOWAX0aeGs0=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=JmkiXmdn0vOSq0KgynVv7SX7tPzb/U4OfP6LCiBBNHZJyqyJm2MmxexPFZOrl8/BNcyvNgPnuPesYbCynV4a5Cj1UKsCEw59Uhj/43VRAdEIIhn1NF0xU2a3JLcpN6UX9PoNYUwKigWqMDEQ/MtLpjdJjTJ6fYc70YjQ9MGxM/4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=F4BHw6ju; 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="F4BHw6ju" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9409FC4CEED; Fri, 11 Jul 2025 06:36:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215791; bh=LxaN+hjdvCM/xzwPbqcEZTawPEEcX1egLOWAX0aeGs0=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=F4BHw6ju3xjy1dv13yR/vpiy9autuYFzGDkOGRA/WRRwsOAM/dgCi9YD2s80sn4N8 jww1QIhQ0JVtotto5cmzKe1h8/i8YFG3LonljnLojB98HT99PSFmkgNC8OFaceo9TE IgvumT24RlALSfqFrCLoyKFmfwmXYUTdeu7eyth0S8m/XewezDS1GewwljV60w556f Vj5v6suLlG5lbY9ADjFHhc7evSXxSUkU4GaBQGEhzTKaJLjpSE/vx93DQL5prT4ugd UeAwSA/iv3Z1xSKHCj21hYvUloaff4cFmVArPIUATDEBPhtsl2IHwZd5i9q6ySFfzc eX08kQz2G0zpA== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:47 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-5-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=13514; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=LxaN+hjdvCM/xzwPbqcEZTawPEEcX1egLOWAX0aeGs0=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDYhVQ3MkyBrsz3W9KbuMwTDRaPOC4AZNH+m W/FGPcscYmJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw2AAKCRDhuBo+eShj d0ufD/sERHkV1JuhsXbOqezjeT/vYMmfHvOeyfXxVLmg0sQfC4fCqXRIXDzSqS31HG6+udumQnv sdm1hCqUPTCkMd1bNTUQs+306P30lWYcdKdWf0pdKBdUmADp6pXyTYIOXQzszyWJOSktsja3WHJ rplL8nTorEuo/45L/tdRQRydeNi0mL6/+2C5Q3KBX1jokTMZ8LNeCYKkGSSIS6klPwcgIHRvV7L sGI1O84zcouj53r825a/15tmnE86CUAO6sE9tlY03hvOPgszHK2QOQ1VXtDwTrfwNpt7dEARb+b Jit4sSbxC1dzBWjWup9PIhhasrzPl3/U9ibcUH/JpC2qv4InwuwrOuL75xyqhYBhUERMWqvrs1j 1FgZtPeMhD5vkDqpX4oEcQb1476m8a6BjCnCVS1mlpFqobNsVQj+vck1uy5rSGNydrnqT9Wh2yM QjfeGQqgESn0bipKq+x/6ekA0LXFjUD2asxr6+Qzk/B1/buyWhG8PqtQOeuYIhzcnPkm1urUtIm bUgw/RY+g0azWW9gDGFxiLfxrIn/zNewhUGEgLCAZ6Q89AVhJDh6Lo5WPQNC8wmapimYSj0MILx 6ze2gHidbqxP/8xwCcEzGPLnBqxp4QoWW8sl03p8REJe+Ti96wYEe3k6KnDzpRXYm1BiOd+TYhh mt19hBjCKTaC9cg== 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 e2602be402c1..365d7eb499c0 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 fa847cf3a9b5..2fb520dc930a 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 1a867a1e787e..c1400597774a 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 08:52:32 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 DFDD51DE4FC; Fri, 11 Jul 2025 06:36:43 +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=1752215804; cv=none; b=MPZn9mcm3Hkerzig0QEj2VPBBcuGpf49+msR/Q8EgCgY9kk1pVTD4gpz4OqXhXlFkpxEzbRRIWg5hk9M1Hxck6FttTVUmVL2eoe1s/QaHly6sCpfnNiZoHp8ilx8RvWO5YTw/YuQhDU6S2egMsS35mi+z0iJJ5dRkXf+HFtRImQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215804; c=relaxed/simple; bh=V3Syysdg1+r38yUWEjRYdLrE6Oqk8+rE/hUE2L4F6lk=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=PhbEYHPdrVoSSB/QHK1XVbfy1JzeV8G/G3qPmduDRy7AwUtN54YwojrZZRgc1vWUG7+eQTDcr3G6TWmYA7MEo7RkEO7Rr+IntOsyZcY14CyNBRfky5n4ChFgLulv+MxilQ9/jbrjyoFaDOi2kFy/lxbV5P9oECWkhRAb5CqDww4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=pCYD6jFY; 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="pCYD6jFY" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4130BC4CEED; Fri, 11 Jul 2025 06:36:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215803; bh=V3Syysdg1+r38yUWEjRYdLrE6Oqk8+rE/hUE2L4F6lk=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=pCYD6jFYQo7VoP12Dho4Y2u6XvVzdRvhtBtB+EN4AjFbORyIFPiIYg4TuyCu22LzP 5ZBZuEjoLJSTbSFm+pDay+5ZNC6mQJeIAjqnNskIIOrhSwH5j2QFPm+cO6/OjqOxRV cGRd+IHxWXEpaq/77y4JBBv31nurRn4000qCGfoWgD/r036sKpsLqWuWlVGkremjJs l+e55IgTv2gkutheH/ktXy3v3FcBQupK/0NdjVaFVda+hwHfwx0dilZ6m0prU3zQUx ytNaNHrR9vM3wqphmhN8ShwPinZMMqCr/1gakFjr6DR/i4EpZ3oort/MD8Qggyz7mS 7R1F01CkMpYdA== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:48 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-6-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=1266; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=V3Syysdg1+r38yUWEjRYdLrE6Oqk8+rE/hUE2L4F6lk=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDZAI0U5EDlUuUeiwl0fVL1i+GcMauDOIlt7 guS6Mx4tBqJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw2QAKCRDhuBo+eShj d+XcD/9duMSjKY3CePRlBL1BTPPAdGifwU8sISRZniAXdGNREpLemAwsoTjdXsfLwkWGavO8jbT NQGC3uTAts7woBNwHkp8yugVw2M8mFA/u/oEcrF8dW1T6tUnHRKPDHWizXlCk5fLNKTnFSTmkpX QuuSJIzBHe8nvjSu9L982aaj7B0xXByMP/dm8zIuYyyXCrDym5cQdyPuMvKBCo6SB0Ycjs8ZUo+ jAcIp2X5dhM+9MDgwS6l66A7y8W3nQ/79x95ZxtyQ+IB1qadKRqxa2PRprMx8736EST3PsTVR7I ajkJV4sVC2iMB9CccZ4Yr8ewH68A91tEngZAnfpJSLDQh5FocWXoo6T66R6aHxF8aFZCHL54f5v jOe3Q/C+lcNUci5l+D09uIOZCecDqhq33+GJpjycwG3uDA9kDvb89octXbEUXZVtvllsd8u69hk 1NK+hDl6f3C+rV12ZCu86nhN7qMJ9BrtVznCkFiBzRHvq+BY9j8rqBA0TbE5Mdkj0uxVMXI35UV eTPnaBc/6siwT+L2Vb26+/3h+1nGvDGPhgSHDeH5Qya3cpD7k8N9kBf/8JYZyZcxHT97htskNf3 IuK3SL7ZhmHu0UVtaaB12Ke/j8l9zkd8yZZtgRYAuQUQtNHpthGt5I4JdC/k/4jH7eWPce+ixFn WPlrDZl9ULpBcXA== 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 1fc7a1be6b6d..8eb9583571d7 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 08:52:32 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 9BFEA1DFD84; Fri, 11 Jul 2025 06:36:49 +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=1752215809; cv=none; b=S2C/1AX4kiQ+AK7WUO1r99QDURrfGdxqoaFnyDpWHez+jeXsq4iuyVvrCJMGyoRKfjNeN+MUtJbTc+w9yjNHUvYAB+nAw2nQjMgYSWZNQci29O6LuTx3pkONAZmL49V30oe2QHVOd4SnKyZPaAC2eRxU7OGdDPmZxmjOrL1QuyY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752215809; c=relaxed/simple; bh=9zt2R482VjqDFpGLu4K8dFNTfKUGK2Pxp+dpiGIf3+c=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=YhHtMrBxX64pBcHMbB1cARSXR5LHbnj1PIQPhVxkXvYq9rTAS5+mtjkf8+mHiLWxhtcqnHUdKPhLStX/X2Rt66hRAwGsSU5wiFtskZRgWeuaCMeUINMeG0eyajL1Z6j5mwSzq0wbsg3CE8IJdf047SQPLKexdmwuWpLHyNZEZIQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=ZGGjAEiu; 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="ZGGjAEiu" Received: by smtp.kernel.org (Postfix) with ESMTPSA id F2FEEC4CEF6; Fri, 11 Jul 2025 06:36:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752215809; bh=9zt2R482VjqDFpGLu4K8dFNTfKUGK2Pxp+dpiGIf3+c=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=ZGGjAEiuyGVQdBfDE9WRHk0kgT+ZbsVdeTQppZGYokLYkph+B8sTpINnHMdRA8O60 yaNPSP2cMpjILtpupYLnyMc/eUbumLjqaSfIA1gLxVFMAI9i6LfnveA7pjIZWCfJIU hHjeWEh8U6x4gU3OjNTy80wfKtaW2RGK57ssqIE3zSs1me8Wu46M/iihFC7o3kkTsz oAdzO8y0e80LgY6B4FmT2HBFm4IKXkgqpjZKb5CsdvaihLd00EhTmEagYjhko/gWwi QqAlXBLjPb5RYi2HvgVCyGjohh3P1zARvsAjqMkpLsTqUnz44iz8DbZGQS1c+/xJiX F6Iz3s80xDygQ== From: Andreas Hindborg Date: Fri, 11 Jul 2025 08:35:49 +0200 Subject: [PATCH v17 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: <20250711-module-params-v3-v17-7-cf9b10d4923d@kernel.org> References: <20250711-module-params-v3-v17-0-cf9b10d4923d@kernel.org> In-Reply-To: <20250711-module-params-v3-v17-0-cf9b10d4923d@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=808; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=9zt2R482VjqDFpGLu4K8dFNTfKUGK2Pxp+dpiGIf3+c=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBocLDa57mfKillk8qBYVlI9D3IUbIcaOFwtpneK D62ptB9ekqJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaHCw2gAKCRDhuBo+eShj dyKAEACmjMn7IrTB4sEkLzRkmPfnnf1u56JklWFL6ZXInd2THjvsCJYxwUsu6VHkPJLmHgwdYLW iVmK/kYmlvaDwCQPlM0oCtQcQuMgg3I7DxmXcdcCBV9E1Qch4cuckXHS6A/NmTMnQB5Xjjefa9O hTT9yIQ5vTPWsWz715i1WXyYTEPjCcjakoKQoqreL6Ot0JSXCdNv5uCK6QFgVvEKT09khGC23qA vKLLOZquoaEORsEkvjlCiVy5B/e6cfMRdKX0kupIGAZvp4AsMjTYrfTerAZlhm9bTb0o2LQQh6T pL1ije7oRyy3adbLCxop8yO1RV9x3sqbLtlFHvOswqKuppnbPrQLPlxL7anbmqVZiCtX0pSAVmR eoXNf/nnV3ZCHGRK5oWj/ISYIpdyyKRntqOhnX5tmRoKMl04ZKSraPROlADMR0ABSYV9hjULfIk J26oDBCWfY0/CkOB//5RI36JObS//hToKmJ9Zyo/KximHkK5UJ60VvX/Mwt+q+EgHOzo2MsuT6J 80VTkrPN+eyRbVxaipPVB2EFhvVyTqDOnYXPXRCE7qoKu4R34zPNFT+BW4wGuVNk3DbeHE0Vo5A rsfqdfJ1S9VWZWk0d5r4jY0bdfvqldSgAVNS4f4KyvFfBDQyMioj04cbg2k2QkxFBlohhb8iGI2 CN1fJjpBNjzACHg== 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 d431320ed3b2..afa385ecc5c4 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