rust: extend `module!` macro with integer parameter support
Subsystems (4)
Andreas Hindborg
reviewerv15 cover rust: extend `module!` macro with integer parameter support
Extend the module! macro with support module parameters. Also add some string to integer parsing functions and updates BStr with a method to strip a string prefix.
Based on code by Adam Bratschi-Kaye lifted from the original rust branch [1].
---
Changes in v15:
- Rebase on v6.16-rc5.
- Dedent code in module macro for better formatting.
- Rename OnceLock to SetOnce.
- Use "being initialized" rather than "being mutably accessed" when
describing initialization state of OnceLock.
- Use Relaxed ordering when transitioning to exclusive access in
OnceLock.
- Add drop implementation for OnceLock.
- Re-export OnceLock from kernel::sync module.
- Improve indentation of in macro code. Prefix cfg to ::core::cfg in
macro code.
- Use core::ptr::from_ref rather than as casts.
- Hide KernelParam instances behind const _: () blocks.
- Rename ModuleParamAccess::get to ModuleParamAccess::value.
- Rename RacyKernelParam to KernelParam.
- Remove ModuleParam::Value.
- Move copy implementation of OnceLock.
- Update safety comments and invariants of OnceLock.
- Link to v14: https://lore.kernel.org/r/[email protected]
Note: This series now depends on the atomics series [1].
[1] https://lore.kernel.org/all/[email protected]
Changes in v14:
- Remove unnecessary crate:: prefix from module_param::set_param.
- Make FromStrRadix safe again by moving unsafe blocks to macro implementation (thanks Benno).
- Use core::ptr::write in set_param and drop safety requirement regarding initialization.
- Add a TODO to use SyncUnsafeCell for ModuleParamAccess when available.
- Add a NOTE regarding Copy bound on ModuleParam.
- Remove 'static lifetime qualifier from ModuleParam::try_from_param_arg argument.
- Fix a typo in the safety requirements for set_param.
- Remove unused #[macro_export] attribute.
- Remove obsolete documentation for ModuleParam::try_from_param_arg.
- Make RacyKernelParam tuple field private.
- Introduce OnceLock and use that to synchronize population of parameter values.
- Link to v13: https://lore.kernel.org/r/[email protected]
Changes in v13:
- remove absolute path for ffi types.
- Split patch 2 into 4 separate patches.
- Overhaul safety framework for set_param.
- Remove generated docs for kernel_param_ops.
- Move parse_int to separate file.
- Rebase on v6.16-rc1
- Link to v12: https://lore.kernel.org/r/[email protected]
Changes in v12:
- Assign through pointer rather than using core::ptr::replace.
- Prevent a potential use-after-free during module teardown.
- Link to v11: https://lore.kernel.org/r/[email protected]
Changes in v11:
- Apply a few nits from Miguel.
- Link to v10: https://lore.kernel.org/r/[email protected]
Changes in v10:
- Apply fixups from Miguel:
- Add integer type suffixes to assert! in tests.
- Fix links to docs.kernel.org.
- Applyy markdown and intra-doc links where possible.
- Change to /// for mod docs.
- Slightly reword a comment.
- Pluralize "Examples" section name.
- Hide uses in example.
- Removed #[expect] for the rusttest target.
- Link to v9: https://lore.kernel.org/r/[email protected]
Changes in v9:
- Remove UB when parsing the minimum integer values.
- Make FromStr trait unsafe, since wrong implementations can cause UB.
- Drop patches that were applied to rust-next.
- Link to v8: https://lore.kernel.org/r/[email protected]
Changes in v8:
- Change print statement in sample to better communicate parameter name.
- Use imperative mode in commit messages.
- Remove prefix path from EINVAL.
- Change try_from_param_arg to accept &BStr rather than &[u8].
- Parse integers without 128 bit integer types.
- Seal trait FromStrRadix.
- Strengthen safety requirement of set_param.
- Remove comment about Display and PAGE_SIZE.
- Add note describing why ModuleParamAccess is pub.
- Typo and grammar fixes for documentation.
- Update MAINTAINERS with rust module files.
- Link to v7: https://lore.kernel.org/r/[email protected]
Changes in v7:
- Remove dependency on pr_warn_once patches, replace with TODO.
- Rework ParseInt::from_str to avoid allocating.
- Add a comment explaining how we parse "0".
- Change trait bound on Index impl for BStr to match std library approach.
- Link to v6: https://lore.kernel.org/r/[email protected]
Changes in v6:
- Fix a bug that prevented parsing of negative default values for
parameters in the module! macro.
- Fix a bug that prevented parsing zero in strip_radix. Also add a
test case for this.
- Add AsRef<BStr> for [u8] and BStr.
- Use impl AsRef<BStr> as type of prefix in BStr::strip_prefix.
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Fix a typo in a safety comment in set_param.
- Use a match statement in parse_int::strip_radix.
- Add an implementation of Index for BStr.
- Fix a logic inversion bug where parameters would not be parsed.
- Use kernel::ffi::c_char in set_param rather than the one in core.
- Use kernel::c_str! rather than c"..." literal in module macro.
- Rebase on v6.14-rc1.
- Link to v4: https://lore.kernel.org/r/[email protected]
Changes in v4:
- Add module maintainers to Cc list (sorry)
- Add a few missing [doc_links]
- Add panic section to expect_string_field
- Fix a typo in safety requirement of module_params::free
- Change assert! to pr_warn_once! in module_params::set_param
- Remove module_params::get_param and install null pointer instead
- Remove use of the unstable feature sync_unsafe_cell
- Link to v3: https://lore.kernel.org/r/[email protected]
Changes in v3:
- use SyncUnsafeCell rather than static mut and simplify parameter access
- remove Display bound from ModuleParam
- automatically generate documentation for PARAM_OPS_.*
- remove as *const _ as *mut_ phrasing
- inline parameter name in struct instantiation in emit_params
- move RacyKernelParam out of macro template
- use C string literals rather than byte string literals with explicit null
- template out __{name}_{param_name} in emit_param
- indent template in emit_params
- use let-else expression in emit_params to get rid of an indentation level
- document expect_string_field
- move invication of impl_int_module_param to be closer to macro def
- move attributes after docs in make_param_ops
- rename impl_module_param to impl_int_module_param`
- use ty instead of ident in impl_parse_int
- use BStr instead of &str for string manipulation
- move string parsing functions to seperate patch and add examples, fix bugs
- degrade comment about future support from doc comment to regular comment
- remove std lib path from Sized marker
- update documentation for trait ModuleParam
- Link to v2: https://lore.kernel.org/all/[email protected]/
Changes in v2:
- Remove support for params without values (NOARG_ALLOWED).
- Improve documentation for try_from_param_arg.
- Use prelude import.
- Refactor try_from_param_arg to return Result.
- Refactor ParseInt::from_str to return Result.
- Move C callable functions out of ModuleParam trait.
- Rename literal string field parser to expect_string_field.
- Move parameter parsing from generation to parsing stage.
- Use absolute type paths in macro code.
- Inline kparamand read_func values.
- Resolve TODO regarding alignment attributes.
- Remove unnecessary unsafe blocks in macro code.
- Improve error message for unrecognized parameter types.
- Do not use self receiver when reading parameter value.
- Add parameter documentation to module! macro.
- Use empty enum for parameter type.
- Use addr_of_mut to get address of parameter value variable.
- Enabled building of docs for for module_param module.
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/
---
Andreas Hindborg (7):
rust: sync: add SetOnce
rust: str: add radix prefixed integer parsing functions
rust: introduce module_param module
rust: module: use a reference in macros::module::module
rust: module: update the module macro with module parameter support
rust: samples: add a module parameter to the rust_minimal sample
modules: add rust modules files to MAINTAINERS
MAINTAINERS | 2 + rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 181 +++++++++++++++++++++++++++++++++++++++ rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 ++++++++++++++++++++++++++++++++ rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++ rust/macros/helpers.rs | 25 ++++++ rust/macros/lib.rs | 31 +++++++ rust/macros/module.rs | 198 ++++++++++++++++++++++++++++++++++++++----- samples/rust/rust_minimal.rs | 10 +++ 11 files changed, 705 insertions(+), 20 deletions(-)
---
base-commit: 47633099a672fc7bfe604ef454e4f116e2c954b1
change-id: 20241211-module-params-v3-ae7e5c8d8b5a
prerequisite-message-id: [email protected]
prerequisite-patch-id: 997f74bd63d81dc66725d7f84ffcf5a3517da1eb
prerequisite-patch-id: 3e3f8bdada027406a356a2b35aebe13edbda0a94
prerequisite-patch-id: 468b093532aa503c23302142b8cfe7989e3cb8f1
prerequisite-patch-id: 96ca162a1e95a29d3aca2e748d600a31417b83e5
prerequisite-patch-id: 8f78abede975c0c9690ee0f4cf4e7af3cb145191
prerequisite-patch-id: a716ee7a51184d224ef60812ecfffadb51980153
prerequisite-patch-id: e54f74896a75147b66e509c1281804047d41f08b
prerequisite-patch-id: 3f77e2179901ae664a2d2e58965a9725ad13189e
prerequisite-patch-id: e964a9576f9c3970bb7a34b4d2891ffb92939d0e
prerequisite-patch-id: bba35ecdf783653e0fa46015bc289706508fac55
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
reviewerPATCH v15 1/7 rust: sync: add `SetOnce`
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.
--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+)
rust/kernel/sync.rs +2 -0
@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;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 ;/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`. #[repr(transparent)]
rust/kernel/sync/set_once.rs new file +125 -0
125 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 79 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+)rust/kernel/sync.rs +2
-0@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;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 ;/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`. #[repr(transparent)] rust/kernel/sync/set_once.rs new file +43
-0@@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A container that can be initialized at most once. + +use super ::atomic::ordering::Acquire ; +use super ::atomic::ordering::Relaxed ; +use super ::atomic::ordering::Release ; +use super ::atomic::Atomic ; +use core::ptr::drop_in_place; +use kernel::types::Opaque ; + +/// 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..=2`. +/// - `init == 0` if and only if the container is empty. +/// - `init == 1` if and only if being initialized. +/// - `init == 2` if and only if the container is populated and valid for shared access. +/// +/// # Example +/// +/// ``` +/// # use kernel::sync::SetOnce; +/// let value = SetOnce::new(); +/// assert_eq!(None, value.as_ref()); +/// +/// let status = value.populate(42u8); +/// assert_eq!(true, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// +/// let status = value.populate(101u8); +/// assert_eq!(false, status); +/// assert_eq!(Some(&42u8), value.as_ref()); +/// assert_eq!(Some(42u8), value.copy()); +/// ``` +pub struct SetOnce <T > { + init:Atomic <u32 >,
rust/kernel/sync/set_once.rs line 53
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+ value: Opaque<T>, +} + +impl <T >Default for SetOnce <T > { +fn default () ->Self { +Self ::new () + } +} + +// TODO: change names
I just saw that this line decided to stick around, that was obviously not intentional. Just disregard this line.
Best regards,
Andreas Hindborg
Re: [PATCH v15 1/7] rust: sync: add `SetOnce`
In reply to Andreas HindborgQuoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>
LGTM:
rust/kernel/sync/set_once.rs line 122
Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Alice
Re: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>rust/kernel/sync/set_once.rs line 122
Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };
Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }Further, with my following Benno's suggestion and making Atomic<T> an `UnsafeCell<T>:
https://lore.kernel.org/rust-for-linux/[email protected]/
compiler can generate a noalias reference here, which allows further optimization.
Regards,
Boqun
Quoted 2 lines
Alice
Andreas Hindborg
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 27 lines · Boqun Feng
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>rust/kernel/sync/set_once.rs line 122
Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }
Quoted 8 lines
Further, with my following Benno's suggestion and making
Atomic<T>an `UnsafeCell<T>:https://lore.kernel.org/rust-for-linux/[email protected]/
compiler can generate a noalias reference here, which allows further optimization.
You would like to remove PhantomPinned to enable noalias? I guess that makes sense in this case. I'll fix that for next spin.
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 32 lines · Andreas Hindborg
Quoted 30 lines · Boqun Feng
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>rust/kernel/sync/set_once.rs line 122
Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }Further, with my following Benno's suggestion and making
Atomic<T>an `UnsafeCell<T>:
Quoted 8 lines
Quoted 5 lines
https://lore.kernel.org/rust-for-linux/[email protected]/
compiler can generate a noalias reference here, which allows further optimization.
You would like to remove
PhantomPinnedto enable noalias? I guess that makes sense in this case. I'll fix that for next spin.
I think you two are talking about different things. Boqun is saying that the Atomic<T> will use UnsafeCell rather than Opaque, which will potentially allow more optimizations.
But you are talking about SetOnce, right? I think it makes more sense for SetOnce to use UnsafeCell<MaybeUninit<T>> rather than Opaque too. So feel free to change it in the next version.
---
Cheers,
Benno
Andreas Hindborg
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 23 lines · Benno Lossin
Quoted 22 lines · Andreas Hindborg
Quoted 20 lines · Boqun Feng
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }
Ok, now I got it. You are saying I don't need to use the atomic load method, because I have mutable access. Sounds good.
But I guess a relaxed load and access through a mutable reference should result in the same code generation on most (all?) platforms?
Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
Further, with my following Benno's suggestion and making
Atomic<T>an `UnsafeCell<T>:Quoted 8 lines
Quoted 5 lines
https://lore.kernel.org/rust-for-linux/[email protected]/
compiler can generate a noalias reference here, which allows further optimization.
You would like to remove
PhantomPinnedto enable noalias? I guess that makes sense in this case. I'll fix that for next spin.
Quoted 7 lines
I think you two are talking about different things. Boqun is saying that the
Atomic<T>will useUnsafeCellrather thanOpaque, which will potentially allow more optimizations.But you are talking about
SetOnce, right? I think it makes more sense forSetOnceto useUnsafeCell<MaybeUninit<T>>rather thanOpaquetoo. So feel free to change it in the next version.
Exactly. We don't need UnsafePinned mechanics here.
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 28 lines · Andreas Hindborg
Quoted 27 lines · Benno Lossin
Quoted 26 lines · Andreas Hindborg
Quoted 25 lines · Boqun Feng
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>rust/kernel/sync/set_once.rs line 122
Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
Quoted 7 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line
if *self.init.get_mut() == 2 { }Ok, now I got it. You are saying I don't need to use the atomic load method, because I have mutable access. Sounds good.
But I guess a relaxed load and access through a mutable reference should result in the same code generation on most (all?) platforms?
AFAIK it is not the same on arm.
---
Cheers,
Benno
Re: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 31 lines · Benno Lossin
Quoted 30 lines · Andreas Hindborg
Quoted 28 lines · Benno Lossin
Quoted 27 lines · Andreas Hindborg
Quoted 26 lines · Boqun Feng
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>Review
Quoted 7 lines
(quoted diff) +7
-0+impl<T> Drop for SetOnce<T> { + fn drop(&mut self) { + if self.init.load(Acquire) == 2 { + // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` + // contains a valid value. We have exclusive access, as we hold a `mut` reference to + // `self`. + unsafe { drop_in_place(self.value.get()) };Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }
Quoted 8 lines
Quoted 5 lines
Ok, now I got it. You are saying I don't need to use the atomic load method, because I have mutable access. Sounds good.
But I guess a relaxed load and access through a mutable reference should result in the same code generation on most (all?) platforms?
AFAIK it is not the same on arm.
Right, when LTO=y, arm64 use acquire load to implement READ_ONCE()/atomic_read().
Regards,
Boqun
Quoted 4 lines
---
Cheers,
Benno
Benno Lossin
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 35 lines · Boqun Feng
Quoted 34 lines · Benno Lossin
Quoted 33 lines · Andreas Hindborg
Quoted 22 lines · Benno Lossin
Quoted 21 lines · Andreas Hindborg
Quoted 20 lines · Boqun Feng
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>Quoted 7 lines
(quoted diff) +7
-0+impl<T> Drop for SetOnce<T> { + fn drop(&mut self) { + if self.init.load(Acquire) == 2 { + // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` + // contains a valid value. We have exclusive access, as we hold a `mut` reference to + // `self`. + unsafe { drop_in_place(self.value.get()) };Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }Ok, now I got it. You are saying I don't need to use the atomic load method, because I have mutable access. Sounds good.
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
But I guess a relaxed load and access through a mutable reference should result in the same code generation on most (all?) platforms?
AFAIK it is not the same on arm.
Right, when LTO=y, arm64 use acquire load to implement READ_ONCE()/atomic_read().
But Andreas was talking about relaxed load vs mutable reference (= normal unsynchronized write)?
---
Cheers,
Benno
Re: [PATCH v15 1/7] rust: sync: add `SetOnce`
On Wed, Jul 09, 2025 at 10:22:04PM +0200, Benno Lossin wrote:
[...]
Quoted 21 lines
Quoted 21 lines
Quoted 21 lines
Quoted 20 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
(quoted diff) +7
-0+impl<T> Drop for SetOnce<T> { + fn drop(&mut self) { + if self.init.load(Acquire) == 2 { + // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` + // contains a valid value. We have exclusive access, as we hold a `mut` reference to + // `self`. + unsafe { drop_in_place(self.value.get()) };Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, I think we can do the similar as Revocable here:
if *self.init.get_mut() == 2 { }Ok, now I got it. You are saying I don't need to use the atomic load method, because I have mutable access. Sounds good.
But I guess a relaxed load and access through a mutable reference should result in the same code generation on most (all?) platforms?
Quoted 9 lines
Quoted 5 lines
Quoted 2 lines
AFAIK it is not the same on arm.
Right, when LTO=y, arm64 use acquire load to implement READ_ONCE()/atomic_read().
But Andreas was talking about relaxed load vs mutable reference (= normal unsynchronized write)?
No, I think it was a relaxed load (self.init.load(Relaxed)) vs a normal unsynchronized *load* (*self.init.get_mut()). Yes, there is a mutable reference, but we never use it for write.
Regards,
Boqun
Quoted 4 lines
---
Cheers,
Benno
Andreas Hindborg
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
In reply to Alice RyhlQuoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>rust/kernel/sync/set_once.rs line 122
Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };
Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, that is actually very cool. My rationale was that if a reference has been shared to another thread of execution, we would need to synchronize here to see a possible initialization from that other thread. But I guess it is impossible to end the lifetime of a reference without doing a synchronization somewhere else.
Best regards,
Andreas Hindborg
Alice Ryhl
maintainerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 22 lines · Andreas Hindborg
Quoted 19 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>LGTM:
Reviewed-by Alice Ryhl <[email protected]>Quoted 7 lines
rust/kernel/sync/set_once.rs new file +7
-0+impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if self.init.load (Acquire ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value. We have exclusive access, as we hold a `mut` reference to +// `self`. +unsafe {drop_in_place (self.value.get ()) };
Quoted 8 lines
Quoted 2 lines
This load does not need to be Acquire. It can be a Relaxed load or even an unsynchronized one since the access is exclusive.
Right, that is actually very cool. My rationale was that if a reference has been shared to another thread of execution, we would need to synchronize here to see a possible initialization from that other thread. But I guess it is impossible to end the lifetime of a reference without doing a synchronization somewhere else.
Yup, a mutable reference generally implies synchronization.
Alice
Re: [PATCH v15 1/7] rust: sync: add `SetOnce`
In reply to Andreas HindborgQuoted 5 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>
One nit and a safety comment fix below. (feel free to ignore the nit) With the safety comment fixed:
Quoted 10 lines
--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+)rust/kernel/sync.rs +0
-0
rust/kernel/sync.rs line 21
Quoted 4 lines
rust/kernel/sync.rs +1
-0@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;
I would have named this once.
rust/kernel/sync.rs
Quoted 10 lines
rust/kernel/sync.rs +7
-0pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use completion::Completion ; +/// 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 ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value.
And the type invariants also ensure that the value of self.init doesn't change.
So probably
// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
// contains a valid value. They also guarantee that `self.init` doesn't change.If you come up with something better, feel free to use it.
---
Cheers,
Benno
Quoted 5 lines
rust/kernel/sync.rs +5
-0+Some (unsafe { &*self.value.get () }) + }else { +None + } + }
Andreas Hindborg
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 17 lines · Benno Lossin
Quoted 5 lines · Andreas Hindborg
Introduce the
SetOncetype, a container that can only be written once. The container uses an internal atomic to synchronize writes to the internal value.Signed-off-by Andreas Hindborg <[email protected]>One nit and a safety comment fix below. (feel free to ignore the nit) With the safety comment fixed:
Reviewed-by Benno Lossin <[email protected]>Quoted 5 lines
--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+)
Quoted 11 lines
rust/kernel/sync.rs line 21
Quoted 9 lines
rust/kernel/sync.rs +1
-0@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;I would have named this
once.
So module once and struct SetOnce? Struct name Once would lead thoughts to std::sync::Once, which is a different thing.
Quoted 12 lines
rust/kernel/sync.rs
Quoted 11 lines
rust/kernel/sync.rs +7
-0pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use completion::Completion ; +/// 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 ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value.
Quoted 8 lines
And the type invariants also ensure that the value of
self.initdoesn't change.So probably
// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` // contains a valid value. They also guarantee that `self.init` doesn't change.
Sure 👍
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 14 lines · Andreas Hindborg
Quoted 12 lines · Benno Lossin
rust/kernel/sync.rs line 21
Quoted 9 lines · Andreas Hindborg
rust/kernel/sync.rs +1
-0@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;I would have named this
once.
Quoted 2 lines
So module
onceand structSetOnce? Struct nameOncewould lead thoughts tostd::sync::Once, which is a different thing.
Hmm I thought that Once and SetOnce would live in the same module, but if they don't then I think it's better to keep the set_once module as-is.
---
Cheers,
Benno
Andreas Hindborg
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 15 lines · Benno Lossin
Quoted 14 lines · Andreas Hindborg
Quoted 12 lines · Benno Lossin
rust/kernel/sync.rs line 21
Quoted 9 lines · Andreas Hindborg
rust/kernel/sync.rs +1
-0@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;I would have named this
once.
Quoted 6 lines
Quoted 2 lines
So module
onceand structSetOnce? Struct nameOncewould lead thoughts tostd::sync::Once, which is a different thing.Hmm I thought that
OnceandSetOncewould live in the same module, but if they don't then I think it's better to keep theset_oncemodule as-is.
I guess they could live together. I was thinking a module for each. We can always move it, the module name is not part of a public API.
Let's go with set_once for now and we can change it later, if we decide it is for the better?
Best regards,
Andreas Hindborg
Benno Lossin
reviewerRe: [PATCH v15 1/7] rust: sync: add `SetOnce`
Quoted 24 lines · Andreas Hindborg
Quoted 15 lines · Benno Lossin
Quoted 14 lines · Andreas Hindborg
Quoted 12 lines · Benno Lossin
rust/kernel/sync.rs line 21
Quoted 9 lines · Andreas Hindborg
rust/kernel/sync.rs +1
-0@@ -18,6 +18,7 @@mod locked_by;pub mod poll;pub mod rcu; +mod set_once;I would have named this
once.Quoted 6 lines
Quoted 2 lines
So module
onceand structSetOnce? Struct nameOncewould lead thoughts tostd::sync::Once, which is a different thing.Hmm I thought that
OnceandSetOncewould live in the same module, but if they don't then I think it's better to keep theset_oncemodule as-is.
Quoted 5 lines
I guess they could live together. I was thinking a module for each. We can always move it, the module name is not part of a public API.
Let's go with
set_oncefor now and we can change it later, if we decide it is for the better?
Sure.
---
Cheers,
Benno
Andreas Hindborg
reviewerPATCH v15 2/7 rust: str: add radix prefixed integer parsing functions
In reply to Andreas HindborgAdd 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.
--- rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+)
rust/kernel/str.rs +2 -0
@@ -8,6 +8,8 @@use crate ::prelude::*; +pub mod parse_int; +/// Byte string without UTF-8 validity guarantee. #[repr(transparent)] pub struct BStr ([u8 ]);
rust/kernel/str/parse_int.rs new file +148 -0
148 lines not on this page · raw message
Signature · 1 line
2.47.2
Re: [PATCH v15 2/7] rust: str: add radix prefixed integer parsing functions
Quoted 8 lines · Andreas Hindborg
Add the trait
ParseIntfor parsing string representations of integers where the string representations are optionally prefixed by a radix specifier. Implement the trait for the primitive integer types.Tested-by Daniel Gomez <[email protected]>Reviewed-by Greg Kroah-Hartman <[email protected]>Suggested-by Benno Lossin <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>
---
Cheers,
Benno
Quoted 4 lines
--- rust/kernel/str.rs | 2 + rust/kernel/str/parse_int.rs | 148 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+)
Andreas Hindborg
reviewerPATCH v15 3/7 rust: introduce module_param module
In reply to Andreas HindborgAdd types and traits for interfacing the C moduleparam API.
--- rust/kernel/lib.rs | 1 + rust/kernel/module_param.rs | 181 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -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;
rust/kernel/module_param.rs new file +181 -0
181 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v15 4/7 rust: module: use a reference in macros::module::module
In reply to Andreas HindborgWhen 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.
--- rust/macros/module.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-)
rust/macros/module.rs +10 -10
@@ -179,26 +179,26 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {// Rust does not allow hyphens in identifiers, use underscore instead. let ident = info.name.replace ('-' ,"_" );let mut modinfo =ModInfoBuilder ::new (ident.as_ref ()); -if let Some (author) = info.author { - modinfo.emit ("author" , &author); +if let Some (author) = &info.author { + modinfo.emit ("author" , author); } -if let Some (authors) = info.authors { +if let Some (authors) = &info.authors {for authorin authors { - modinfo.emit ("author" , &author); + modinfo.emit ("author" , author); } } -if let Some (description) = info.description { - modinfo.emit ("description" , &description); +if let Some (description) = &info.description { + modinfo.emit ("description" , description); } modinfo.emit ("license" , &info.license); -if let Some (aliases) = info.alias { +if let Some (aliases) = &info.alias {for aliasin aliases { - modinfo.emit ("alias" , &alias); + modinfo.emit ("alias" , alias); } } -if let Some (firmware) = info.firmware { +if let Some (firmware) = &info.firmware {for fwin firmware { - modinfo.emit ("firmware" , &fw); + modinfo.emit ("firmware" , fw); } }
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v15 5/7 rust: module: update the module macro with module parameter support
In reply to Andreas HindborgAllow module parameters to be declared in the rust module! macro.
--- rust/macros/helpers.rs | 25 +++++++ rust/macros/lib.rs | 31 +++++++++ rust/macros/module.rs | 178 ++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 224 insertions(+), 10 deletions(-)
rust/macros/helpers.rs +25 -0
@@ -10,6 +10,17 @@ pub(crate) fn try_ident(it: &mut token_stream::IntoIter) -> Option<String> { } } +pub (crate )fn try_sign (it: &mut token_stream::IntoIter ) ->Option <char > { +let peek = it.clone ().next (); +match peek { +Some (TokenTree ::Punct (punct))if punct.as_char () =='-' => { +let _ = it.next (); +Some (punct.as_char ()) + } + _ =>None , + } +} +pub (crate )fn try_literal (it: &mut token_stream::IntoIter ) ->Option <String > {if let Some (TokenTree ::Literal (literal)) = 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 , expected_name: &str ) ->String { +assert_eq! (expect_ident (it), expected_name); +assert_eq! (expect_punct (it),':' ); +let string =expect_string (it); +assert_eq! (expect_punct (it),',' ); + string +}
rust/macros/lib.rs +31 -0
@@ -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/moduleparam.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<Self> { /// let foo: i32 = 42; /// pr_info!("I contain: {}\n", foo); +/// pr_info!("i32 param is: {}\n", module_parameters::my_parameter.read()); /// Ok(Self(foo)) /// } /// }
rust/macros/module.rs +168 -10
252 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v15 6/7 rust: samples: add a module parameter to the rust_minimal sample
In reply to Andreas HindborgShowcase the rust module parameter support by adding a module parameter to the rust_minimal sample.
--- samples/rust/rust_minimal.rs | 10 ++++++++++ 1 file changed, 10 insertions(+)
samples/rust/rust_minimal.rs +10 -0
@@ -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" , + }, + }, }struct RustMinimal {
@@ -20,6 +26,10 @@ impl kernel::Module for RustMinimal {fn init (_module: &'staticThisModule ) ->Result <Self > {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 () + );let mut numbers =KVec ::new (); numbers.push (72 ,GFP_KERNEL )?;
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v15 7/7 modules: add rust modules files to MAINTAINERS
In reply to Andreas HindborgThe module subsystem people agreed to maintain rust support for modules [1]. Thus, add entries for relevant files to modules entry in MAINTAINERS.
--- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+)
MAINTAINERS +2 -0
@@ -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/
Signature · 1 line
2.47.2
Quoted 2 lines · Andreas Hindborg
Based on code by Adam Bratschi-Kaye lifted from the original
rustbranch [1].
I would suggest adding this sort of note to the commit messages, especially since the commits have no Co-developed-by/Link tags otherwise.
From our discussion in Zulip: the code itself is older than that the merge above. I think you wanted an example sentence for this -- something simple could be e.g.
Based on the original module parameter support by Miguel [1],
later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].
Link: https://github.com/Rust-for-Linux/linux/pull/7 [1] Link: https://github.com/Rust-for-Linux/linux/pull/82 [2] Link: https://github.com/Rust-for-Linux/linux/pull/87 [3] Link: https://github.com/Rust-for-Linux/linux/issues/11 [4]
By the way, I guess you should inherit that issue in the last link :) It had some details about things we may or may not want to support etc. that I looked up back then. If you prefer that we close it or that we create sub-issues, that is fine -- up to you!
Finally, if you end up adding strings, please link to Adam's
https://github.com/Rust-for-Linux/linux/pull/110.
Thanks!
Cheers,
Miguel
Andreas Hindborg
reviewerQuoted 21 lines · Miguel Ojeda
Quoted 2 lines · Andreas Hindborg
Based on code by Adam Bratschi-Kaye lifted from the original
rustbranch [1].I would suggest adding this sort of note to the commit messages, especially since the commits have no Co-developed-by/Link tags otherwise.
From our discussion in Zulip: the code itself is older than that the merge above. I think you wanted an example sentence for this -- something simple could be e.g.
Based on the original module parameter support by Miguel [1],
later extended and generalized by Adam for more types [2][3]. Originally tracked at [4].Link: https://github.com/Rust-for-Linux/linux/pull/7 [1] Link: https://github.com/Rust-for-Linux/linux/pull/82 [2] Link: https://github.com/Rust-for-Linux/linux/pull/87 [3] Link: https://github.com/Rust-for-Linux/linux/issues/11 [4]
Quoted 7 lines
By the way, I guess you should inherit that issue in the last link :) It had some details about things we may or may not want to support etc. that I looked up back then. If you prefer that we close it or that we create sub-issues, that is fine -- up to you!
Finally, if you end up adding strings, please link to Adam's
https://github.com/Rust-for-Linux/linux/pull/110.
Thanks, I'll add this!
Best regards,
Andreas Hindborg