`Zeroable` improvements & bindings integration
Subsystems (11)
Benno Lossin
maintainerv2 cover `Zeroable` improvements & bindings integration
Depends on the pin-init test & CI fixes sync [1].
This came from a discussion at [2]. And I added some more useful parts to the original idea.
I'm not sure on the impact of build times and rust-analyzer. We're adding a derive macro to every struct and union emitted by bindgen. Building using my test-config took 27.7s before and 28.2s after this change, but those are only two runs on my machine with a very reduced config (that enables all Rust code that we have at the moment).
Maybe we have to reevaluate this when more C code is scanned by bindgen.
[1]: https://rust-for-linux.zulipchat.com/#narrow/channel/291565-Help/topic/Zeroable.20trait.20for.20C.20structs/with/509711564
[2]: https://lore.kernel.org/all/[email protected]
Changelog
=========
* v2:
- added patches with more extensive pin-init changes to Zeroable & related methods. for the upstream PR, see
https://github.com/Rust-for-Linux/pin-init/pull/56
- added patches replacing usage of mem::zeroed and MaybeUninit::zeroed().assume_init() with the new pin_init::zeroed
- fix rust-analyzer support
- use import in {uapi,bindings}/lib.rs to avoid the pin_init:: prefix
* v1: https://lore.kernel.org/all/[email protected]
Benno Lossin (13):
rust: pin-init: rename zeroed to init_zeroed
rust: pin-init: add Zeroable::init_zeroed
rust: pin-init: add zeroed() & Zeroable::zeroed() functions
rust: pin-init: implement ZeroableOption for &T and &mut T
rust: pin-init: change impl Zeroable for Option<NonNull<T>> to
ZeroableOption for NonNull<T>
rust: pin-init: implement ZeroableOption for function pointers with
up to 20 arguments
rust: add pin-init as a dependency to bindings and uapi
rust: derive Zeroable for all structs & unions generated by bindgen
where possible
rust: miscdevice: replace MaybeUninit::zeroed().assume_init with
`pin_init::zeroed`
rust: phy: replace `MaybeUninit::zeroed().assume_init` with
`pin_init::zeroed` rust: block: replace core::mem::zeroed with pin_init::zeroed
rust: of: replace core::mem::zeroed with pin_init::zeroed
rust: security: replace core::mem::zeroed with pin_init::zeroed
rust/Makefile | 6 +- rust/bindgen_parameters | 4 + rust/bindings/lib.rs | 8 ++ rust/kernel/block/mq/gen_disk.rs | 3 +- rust/kernel/block/mq/tag_set.rs | 4 +- rust/kernel/init.rs | 8 +- rust/kernel/miscdevice.rs | 8 +- rust/kernel/net/phy.rs | 4 +- rust/kernel/of.rs | 4 +- rust/kernel/security.rs | 3 +- rust/pin-init/README.md | 2 +- rust/pin-init/examples/big_struct_in_place.rs | 4 +- rust/pin-init/src/lib.rs | 120 +++++++++++++++--- rust/pin-init/src/macros.rs | 16 +-- rust/uapi/lib.rs | 2 + scripts/generate_rust_analyzer.py | 4 +- 16 files changed, 147 insertions(+), 53 deletions(-)
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: 8d7ade67c2e5189bf8a2c91253d925e25744cba5
prerequisite-patch-id: 0ebbd4a86bebeff23257870db92a1b0fe017c481
prerequisite-patch-id: 1437fc7adeff6e13abd433594da923272b9388bf
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 1/13 rust: pin-init: rename `zeroed` to `init_zeroed`
The name zeroed is a much better fit for a function that returns the type by-value.
--- rust/kernel/init.rs | 8 +++--- rust/pin-init/README.md | 2 +- rust/pin-init/examples/big_struct_in_place.rs | 4 +-- rust/pin-init/src/lib.rs | 28 +++++++++---------- rust/pin-init/src/macros.rs | 16 +++++------ 5 files changed, 29 insertions(+), 29 deletions(-)
rust/kernel/init.rs +4 -4
@@ -206,7 +206,7 @@ fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self>/// /// ```rust /// use kernel::error::Error; -/// use pin_init::zeroed; +/// use pin_init::init_zeroed; /// struct BigBuf { /// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024],
@@ -215,7 +215,7 @@ fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self>/// impl BigBuf { /// fn new() -> impl Init<Self, Error> { /// try_init!(Self { -/// big: KBox::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init_zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// }
@@ -264,7 +264,7 @@ macro_rules! try_init {/// ```rust /// # #![feature(new_uninit)] /// use kernel::error::Error; -/// use pin_init::zeroed; +/// use pin_init::init_zeroed; /// #[pin_data] /// struct BigBuf { /// big: KBox<[u8; 1024 * 1024 * 1024]>,
@@ -275,7 +275,7 @@ macro_rules! try_init {/// impl BigBuf { /// fn new() -> impl PinInit<Self, Error> { /// try_pin_init!(Self { -/// big: KBox::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init_zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error)
rust/pin-init/README.md +1 -1
@@ -125,7 +125,7 @@ impl DriverData { fn new() -> impl PinInit<Self, Error> { try_pin_init!(Self { status <- CMutex::new(0), - buffer: Box::init(pin_init::zeroed())?, + buffer: Box::init(pin_init::init_zeroed())?, }? Error) } }
rust/pin-init/examples/big_struct_in_place.rs +2 -2
@@ -21,7 +21,7 @@ pub struct ManagedBuf {impl ManagedBuf {pub fn new () ->impl Init <Self > { -init! (ManagedBuf { buf <-zeroed () }) +init! (ManagedBuf { buf <-init_zeroed () }) } }
@@ -30,7 +30,7 @@ fn main() { { // we want to initialize the struct in-place, otherwise we would get a stackoverflow let buf: Box<BigStruct> = Box::init(init!(BigStruct { - buf <- zeroed(), + buf <- init_zeroed(), a: 7, b: 186, c: 7789,
rust/pin-init/src/lib.rs +14 -14
@@ -148,7 +148,7 @@//! fn new() -> impl PinInit<Self, Error> { //! try_pin_init!(Self { //! status <- CMutex::new(0), -//! buffer: Box::init(pin_init::zeroed())?, +//! buffer: Box::init(pin_init::init_zeroed())?, //! }? Error) //! } //! }
@@ -742,7 +742,7 @@ macro_rules! stack_try_pin_init {/// - Fields that you want to initialize in-place have to use `<-` instead of `:`. /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`] /// pointer named `this` inside of the initializer. -/// - Using struct update syntax one can place `..Zeroable::zeroed()` at the very end of the +/// - Using struct update syntax one can place `..Zeroable::init_zeroed()` at the very end of the /// struct, this initializes every field with 0 and then runs all initializers specified in the /// body. This can only be done if [`Zeroable`] is implemented for the struct. ///
@@ -769,7 +769,7 @@ macro_rules! stack_try_pin_init {/// }); /// let init = pin_init!(Buf { /// buf: [1; 64], -/// ..Zeroable::zeroed() +/// ..Zeroable::init_zeroed() /// }); /// ``` ///
@@ -805,7 +805,7 @@ macro_rules! pin_init {/// ```rust /// # #![feature(allocator_api)] /// # #[path = "../examples/error.rs"] mod error; use error::Error; -/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, zeroed}; +/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, init_zeroed}; /// /// #[pin_data] /// struct BigBuf {
@@ -817,7 +817,7 @@ macro_rules! pin_init {/// impl BigBuf { /// fn new() -> impl PinInit<Self, Error> { /// try_pin_init!(Self { -/// big: Box::init(zeroed())?, +/// big: Box::init(init_zeroed())?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error)
@@ -866,7 +866,7 @@ macro_rules! try_pin_init {/// # #[path = "../examples/error.rs"] mod error; use error::Error; /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; /// # use pin_init::InPlaceInit; -/// use pin_init::{init, Init, zeroed}; +/// use pin_init::{init, Init, init_zeroed}; /// /// struct BigBuf { /// small: [u8; 1024 * 1024],
@@ -875,7 +875,7 @@ macro_rules! try_pin_init {/// impl BigBuf { /// fn new() -> impl Init<Self> { /// init!(Self { -/// small <- zeroed(), +/// small <- init_zeroed(), /// }) /// } /// }
@@ -913,7 +913,7 @@ macro_rules! init {/// # #![feature(allocator_api)] /// # use core::alloc::AllocError; /// # use pin_init::InPlaceInit; -/// use pin_init::{try_init, Init, zeroed}; +/// use pin_init::{try_init, Init, init_zeroed}; /// /// struct BigBuf { /// big: Box<[u8; 1024 * 1024 * 1024]>,
@@ -923,7 +923,7 @@ macro_rules! init {/// impl BigBuf { /// fn new() -> impl Init<Self, AllocError> { /// try_init!(Self { -/// big: Box::init(zeroed())?, +/// big: Box::init(init_zeroed())?, /// small: [0; 1024 * 1024], /// }? AllocError) /// }
@@ -1170,7 +1170,7 @@ pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {/// /// ```rust /// # #![expect(clippy::disallowed_names)] -/// use pin_init::{init, zeroed, Init}; +/// use pin_init::{init, init_zeroed, Init}; /// /// struct Foo { /// buf: [u8; 1_000_000],
@@ -1183,7 +1183,7 @@ pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {/// } /// /// let foo = init!(Foo { -/// buf <- zeroed() +/// buf <- init_zeroed() /// }).chain(|foo| { /// foo.setup(); /// Ok(())
@@ -1469,7 +1469,7 @@ pub unsafe trait PinnedDrop: __internal::HasPinData {/// this is not UB: /// /// ```rust,ignore -/// let val: Self = unsafe { core::mem::zeroed() }; +/// let val: Self = unsafe { core::mem::init_zeroed() }; /// ``` pub unsafe trait Zeroable {}
@@ -1484,11 +1484,11 @@ pub unsafe trait ZeroableOption {}// SAFETY: by the safety requirement of `ZeroableOption`, this is valid. unsafe impl <T :ZeroableOption >Zeroable for Option <T > {} -/// Create a new zeroed T. +/// Create an initializer for a zeroed `T`. /// /// The returned initializer will write `0x00` to every byte of the given `slot`. #[inline] -pub fn zeroed <T :Zeroable >() ->impl Init <T > { +pub fn init_zeroed <T :Zeroable >() ->impl Init <T > {// SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T` // and because we write all zeroes, the memory is initialized. unsafe {
rust/pin-init/src/macros.rs +8 -8
@@ -1030,7 +1030,7 @@ impl<$($impl_generics)*> $pin_data<$($ty_generics)*>/// /// This macro has multiple internal call configurations, these are always the very first ident: /// - nothing: this is the base case and called by the `{try_}{pin_}init!` macros. -/// - `with_update_parsed`: when the `..Zeroable::zeroed()` syntax has been handled. +/// - `with_update_parsed`: when the `..Zeroable::init_zeroed()` syntax has been handled. /// - `init_slot`: recursively creates the code that initializes all fields in `slot`. /// - `make_initializer`: recursively create the struct initializer that guarantees that every /// field has been initialized exactly once.
@@ -1059,7 +1059,7 @@ macro_rules! __init_internal { @data($data, $($use_data)?), @has_data($has_data, $get_data), @construct_closure($construct_closure), - @zeroed(), // Nothing means default behavior. + @init_zeroed(), // Nothing means default behavior. ) }; (
@@ -1074,7 +1074,7 @@ macro_rules! __init_internal { @has_data($has_data:ident, $get_data:ident), // `pin_init_from_closure` or `init_from_closure`. @construct_closure($construct_closure:ident), - @munch_fields(..Zeroable::zeroed()), + @munch_fields(..Zeroable::init_zeroed()), ) => { $crate::__init_internal!(with_update_parsed : @this($($this)?),
@@ -1084,7 +1084,7 @@ macro_rules! __init_internal { @data($data, $($use_data)?), @has_data($has_data, $get_data), @construct_closure($construct_closure), - @zeroed(()), // `()` means zero all fields not mentioned. + @init_zeroed(()), // `()` means zero all fields not mentioned. ) }; (
@@ -1124,7 +1124,7 @@ macro_rules! __init_internal { @has_data($has_data:ident, $get_data:ident), // `pin_init_from_closure` or `init_from_closure`. @construct_closure($construct_closure:ident), - @zeroed($($init_zeroed:expr)?), + @init_zeroed($($init_zeroed:expr)?), ) => {{// We do not want to allow arbitrary returns, so we declare this type as the `Ok` return // type and shadow it later when we insert the arbitrary user code. That way there will be
@@ -1196,7 +1196,7 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {} @data($data:ident), @slot($slot:ident), @guards($($guards:ident,)*), - @munch_fields($(..Zeroable::zeroed())? $(,)?), + @munch_fields($(..Zeroable::init_zeroed())? $(,)?), ) => {// Endpoint of munching, no fields are left. If execution reaches this point, all fields // have been initialized. Therefore we can now dismiss the guards by forgetting them.
@@ -1300,11 +1300,11 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {} (make_initializer: @slot($slot:ident), @type_name($t:path), - @munch_fields(..Zeroable::zeroed() $(,)?), + @munch_fields(..Zeroable::init_zeroed() $(,)?), @acc($($acc:tt)*), ) => {// Endpoint, nothing more to munch, create the initializer. Since the users specified -// `..Zeroable::zeroed()`, the slot will already have been zeroed and all field that have +// `..Zeroable::init_zeroed()`, the slot will already have been zeroed and all field that have // not been overwritten are thus zero and initialized. We still check that all fields are // actually accessible by using the struct update syntax ourselves. // We are inside of a closure that is never executed and thus we can abuse `slot` to
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 2/13 rust: pin-init: add `Zeroable::init_zeroed`
In reply to Benno LossinThe trait function delegates to the already existing init_zeroed function that returns a zeroing initializer for Self.
The syntax ..Zeroable::init_zeroed() is already used by the initialization macros to initialize all fields that are not mentioned in the initializer with zero. Therefore it is expected that the function also exists on the trait.
--- rust/pin-init/src/lib.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-)
rust/pin-init/src/lib.rs +12 -1
@@ -1471,7 +1471,18 @@ pub unsafe trait PinnedDrop: __internal::HasPinData {/// ```rust,ignore /// let val: Self = unsafe { core::mem::init_zeroed() }; /// ``` -pub unsafe trait Zeroable {} +pub unsafe trait Zeroable { +/// Create a new zeroed `Self`. +/// +/// The returned initializer will write `0x00` to every byte of the given `slot`. +#[inline] +fn init_zeroed () ->impl Init <Self > +where +Self :Sized , + { +init_zeroed () + } +}/// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write /// `None` to that location.
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 3/13 rust: pin-init: add `zeroed()` & `Zeroable::zeroed()` functions
In reply to Benno Lossinzeroed() returns a zeroed out value of a sized type implementing Zeroable.
The function is added as a free standing function, in addition to an associated function on Zeroable, because then it can be marked const (functions in traits can't be const at the moment).
--- rust/pin-init/src/lib.rs | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+)
rust/pin-init/src/lib.rs +52 -0
@@ -1482,6 +1482,33 @@ fn init_zeroed() -> impl Init<Self> {init_zeroed () } + +/// Create a `Self` consisting of all zeroes. +/// +/// Whenever a type implements [`Zeroable`], this function should be preferred over +/// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`. +/// +/// # Examples +/// +/// ``` +/// use pin_init::{Zeroable, zeroed}; +/// +/// #[derive(Zeroable)] +/// struct Point { +/// x: u32, +/// y: u32, +/// } +/// +/// let point: Point = zeroed(); +/// assert_eq!(point.x, 0); +/// assert_eq!(point.y, 0); +/// ``` +fn zeroed () ->Self +where +Self :Sized , + { +zeroed () + } }/// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write
@@ -1510,6 +1537,31 @@ pub fn init_zeroed<T: Zeroable>() -> impl Init<T> { } } +/// Create a `T` consisting of all zeroes. +/// +/// Whenever a type implements [`Zeroable`], this function should be preferred over +/// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`. +/// +/// # Examples +/// +/// ``` +/// use pin_init::{Zeroable, zeroed}; +/// +/// #[derive(Zeroable)] +/// struct Point { +/// x: u32, +/// y: u32, +/// } +/// +/// let point: Point = zeroed(); +/// assert_eq!(point.x, 0); +/// assert_eq!(point.y, 0); +/// ``` +pub const fn zeroed <T :Zeroable >() ->T { +// SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`. +unsafe { core::mem::zeroed () } +} +macro_rules! impl_zeroable { ($($({$($generics:tt)*})? $t:ty, )*) => {// SAFETY: Safety comments written in the macro invocation.
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 4/13 rust: pin-init: implement `ZeroableOption` for `&T` and `&mut T`
In reply to Benno LossinOption<&T> and Option<&mut T> are documented [1] to have the None variant be all zeroes.
--- rust/pin-init/src/lib.rs | 7 +++++++ 1 file changed, 7 insertions(+)
rust/pin-init/src/lib.rs +7 -0
@@ -1522,6 +1522,13 @@ pub unsafe trait ZeroableOption {}// SAFETY: by the safety requirement of `ZeroableOption`, this is valid. unsafe impl <T :ZeroableOption >Zeroable for Option <T > {} +// SAFETY: `Option<&T>` is part of the option layout optimization guarantee: +// <https://doc.rust-lang.org/stable/std/option/index.html#representation>. +unsafe impl <T >ZeroableOption for &T {} +// SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee: +// <https://doc.rust-lang.org/stable/std/option/index.html#representation>. +unsafe impl <T >ZeroableOption for &mut T {} +/// Create an initializer for a zeroed `T`. /// /// The returned initializer will write `0x00` to every byte of the given `slot`.
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 5/13 rust: pin-init: change `impl Zeroable for Option<NonNull<T>>` to `ZeroableOption for NonNull<T>`
In reply to Benno LossinThis brings it in line with references. It too is listed in [1].
--- rust/pin-init/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
rust/pin-init/src/lib.rs +3 -1
@@ -1528,6 +1528,9 @@ unsafe impl<T> ZeroableOption for &T {}// SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee: // <https://doc.rust-lang.org/stable/std/option/index.html#representation>. unsafe impl <T >ZeroableOption for &mut T {} +// SAFETY: `Option<NonNull<T>>` is part of the option layout optimization guarantee: +// <https://doc.rust-lang.org/stable/std/option/index.html#representation>. +unsafe impl <T >ZeroableOption for NonNull <T > {}/// Create an initializer for a zeroed `T`. ///
@@ -1606,7 +1609,6 @@ macro_rules! impl_zeroable { Option<NonZeroU128>, Option<NonZeroUsize>, Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>, Option<NonZeroI128>, Option<NonZeroIsize>, - {<T>} Option<NonNull<T>>,// SAFETY: `null` pointer is valid. //
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 6/13 rust: pin-init: implement `ZeroableOption` for function pointers with up to 20 arguments
In reply to Benno LossinOption<[unsafe] [extern "abi"] fn(...args...) -> ret> is documented
[1] to also have the None variant equal all zeroes.
--- rust/pin-init/src/lib.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
rust/pin-init/src/lib.rs +16 -0
@@ -1638,6 +1638,22 @@ unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*)impl_tuple_zeroable! (A ,B ,C ,D ,E ,F ,G ,H ,I ,J ); +macro_rules! impl_fn_zeroable_option { + ([$($abi:literal),* $(,)?] $args:tt) => { + $(impl_fn_zeroable_option! ({extern $abi} $args);)* + $(impl_fn_zeroable_option! ({unsafe extern $abi} $args);)* + }; + ({$($prefix:tt)*} {$(,)?}) => {}; + ({$($prefix:tt)*} {$ret:ident, $($rest:ident),* $(,)?}) => { +// SAFETY: function pointers are part of the option layout optimization: +// <https://doc.rust-lang.org/stable/std/option/index.html#representation>. +unsafe impl <$ret, $($rest),*>ZeroableOption for $($prefix)*fn ($($rest),*) -> $ret {} +impl_fn_zeroable_option! ({$($prefix)*} {$($rest),*,}); + }; +} + +impl_fn_zeroable_option! (["Rust" ,"C" ] {A ,B ,C ,D ,E ,F ,G ,H ,I ,J ,K ,L ,M ,N ,O ,P ,Q ,R ,S ,T ,U }); +/// This trait allows creating an instance of `Self` which contains exactly one /// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning). ///
base-commit: ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 7/13 rust: add `pin-init` as a dependency to `bindings` and `uapi`
In reply to Benno LossinThis allows bindings and uapi to implement Zeroable and use other items from pin-init.
--- rust/Makefile | 6 ++++-- scripts/generate_rust_analyzer.py | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-)
rust/Makefile +4 -2
@@ -513,17 +513,19 @@ $(obj)/ffi.o: private skip_gendwarfksyms = 1 $(obj)/ffi.o: $(src)/ffi.rs $(obj)/compiler_builtins.o FORCE +$(call if_changed_rule,rustc_library) -$(obj)/bindings.o: private rustc_target_flags = --extern ffi +$(obj)/bindings.o: private rustc_target_flags = --extern ffi --extern pin_init $(obj)/bindings.o: $(src)/bindings/lib.rs \ $(obj)/ffi.o \ + $(obj)/pin_init.o \ $(obj)/bindings/bindings_generated.rs \ $(obj)/bindings/bindings_helpers_generated.rs FORCE +$(call if_changed_rule,rustc_library) -$(obj)/uapi.o: private rustc_target_flags = --extern ffi +$(obj)/uapi.o: private rustc_target_flags = --extern ffi --extern pin_init $(obj)/uapi.o: private skip_gendwarfksyms = 1 $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/ffi.o \ + $(obj)/pin_init.o \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_rule,rustc_library)
scripts/generate_rust_analyzer.py +2 -2
@@ -137,8 +137,8 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): "exclude_dirs": [], } - append_crate_with_generated("bindings", ["core", "ffi"]) - append_crate_with_generated("uapi", ["core", "ffi"]) + append_crate_with_generated("bindings", ["core", "ffi", "pin_init"]) + append_crate_with_generated("uapi", ["core", "ffi", "pin_init"]) append_crate_with_generated("kernel", ["core", "macros", "build_error", "pin_init", "ffi", "bindings", "uapi"]) def is_root_crate(build_file, target):
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 8/13 rust: derive `Zeroable` for all structs & unions generated by bindgen where possible
In reply to Benno LossinUsing the --with-derive-custom-{struct,union} option of bindgen, add #[derive(MaybeZeroable)] to every struct & union. This makes those types implement Zeroable if all their fields implement it.
Sadly bindgen doesn't add custom derives to the __BindgenBitfieldUnit struct. So manually implement Zeroable for that.
--- rust/bindgen_parameters | 4 ++++ rust/bindings/lib.rs | 8 ++++++++ rust/uapi/lib.rs | 2 ++ 3 files changed, 14 insertions(+)
rust/bindgen_parameters +4 -0
@@ -34,3 +34,7 @@ # We use const helpers to aid bindgen, to avoid conflicts when constants are # recognized, block generation of the non-helper constants. --blocklist-item ARCH_SLAB_MINALIGN + +# Structs should implement Zeroable when all of their fields do. +--with-derive-custom-struct .*=MaybeZeroable +--with-derive-custom-union .*=MaybeZeroable
rust/bindings/lib.rs +8 -0
@@ -28,11 +28,19 @@#[allow(clippy::undocumented_unsafe_blocks)] #[cfg_attr( CONFIG_RUSTC_HAS_UNNECESSARY_TRANSMUTES , allow(unnecessary_transmutes))] mod bindings_raw { +use pin_init::{MaybeZeroable ,Zeroable }; +// Manual definition for blocklisted types. type __kernel_size_t =usize ;type __kernel_ssize_t =isize ;type __kernel_ptrdiff_t =isize ; +// `bindgen` doesn't automatically do this, see +// <https://github.com/rust-lang/rust-bindgen/issues/3196> +// +// SAFETY: `__BindgenBitfieldUnit<Storage>` is a newtype around `Storage`. +unsafe impl <Storage >Zeroable for __BindgenBitfieldUnit <Storage >where Storage :Zeroable {} +// Use glob import here to expose all helpers. // Symbols defined within the module will take precedence to the glob import. pub use super ::bindings_helper::*;
rust/uapi/lib.rs +2 -0
@@ -31,4 +31,6 @@type __kernel_ssize_t =isize ;type __kernel_ptrdiff_t =isize ; +use pin_init::MaybeZeroable ; +include! (concat! (env! ("OBJTREE" ),"/rust/uapi/uapi_generated.rs" ));
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 9/13 rust: miscdevice: replace `MaybeUninit::zeroed().assume_init` with `pin_init::zeroed`
In reply to Benno LossinAll types in bindings implement Zeroable if they can, so use pin_init::zeroed instead of relying on unsafe code.
If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
--- rust/kernel/miscdevice.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
rust/kernel/miscdevice.rs +3 -5
@@ -19,7 +19,7 @@ str::CStr, types::{ForeignOwnable, Opaque}, }; -use core::{marker::PhantomData , mem::MaybeUninit , pin::Pin }; +use core::{marker::PhantomData , pin::Pin };/// Options for creating a misc device. #[derive( Copy , Clone )]
@@ -31,8 +31,7 @@ pub struct MiscDeviceOptions {impl MiscDeviceOptions {/// Create a raw `struct miscdev` ready for registration. pub const fn into_raw <T :MiscDevice >(self) -> bindings::miscdevice { -// SAFETY: All zeros is valid for this C type. -let mut result: bindings::miscdevice =unsafe {MaybeUninit ::zeroed ().assume_init () }; +let mut result: bindings::miscdevice = pin_init::zeroed (); result.minor = bindings::MISC_DYNAMIC_MINOR as _ ; result.name = self.name.as_char_ptr (); result.fops =MiscdeviceVTable ::<T >::build ();
@@ -309,8 +308,7 @@ impl<T: MiscDevice> MiscdeviceVTable<T> { }else {None }, -// SAFETY: All zeros is a valid value for `bindings::file_operations`. - ..unsafe {MaybeUninit ::zeroed ().assume_init () } + ..pin_init::zeroed () };const fn build () -> &'static bindings::file_operations {
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 10/13 rust: phy: replace `MaybeUninit::zeroed().assume_init` with `pin_init::zeroed`
In reply to Benno LossinAll types in bindings implement Zeroable if they can, so use pin_init::zeroed instead of relying on unsafe code.
If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
--- rust/kernel/net/phy.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
rust/kernel/net/phy.rs +1 -3
@@ -563,9 +563,7 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable { }else {None }, -// SAFETY: The rest is zeroed out to initialize `struct phy_driver`, -// sets `Option<&F>` to be `None`. - ..unsafe { core::mem::MaybeUninit ::<bindings::phy_driver >::zeroed ().assume_init () } + ..pin_init::zeroed () })) }
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 11/13 rust: block: replace `core::mem::zeroed` with `pin_init::zeroed`
In reply to Benno LossinAll types in bindings implement Zeroable if they can, so use pin_init::zeroed instead of relying on unsafe code.
If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
--- rust/kernel/block/mq/gen_disk.rs | 3 +-- rust/kernel/block/mq/tag_set.rs | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-)
rust/kernel/block/mq/gen_disk.rs +1 -2
@@ -93,8 +93,7 @@ pub fn build<T: Operations>( name: fmt::Arguments<'_>, tagset: Arc<TagSet<T>>, ) -> Result<GenDisk<T>> { -// SAFETY: `bindings::queue_limits` contain only fields that are valid when zeroed. -let mut lim: bindings::queue_limits =unsafe { core::mem::zeroed () }; +let mut lim: bindings::queue_limits = pin_init::zeroed (); lim.logical_block_size = self.logical_block_size; lim.physical_block_size = self.physical_block_size;
rust/kernel/block/mq/tag_set.rs +1 -3
@@ -38,9 +38,7 @@ pub fn new( num_tags: u32, num_maps: u32, ) -> impl PinInit<Self, error::Error> { -// SAFETY: `blk_mq_tag_set` only contains integers and pointers, which -// all are allowed to be 0. -let tag_set: bindings::blk_mq_tag_set =unsafe { core::mem::zeroed () }; +let tag_set: bindings::blk_mq_tag_set = pin_init::zeroed ();let tag_set = core::mem::size_of ::<RequestDataWrapper >() .try_into () .map(|cmd_size| {
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 12/13 rust: of: replace `core::mem::zeroed` with `pin_init::zeroed`
In reply to Benno LossinAll types in bindings implement Zeroable if they can, so use pin_init::zeroed instead of relying on unsafe code.
If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
--- rust/kernel/of.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
rust/kernel/of.rs +1 -3
@@ -30,9 +30,7 @@ impl DeviceId {/// Create a new device id from an OF 'compatible' string. pub const fn new (compatible: &'staticCStr ) ->Self {let src = compatible.as_bytes_with_nul (); -// Replace with `bindings::of_device_id::default()` once stabilized for `const`. -// SAFETY: FFI type is valid to be zero-initialized. -let mut of: bindings::of_device_id =unsafe { core::mem::zeroed () }; +let mut of: bindings::of_device_id = pin_init::zeroed ();// TODO: Use `clone_from_slice` once the corresponding types do match. let mut i =0 ;
Signature · 1 line
2.49.0
Benno Lossin
maintainerPATCH v2 13/13 rust: security: replace `core::mem::zeroed` with `pin_init::zeroed`
In reply to Benno LossinAll types in bindings implement Zeroable if they can, so use pin_init::zeroed instead of relying on unsafe code.
If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
--- rust/kernel/security.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
rust/kernel/security.rs +1 -2
@@ -25,8 +25,7 @@ impl SecurityCtx {/// Get the security context given its id. #[inline] pub fn from_secid (secid:u32 ) ->Result <Self > { -// SAFETY: `struct lsm_context` can be initialized to all zeros. -let mut ctx: bindings::lsm_context =unsafe { core::mem::zeroed () }; +let mut ctx: bindings::lsm_context = pin_init::zeroed ();// SAFETY: Just a C FFI call. The pointer is valid for writes. to_result (unsafe { bindings::security_secid_to_secctx (secid, &mut ctx) })?;
Signature · 1 line
2.49.0
Re: [PATCH v2 01/13] rust: pin-init: rename `zeroed` to `init_zeroed`
In reply to Benno LossinQuoted 193 lines · On Fri, 23 May 2025 16:50:57 +0200 Benno Lossin <[email protected]> wrote:
The name
zeroedis a much better fit for a function that returns the type by-value.Link https://github.com/Rust-for-Linux/pin-init/pull/56/commits/7dbe38682c9725405bab91dcabe9c4d8893d2f5e[ also rename uses in `rust/kernel/init.rs` - Benno]Signed-off-by Benno Lossin <[email protected]>--- rust/kernel/init.rs | 8 +++--- rust/pin-init/README.md | 2 +- rust/pin-init/examples/big_struct_in_place.rs | 4 +-- rust/pin-init/src/lib.rs | 28 +++++++++---------- rust/pin-init/src/macros.rs | 16 +++++------ 5 files changed, 29 insertions(+), 29 deletions(-)rust/kernel/init.rs +4
-4@@ -206,7 +206,7 @@ fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self>/// /// ```rust /// use kernel::error::Error; -/// use pin_init::zeroed; +/// use pin_init::init_zeroed; /// struct BigBuf { /// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], @@ -215,7 +215,7 @@ fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self>/// impl BigBuf { /// fn new() -> impl Init<Self, Error> { /// try_init!(Self { -/// big: KBox::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init_zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// } @@ -264,7 +264,7 @@ macro_rules! try_init {/// ```rust /// # #![feature(new_uninit)] /// use kernel::error::Error; -/// use pin_init::zeroed; +/// use pin_init::init_zeroed; /// #[pin_data] /// struct BigBuf { /// big: KBox<[u8; 1024 * 1024 * 1024]>, @@ -275,7 +275,7 @@ macro_rules! try_init {/// impl BigBuf { /// fn new() -> impl PinInit<Self, Error> { /// try_pin_init!(Self { -/// big: KBox::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init_zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) rust/pin-init/README.md +1
-1@@ -125,7 +125,7 @@ impl DriverData { fn new() -> impl PinInit<Self, Error> { try_pin_init!(Self { status <- CMutex::new(0), - buffer: Box::init(pin_init::zeroed())?, + buffer: Box::init(pin_init::init_zeroed())?, }? Error) } }rust/pin-init/examples/big_struct_in_place.rs +2
-2@@ -21,7 +21,7 @@ pub struct ManagedBuf {impl ManagedBuf {pub fn new () ->impl Init <Self > { -init! (ManagedBuf { buf <-zeroed () }) +init! (ManagedBuf { buf <-init_zeroed () }) } }@@ -30,7 +30,7 @@ fn main() { { // we want to initialize the struct in-place, otherwise we would get a stackoverflow let buf: Box<BigStruct> = Box::init(init!(BigStruct { - buf <- zeroed(), + buf <- init_zeroed(), a: 7, b: 186, c: 7789,rust/pin-init/src/lib.rs +11
-11@@ -148,7 +148,7 @@//! fn new() -> impl PinInit<Self, Error> { //! try_pin_init!(Self { //! status <- CMutex::new(0), -//! buffer: Box::init(pin_init::zeroed())?, +//! buffer: Box::init(pin_init::init_zeroed())?, //! }? Error) //! } //! } @@ -742,7 +742,7 @@ macro_rules! stack_try_pin_init {/// - Fields that you want to initialize in-place have to use `<-` instead of `:`. /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`] /// pointer named `this` inside of the initializer. -/// - Using struct update syntax one can place `..Zeroable::zeroed()` at the very end of the +/// - Using struct update syntax one can place `..Zeroable::init_zeroed()` at the very end of the /// struct, this initializes every field with 0 and then runs all initializers specified in the /// body. This can only be done if [`Zeroable`] is implemented for the struct. /// @@ -769,7 +769,7 @@ macro_rules! stack_try_pin_init {/// }); /// let init = pin_init!(Buf { /// buf: [1; 64], -/// ..Zeroable::zeroed() +/// ..Zeroable::init_zeroed() /// }); /// ``` /// @@ -805,7 +805,7 @@ macro_rules! pin_init {/// ```rust /// # #![feature(allocator_api)] /// # #[path = "../examples/error.rs"] mod error; use error::Error; -/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, zeroed}; +/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, init_zeroed}; /// /// #[pin_data] /// struct BigBuf { @@ -817,7 +817,7 @@ macro_rules! pin_init {/// impl BigBuf { /// fn new() -> impl PinInit<Self, Error> { /// try_pin_init!(Self { -/// big: Box::init(zeroed())?, +/// big: Box::init(init_zeroed())?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -866,7 +866,7 @@ macro_rules! try_pin_init {/// # #[path = "../examples/error.rs"] mod error; use error::Error; /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; /// # use pin_init::InPlaceInit; -/// use pin_init::{init, Init, zeroed}; +/// use pin_init::{init, Init, init_zeroed}; /// /// struct BigBuf { /// small: [u8; 1024 * 1024], @@ -875,7 +875,7 @@ macro_rules! try_pin_init {/// impl BigBuf { /// fn new() -> impl Init<Self> { /// init!(Self { -/// small <- zeroed(), +/// small <- init_zeroed(), /// }) /// } /// } @@ -913,7 +913,7 @@ macro_rules! init {/// # #![feature(allocator_api)] /// # use core::alloc::AllocError; /// # use pin_init::InPlaceInit; -/// use pin_init::{try_init, Init, zeroed}; +/// use pin_init::{try_init, Init, init_zeroed}; /// /// struct BigBuf { /// big: Box<[u8; 1024 * 1024 * 1024]>, @@ -923,7 +923,7 @@ macro_rules! init {/// impl BigBuf { /// fn new() -> impl Init<Self, AllocError> { /// try_init!(Self { -/// big: Box::init(zeroed())?, +/// big: Box::init(init_zeroed())?, /// small: [0; 1024 * 1024], /// }? AllocError) /// } @@ -1170,7 +1170,7 @@ pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {/// /// ```rust /// # #![expect(clippy::disallowed_names)] -/// use pin_init::{init, zeroed, Init}; +/// use pin_init::{init, init_zeroed, Init}; /// /// struct Foo { /// buf: [u8; 1_000_000], @@ -1183,7 +1183,7 @@ pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {/// } /// /// let foo = init!(Foo { -/// buf <- zeroed() +/// buf <- init_zeroed() /// }).chain(|foo| { /// foo.setup(); /// Ok(())
rust/pin-init/src/lib.rs pub unsafe trait PinnedDrop: __internal::HasPinData { · line 1472
Quoted 5 lines
rust/pin-init/src/lib.rs +1
-1@@ -1469,7 +1469,7 @@ pub unsafe trait PinnedDrop: __internal::HasPinData {/// this is not UB: /// /// ```rust,ignore -/// let val: Self = unsafe { core::mem::zeroed() }; +/// let val: Self = unsafe { core::mem::init_zeroed() };
This looks like a find/replace that was a bit too eager :)
Quoted 90 lines
rust/pin-init/src/lib.rs +2
-2/// ``` pub unsafe trait Zeroable {}@@ -1484,11 +1484,11 @@ pub unsafe trait ZeroableOption {}// SAFETY: by the safety requirement of `ZeroableOption`, this is valid. unsafe impl <T :ZeroableOption >Zeroable for Option <T > {} -/// Create a new zeroed T. +/// Create an initializer for a zeroed `T`. /// /// The returned initializer will write `0x00` to every byte of the given `slot`. #[inline] -pub fn zeroed <T :Zeroable >() ->impl Init <T > { +pub fn init_zeroed <T :Zeroable >() ->impl Init <T > {// SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T` // and because we write all zeroes, the memory is initialized. unsafe {rust/pin-init/src/macros.rs +8
-8@@ -1030,7 +1030,7 @@ impl<$($impl_generics)*> $pin_data<$($ty_generics)*>/// /// This macro has multiple internal call configurations, these are always the very first ident: /// - nothing: this is the base case and called by the `{try_}{pin_}init!` macros. -/// - `with_update_parsed`: when the `..Zeroable::zeroed()` syntax has been handled. +/// - `with_update_parsed`: when the `..Zeroable::init_zeroed()` syntax has been handled. /// - `init_slot`: recursively creates the code that initializes all fields in `slot`. /// - `make_initializer`: recursively create the struct initializer that guarantees that every /// field has been initialized exactly once. @@ -1059,7 +1059,7 @@ macro_rules! __init_internal { @data($data, $($use_data)?), @has_data($has_data, $get_data), @construct_closure($construct_closure), - @zeroed(), // Nothing means default behavior. + @init_zeroed(), // Nothing means default behavior. ) }; (@@ -1074,7 +1074,7 @@ macro_rules! __init_internal { @has_data($has_data:ident, $get_data:ident), // `pin_init_from_closure` or `init_from_closure`. @construct_closure($construct_closure:ident), - @munch_fields(..Zeroable::zeroed()), + @munch_fields(..Zeroable::init_zeroed()), ) => { $crate::__init_internal!(with_update_parsed : @this($($this)?),@@ -1084,7 +1084,7 @@ macro_rules! __init_internal { @data($data, $($use_data)?), @has_data($has_data, $get_data), @construct_closure($construct_closure), - @zeroed(()), // `()` means zero all fields not mentioned. + @init_zeroed(()), // `()` means zero all fields not mentioned. ) }; (@@ -1124,7 +1124,7 @@ macro_rules! __init_internal { @has_data($has_data:ident, $get_data:ident), // `pin_init_from_closure` or `init_from_closure`. @construct_closure($construct_closure:ident), - @zeroed($($init_zeroed:expr)?), + @init_zeroed($($init_zeroed:expr)?), ) => {{// We do not want to allow arbitrary returns, so we declare this type as the `Ok` return // type and shadow it later when we insert the arbitrary user code. That way there will be @@ -1196,7 +1196,7 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {} @data($data:ident), @slot($slot:ident), @guards($($guards:ident,)*), - @munch_fields($(..Zeroable::zeroed())? $(,)?), + @munch_fields($(..Zeroable::init_zeroed())? $(,)?), ) => {// Endpoint of munching, no fields are left. If execution reaches this point, all fields // have been initialized. Therefore we can now dismiss the guards by forgetting them. @@ -1300,11 +1300,11 @@ fn assert_zeroable<T: $crate::Zeroable>(_: *mut T) {} (make_initializer: @slot($slot:ident), @type_name($t:path), - @munch_fields(..Zeroable::zeroed() $(,)?), + @munch_fields(..Zeroable::init_zeroed() $(,)?), @acc($($acc:tt)*), ) => {// Endpoint, nothing more to munch, create the initializer. Since the users specified -// `..Zeroable::zeroed()`, the slot will already have been zeroed and all field that have +// `..Zeroable::init_zeroed()`, the slot will already have been zeroed and all field that have // not been overwritten are thus zero and initialized. We still check that all fields are // actually accessible by using the struct update syntax ourselves. // We are inside of a closure that is never executed and thus we can abuse `slot` to
Quoted 6 lines
base-commit:
ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]
prerequisite-patch-id: https://lore.kernel.org/all/[email protected]Signature · 1 line
2.49.0
Benoît du Garreau
Benno Lossin
maintainerRe: [PATCH v2 01/13] rust: pin-init: rename `zeroed` to `init_zeroed`
Quoted 9 lines · Benoît du Garreau
rust/pin-init/src/lib.rs pub unsafe trait PinnedDrop: __internal::HasPinData { · line 1472
Quoted 6 lines · On Fri, 23 May 2025 16:50:57 +0200 Benno Lossin <[email protected]> wrote:
rust/pin-init/src/lib.rs +1
-1@@ -1469,7 +1469,7 @@ pub unsafe trait PinnedDrop: __internal::HasPinData {/// this is not UB: /// /// ```rust,ignore -/// let val: Self = unsafe { core::mem::zeroed() }; +/// let val: Self = unsafe { core::mem::init_zeroed() }; This looks like a find/replace that was a bit too eager :)
Oh yeah! Thanks for spotting this!
---
Cheers,
Benno
Benno Lossin
maintainerQuoted 69 lines · Benno Lossin
Depends on the pin-init test & CI fixes sync [1].
This came from a discussion at [2]. And I added some more useful parts to the original idea.
I'm not sure on the impact of build times and rust-analyzer. We're adding a derive macro to every struct and union emitted by bindgen. Building using my test-config took 27.7s before and 28.2s after this change, but those are only two runs on my machine with a very reduced config (that enables all Rust code that we have at the moment).
Maybe we have to reevaluate this when more C code is scanned by bindgen.
[1]: https://rust-for-linux.zulipchat.com/#narrow/channel/291565-Help/topic/Zeroable.20trait.20for.20C.20structs/with/509711564
[2]: https://lore.kernel.org/all/[email protected]Changelog
=========
* v2:
- added patches with more extensive pin-init changes toZeroable& related methods. for the upstream PR, see
https://github.com/Rust-for-Linux/pin-init/pull/56
- added patches replacing usage ofmem::zeroedandMaybeUninit::zeroed().assume_init()with the newpin_init::zeroed
- fix rust-analyzer support
- use import in{uapi,bindings}/lib.rsto avoid thepin_init::prefix
* v1: https://lore.kernel.org/all/[email protected]Benno Lossin (13):
rust: pin-init: renamezeroedtoinit_zeroed
rust: pin-init: addZeroable::init_zeroed
rust: pin-init: addzeroed()&Zeroable::zeroed()functions
rust: pin-init: implementZeroableOptionfor&Tand&mut T
rust: pin-init: changeimpl Zeroable for Option<NonNull<T>>to
ZeroableOption for NonNull<T>
rust: pin-init: implementZeroableOptionfor function pointers with
up to 20 arguments
rust: addpin-initas a dependency tobindingsanduapi
rust: deriveZeroablefor all structs & unions generated by bindgen
where possible
rust: miscdevice: replaceMaybeUninit::zeroed().assume_initwith`pin_init::zeroed` rust: phy: replace `MaybeUninit::zeroed().assume_init` with `pin_init::zeroed`rust: block: replace
core::mem::zeroedwithpin_init::zeroed
rust: of: replacecore::mem::zeroedwithpin_init::zeroed
rust: security: replacecore::mem::zeroedwithpin_init::zeroedrust/Makefile | 6 +- rust/bindgen_parameters | 4 + rust/bindings/lib.rs | 8 ++ rust/kernel/block/mq/gen_disk.rs | 3 +- rust/kernel/block/mq/tag_set.rs | 4 +- rust/kernel/init.rs | 8 +- rust/kernel/miscdevice.rs | 8 +- rust/kernel/net/phy.rs | 4 +- rust/kernel/of.rs | 4 +- rust/kernel/security.rs | 3 +- rust/pin-init/README.md | 2 +- rust/pin-init/examples/big_struct_in_place.rs | 4 +- rust/pin-init/src/lib.rs | 120 +++++++++++++++--- rust/pin-init/src/macros.rs | 16 +-- rust/uapi/lib.rs | 2 + scripts/generate_rust_analyzer.py | 4 +- 16 files changed, 147 insertions(+), 53 deletions(-)
Quoted 4 lines
base-commit:
ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id:8d7ade67c2e5189bf8a2c91253d925e25744cba5
prerequisite-patch-id:0ebbd4a86bebeff23257870db92a1b0fe017c481
prerequisite-patch-id:1437fc7adeff6e13abd433594da923272b9388bf
Applied the first 6 patches to pin-init-next -- thanks everyone!
[ fix wrong replacement of mem::zeroed in the definition of `trait
Zeroable` - Benno ]
---
Cheers,
Benno
Benno Lossin
maintainerQuoted 70 lines · Benno Lossin
Quoted 69 lines · Benno Lossin
Depends on the pin-init test & CI fixes sync [1].
This came from a discussion at [2]. And I added some more useful parts to the original idea.
I'm not sure on the impact of build times and rust-analyzer. We're adding a derive macro to every struct and union emitted by bindgen. Building using my test-config took 27.7s before and 28.2s after this change, but those are only two runs on my machine with a very reduced config (that enables all Rust code that we have at the moment).
Maybe we have to reevaluate this when more C code is scanned by bindgen.
[1]: https://rust-for-linux.zulipchat.com/#narrow/channel/291565-Help/topic/Zeroable.20trait.20for.20C.20structs/with/509711564
[2]: https://lore.kernel.org/all/[email protected]Changelog
=========
* v2:
- added patches with more extensive pin-init changes toZeroable& related methods. for the upstream PR, see
https://github.com/Rust-for-Linux/pin-init/pull/56
- added patches replacing usage ofmem::zeroedandMaybeUninit::zeroed().assume_init()with the newpin_init::zeroed
- fix rust-analyzer support
- use import in{uapi,bindings}/lib.rsto avoid thepin_init::prefix
* v1: https://lore.kernel.org/all/[email protected]Benno Lossin (13):
rust: pin-init: renamezeroedtoinit_zeroed
rust: pin-init: addZeroable::init_zeroed
rust: pin-init: addzeroed()&Zeroable::zeroed()functions
rust: pin-init: implementZeroableOptionfor&Tand&mut T
rust: pin-init: changeimpl Zeroable for Option<NonNull<T>>to
ZeroableOption for NonNull<T>
rust: pin-init: implementZeroableOptionfor function pointers with
up to 20 arguments
rust: addpin-initas a dependency tobindingsanduapi
rust: deriveZeroablefor all structs & unions generated by bindgen
where possible
rust: miscdevice: replaceMaybeUninit::zeroed().assume_initwith`pin_init::zeroed` rust: phy: replace `MaybeUninit::zeroed().assume_init` with `pin_init::zeroed`rust: block: replace
core::mem::zeroedwithpin_init::zeroed
rust: of: replacecore::mem::zeroedwithpin_init::zeroed
rust: security: replacecore::mem::zeroedwithpin_init::zeroedrust/Makefile | 6 +- rust/bindgen_parameters | 4 + rust/bindings/lib.rs | 8 ++ rust/kernel/block/mq/gen_disk.rs | 3 +- rust/kernel/block/mq/tag_set.rs | 4 +- rust/kernel/init.rs | 8 +- rust/kernel/miscdevice.rs | 8 +- rust/kernel/net/phy.rs | 4 +- rust/kernel/of.rs | 4 +- rust/kernel/security.rs | 3 +- rust/pin-init/README.md | 2 +- rust/pin-init/examples/big_struct_in_place.rs | 4 +- rust/pin-init/src/lib.rs | 120 +++++++++++++++--- rust/pin-init/src/macros.rs | 16 +-- rust/uapi/lib.rs | 2 + scripts/generate_rust_analyzer.py | 4 +- 16 files changed, 147 insertions(+), 53 deletions(-)
Quoted 6 lines
Quoted 4 lines
base-commit:
ae8b3a83fb9de394f609035041cd7a668fda2ab3
prerequisite-patch-id:8d7ade67c2e5189bf8a2c91253d925e25744cba5
prerequisite-patch-id:0ebbd4a86bebeff23257870db92a1b0fe017c481
prerequisite-patch-id:1437fc7adeff6e13abd433594da923272b9388bfApplied the first 6 patches to pin-init-next -- thanks everyone!
@Miguel, I guess this flew under the radar for v6.17, or did you have a reason to not pick it?
---
Cheers,
Benno
Quoted 3 lines · Benno Lossin
@Miguel, I guess this flew under the radar for v6.17, or did you have a reason to not pick it?
I had it marked as applied in the spreadsheet -- I didn't notice you expected them to be picked as-is next cycle, sorry.
Since there were no other comments nor Acked-bys, I guess it flew under the radar for others too. So I would suggest re-submitting the remaining ones rebased as soon as -rc1 is out, and we go from there.
Thanks for the ping!
Cheers,
Miguel
Benno Lossin
maintainerQuoted 7 lines · Miguel Ojeda
Quoted 3 lines · Benno Lossin
@Miguel, I guess this flew under the radar for v6.17, or did you have a reason to not pick it?
I had it marked as applied in the spreadsheet -- I didn't notice you expected them to be picked as-is next cycle, sorry.
Ah my understanding was that I pick the first 6 patches and you would pick the rest. I didn't look at the spreadsheet :)
Quoted 3 lines
Since there were no other comments nor Acked-bys, I guess it flew under the radar for others too. So I would suggest re-submitting the remaining ones rebased as soon as -rc1 is out, and we go from there.
Yeah will send them, but probably in 2 weeks-ish.
---
Cheers,
Benno
Quoted 2 lines · Benno Lossin
Yeah will send them, but probably in 2 weeks-ish.
Yeah, -rc1 is at least 2 weeks into the future, so no rush/worries.
Thanks!
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v2 03/13] rust: pin-init: add `zeroed()` & `Zeroable::zeroed()` functions
In reply to Benno LossinQuoted 6 lines · Benno Lossin
zeroed()returns a zeroed out value of a sized type implementingZeroable.The function is added as a free standing function, in addition to an associated function on
Zeroable, because then it can be markedconst(functions in traits can't be const at the moment).
Do you want to add a note on this in the code, so we can const the trait function and let go of the other one if it becomes possible in the future?
Best regards,
Andreas Hindborg
Re: [PATCH v2 11/13] rust: block: replace `core::mem::zeroed` with `pin_init::zeroed`
In reply to Benno LossinQuoted 8 lines · Benno Lossin
All types in
bindingsimplementZeroableif they can, so usepin_init::zeroedinstead of relying onunsafecode.If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
Signed-off-by Benno Lossin <[email protected]>---
Best regards,
Andreas Hindborg
Benno Lossin
maintainerRe: [PATCH v2 11/13] rust: block: replace `core::mem::zeroed` with `pin_init::zeroed`
Quoted 5 lines · Andreas Hindborg
Quoted 3 lines · Benno Lossin
All types in
bindingsimplementZeroableif they can, so usepin_init::zeroedinstead of relying onunsafecode.
Quoted 7 lines
Quoted 5 lines
If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
Signed-off-by Benno Lossin <[email protected]>---
Acked-by Andreas Hindborg <[email protected]>
Thanks, this one was already picked & the PR that included it contains your Acked-by (it couldn't be rebased since I noticed it too late). Let me know if you need any pointers.
---
Cheers,
Benno
Andreas Hindborg
maintainerRe: [PATCH v2 11/13] rust: block: replace `core::mem::zeroed` with `pin_init::zeroed`
Quoted 9 lines · Benno Lossin
Quoted 8 lines · Andreas Hindborg
Quoted 6 lines · Benno Lossin
All types in
bindingsimplementZeroableif they can, so usepin_init::zeroedinstead of relying onunsafecode.If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Signed-off-by Benno Lossin <[email protected]>---
Acked-by Andreas Hindborg <[email protected]>Thanks, this one was already picked & the PR that included it contains your Acked-by (it couldn't be rebased since I noticed it too late). Let me know if you need any pointers.
Right, I remember now that you point it out. It's just because I got a new fancy email filter (lei q dfn:...). Hopefully I will miss fewer of these in the future.
Best regards,
Andreas Hindborg
Benno Lossin
maintainerRe: [PATCH v2 11/13] rust: block: replace `core::mem::zeroed` with `pin_init::zeroed`
Quoted 16 lines · Andreas Hindborg
Quoted 14 lines · Benno Lossin
Quoted 12 lines · Andreas Hindborg
Quoted 8 lines · Benno Lossin
All types in
bindingsimplementZeroableif they can, so usepin_init::zeroedinstead of relying onunsafecode.If this ends up not compiling in the future, something in bindgen or on the C side changed and is most likely incorrect.
Signed-off-by Benno Lossin <[email protected]>---
Acked-by Andreas Hindborg <[email protected]>
Quoted 7 lines
Quoted 3 lines
Thanks, this one was already picked & the PR that included it contains your Acked-by (it couldn't be rebased since I noticed it too late). Let me know if you need any pointers.
Right, I remember now that you point it out. It's just because I got a new fancy email filter (lei q dfn:...). Hopefully I will miss fewer of these in the future.
That's nice and no worries, I should have pinged you before applying :)
---
Cheers,
Benno
Benno Lossin
maintainerRe: [PATCH v2 03/13] rust: pin-init: add `zeroed()` & `Zeroable::zeroed()` functions
In reply to Andreas HindborgQuoted 5 lines · Andreas Hindborg
Quoted 3 lines · Benno Lossin
zeroed()returns a zeroed out value of a sized type implementingZeroable.
Quoted 7 lines
Quoted 3 lines
The function is added as a free standing function, in addition to an associated function on
Zeroable, because then it can be markedconst(functions in traits can't be const at the moment).Do you want to add a note on this in the code, so we can const the trait function and let go of the other one if it becomes possible in the future?
I'll create an issue instead (the commit is already merged).
---
Cheers,
Benno