rust: extend `module!` macro with integer parameter support
Subsystems (4)
Andreas Hindborg
reviewerv16 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.
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].
---
Changes in v16:
- Normalize imports in set_once.rs.
- Use UnsafeCell<MaybeUninit<T>> rather than Opaque<T> for SetOnce.
- Use regular load in drop of SetOnce.
- Update attribution paragraph in cover letter with details from Miguel.
- Remove stray TODO in set_once.rs
- Link to v15: https://lore.kernel.org/r/[email protected]
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 | 122 ++++++++++++++++++++++++++ rust/macros/helpers.rs | 25 ++++++ rust/macros/lib.rs | 31 +++++++ rust/macros/module.rs | 198 ++++++++++++++++++++++++++++++++++++++----- samples/rust/rust_minimal.rs | 10 +++ 11 files changed, 702 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 v16 5/7 rust: module: update the module macro with module parameter support
Allow 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 v16 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 v16 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
Andreas Hindborg
reviewerPATCH v16 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
Andreas Hindborg
reviewerPATCH v16 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 v16 1/7 rust: sync: add `SetOnce`
In reply to Andreas HindborgIntroduce 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 | 122 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 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 +122 -0
122 lines not on this page · raw message
Signature · 1 line
2.47.2
Andreas Hindborg
reviewerPATCH v16 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
Re: [PATCH v16 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.Reviewed-by Alice Ryhl <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>
A couple notes on safety documentation below. Also one pretty subtle functionality change from last version. With everything fixed:
Quoted 43 lines
--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 122 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 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 +12
-0@@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A container that can be initialized at most once. + +use super ::atomic::{ + ordering::{Acquire ,Relaxed ,Release }, +Atomic , +}; +use core::{cell::UnsafeCell , mem::MaybeUninit , ptr::drop_in_place}; + +/// A container that can be populated at most once. Thread safe. +///
rust/kernel/sync/set_once.rs line 22
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+/// 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.
I think I have a better idea for the last three invariants:
- init == 0 if and only if value is uninitialized.
- init == 1 if and only if there is exactly one thread with exclusive access to self.value.
- init == 2 if and only if value is initialized and valid for shared access.
Quoted 38 lines
rust/kernel/sync/set_once.rs new file +38
-0+/// +/// # 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 >, + value:UnsafeCell <MaybeUninit <T >>, +} + +impl <T >Default for SetOnce <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >SetOnce <T > { +/// 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 ),
rust/kernel/sync/set_once.rs line 70
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-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 ) ==2 { +// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value` +// contains a valid value.
s/contains a valid value/is initialized and valid for shared access/
Quoted 8 lines
rust/kernel/sync/set_once.rs new file +8
-0+Some (unsafe { &*self.value.get ().cast () }) + }else { +None + } + } + +/// Populate the [`SetOnce`]. +///
rust/kernel/sync/set_once.rs line 88
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+/// 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 exclusive access after the +// write. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Relaxed ) { +// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1` +// to `self.init` means we obtained exclusive access to the contained object.
s/to the contained object/to self.value/
Quoted 21 lines
rust/kernel/sync/set_once.rs new file +21
-0+unsafe { core::ptr::write (self.value.get ().cast (), value) }; +// INVARIANT: +// - We increase `init`. +// - We write the valid value `2` to `init`. +// - We release our exclusive access to the contained object and the object is now +// valid for shared access. + self.init.store (2 ,Release ); +true + }else { +false + } + } + +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`SetOnce`] is empty. +pub fn copy (&self) ->Option <T > +where +T :Copy , + { + self.as_ref ().copied ()
rust/kernel/sync/set_once.rs line 119
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+ } +} + +impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if *self.init.get_mut () ==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 is sadly doing the wrong thing now since you changed the type of value: self.value.get() is of type MaybeUninit<T> and dropping that has (obviously) no effect. So we probably need to do
let value = unsafe { &mut *self.value.get() };
unsafe { value.assume_init_drop() };I almost overlooked this :)
---
Cheers,
Benno
Quoted 3 lines
rust/kernel/sync/set_once.rs new file +3
-0+ } + } +}
Andreas Hindborg
reviewerRe: [PATCH v16 1/7] rust: sync: add `SetOnce`
Quoted 69 lines · Benno Lossin
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.Reviewed-by Alice Ryhl <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>A couple notes on safety documentation below. Also one pretty subtle functionality change from last version. With everything fixed:
Reviewed-by Benno Lossin <[email protected]>Quoted 43 lines
--- rust/kernel/sync.rs | 2 + rust/kernel/sync/set_once.rs | 122 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 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 +12
-0@@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A container that can be initialized at most once. + +use super ::atomic::{ + ordering::{Acquire ,Relaxed ,Release }, +Atomic , +}; +use core::{cell::UnsafeCell , mem::MaybeUninit , ptr::drop_in_place}; + +/// A container that can be populated at most once. Thread safe. +/// rust/kernel/sync/set_once.rs line 22
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+/// 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. I think I have a better idea for the last three invariants:
Quoted 5 lines
-
init == 0if and only ifvalueis uninitialized.
-init == 1if and only if there is exactly one thread with exclusive access toself.value.
-init == 2if and only ifvalueis initialized and valid for shared access.
Sounds good to me.
Quoted 43 lines
Quoted 43 lines
rust/kernel/sync/set_once.rs new file +42
-0+/// +/// # 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 >, + value:UnsafeCell <MaybeUninit <T >>, +} + +impl <T >Default for SetOnce <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >SetOnce <T > { +/// 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.
Quoted 8 lines
rust/kernel/sync/set_once.rs line 70
Quoted 6 lines
rust/kernel/sync/set_once.rs new file +6
-0+/// +/// 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. s/contains a valid value/is initialized and valid for shared access/
OK.
Quoted 20 lines
Quoted 9 lines
rust/kernel/sync/set_once.rs new file +8
-0+Some (unsafe { &*self.value.get ().cast () }) + }else { +None + } + } + +/// Populate the [`SetOnce`]. +/// rust/kernel/sync/set_once.rs line 88
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+/// 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 exclusive access after the +// write. +if let Ok (0 ) = self.init.cmpxchg (0 ,1 ,Relaxed ) { +// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1` +// to `self.init` means we obtained exclusive access to the contained object.
Quoted 1 line
s/to the contained object/to
self.value/
OK.
Quoted 37 lines
Quoted 22 lines
rust/kernel/sync/set_once.rs new file +21
-0+unsafe { core::ptr::write (self.value.get ().cast (), value) }; +// INVARIANT: +// - We increase `init`. +// - We write the valid value `2` to `init`. +// - We release our exclusive access to the contained object and the object is now +// valid for shared access. + self.init.store (2 ,Release ); +true + }else { +false + } + } + +/// Get a copy of the contained object. +/// +/// Returns [`None`] if the [`SetOnce`] is empty. +pub fn copy (&self) ->Option <T > +where +T :Copy , + { + self.as_ref ().copied ()rust/kernel/sync/set_once.rs line 119
Quoted 10 lines
rust/kernel/sync/set_once.rs new file +10
-0+ } +} + +impl <T >Drop for SetOnce <T > { +fn drop (&mut self) { +if *self.init.get_mut () ==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 is sadly doing the wrong thing now since you changed the type of
value:self.value.get()is of typeMaybeUninit<T>and dropping that has (obviously) no effect. So we probably need to do
Quoted 4 lines
let value = unsafe { &mut *self.value.get() }; unsafe { value.assume_init_drop() };I almost overlooked this :)
Oops.
Best regards,
Andreas Hindborg