rust: pin-init: merge `__init` and `__pinned_init`
Subsystems (10)
Gary Guo
maintainercover rust: pin-init: merge `__init` and `__pinned_init`
Currently we have PinInit::__pinned_init and Init::__init which has slightly different safety requirement but are required to do the same thing. Instead of having to duplicate impl everywhere, it's simpler to just use Init as a marker trait that cancels out the pinning requirement on PinInit::__pinned_init. This also simplifies code (and shorten the symbol name) so __init can always be used.
Note that to pull off this change it needs a stage approach. The plan is:
* Patch 1 (the __pinned_init and __init merge) is to be taken this cycle through pin-init tree; this preserves the __pinned_init method as an alias for compatibility.
* Patch 2 can be taken via driver-core this cycle.
* Patch 3 (tree-wide changes) to be taken next cycle. I can split this further up next cycle so this can be routed via various subsystems.
* Patch 4 (removal of __pinned_init) is to be taken via pin-init two cycles after.
---
This might be an opportunity to rethink about the API. IIRC we use __init initially to avoid conflicts because we have the blanket impl on T and Result<T, E>.
Maybe we should get rid of the underscores and name it something more proper, like init_ptr, or maybe add an extension trait to raw pointers type so you can do
unsafe { raw_ptr.init(something_that_impls_pin_init) }?
To: Benno Lossin <[email protected]>
To: Miguel Ojeda <[email protected]>
To: Boqun Feng <[email protected]>
To: Björn Roy Baron <[email protected]>
To: Andreas Hindborg <[email protected]>
To: Alice Ryhl <[email protected]>
To: Trevor Gross <[email protected]>
To: Danilo Krummrich <[email protected]>
To: Daniel Almeida <[email protected]>
To: Tamir Duberstein <[email protected]>
To: Alexandre Courbot <[email protected]>
To: Onur Özkan <[email protected]>
---
Gary Guo (4):
rust: pin-init: merge __pinned_init and __init
rust: devres: use cast_pin_init instead of manual reimplementation
rust: treewide: replace __pinned_init with __init
rust: pin-init: remove __pinned_init method for cfg(kernel)
rust/kernel/alloc/kbox.rs | 6 +- rust/kernel/devres.rs | 6 +- rust/kernel/drm/device.rs | 2 +- rust/kernel/drm/gpuvm/va.rs | 2 +- rust/kernel/drm/gpuvm/vm_bo.rs | 2 +- rust/kernel/init.rs | 10 +-- rust/kernel/pwm.rs | 2 +- rust/kernel/sync/arc.rs | 4 +- rust/kernel/types.rs | 2 +- rust/macros/module.rs | 2 +- rust/pin-init/examples/mutex.rs | 2 +- rust/pin-init/examples/static_init.rs | 9 +-- rust/pin-init/src/__internal.rs | 8 +- rust/pin-init/src/alloc.rs | 6 +- rust/pin-init/src/lib.rs | 147 ++++++++++++++-------------------- 15 files changed, 85 insertions(+), 125 deletions(-)
---
base-commit: b4515cf4156356e8f4fe6e0fdc17f59adab9772f
change-id: 20260722-merge-init-3ed98519ec7f
Best regards,
Signature · 1 line
Gary Guo <[email protected]>
Gary Guo
maintainerPATCH 1/4 rust: pin-init: merge `__pinned_init` and `__init`
These functions have the same requirements and are also required to execute the same code. Prevent duplication by merging them to the single function and document the additional relaxation of Init::__init on both the merged function and the safety requirement of Init.
The existing __pinned_init function is deprecated and kept for compatibility for existing users. For cfg(kernel), it is soft-deprecated for now and will be removed when all users are migrated.
--- rust/pin-init/examples/mutex.rs | 2 +- rust/pin-init/examples/static_init.rs | 9 +-- rust/pin-init/src/__internal.rs | 8 +- rust/pin-init/src/alloc.rs | 6 +- rust/pin-init/src/lib.rs | 146 +++++++++++++--------------------- 5 files changed, 68 insertions(+), 103 deletions(-)
rust/pin-init/examples/mutex.rs +1 -1
@@ -81,7 +81,7 @@ pub fn new(val: impl PinInit<T>) -> impl PinInit<Self> { locked: Cell::new(false), data <-unsafe {pin_init_from_closure (|slot: *mut UnsafeCell <T >| { - val.__pinned_init (slot.cast ::<T >()) + val.__init (slot.cast ::<T >()) }) }, })
rust/pin-init/examples/static_init.rs +3 -6
@@ -59,7 +59,7 @@ fn deref(&self) -> &Self::Target {println! ("doing init" );let ptr = self.cell.get ().cast ::<T >();match self.init.take () { -Some (f) =>unsafe { f.__pinned_init (ptr).unwrap () }, +Some (f) =>unsafe { f.__init (ptr).unwrap () },None =>unsafe { core::hint::unreachable_unchecked () }, } self.present.set (true );
@@ -71,13 +71,10 @@ fn deref(&self) -> &Self::Target {pub struct CountInit ;unsafe impl PinInit <CMutex <usize >>for CountInit { -unsafe fn __pinned_init ( - self, - slot: *mut CMutex <usize >, - ) ->Result <(), core::convert::Infallible > { +unsafe fn __init (self, slot: *mut CMutex <usize >) ->Result <(), core::convert::Infallible > {let init =CMutex ::new (0 ); std::thread::sleep (std::time::Duration ::from_millis (1000 )); -unsafe { init.__pinned_init (slot) } +unsafe { init.__init (slot) } } }
rust/pin-init/src/__internal.rs +4 -4
@@ -181,7 +181,7 @@ pub fn init<E>(self: Pin<&mut Self>, init: impl PinInit<T, E>) -> Result<Pin<&muunsafe { this.value.assume_init_drop () }; }// SAFETY: The memory slot is valid and this type ensures that it will stay pinned. -unsafe { init.__pinned_init (this.value.as_mut_ptr ())? }; +unsafe { init.__init (this.value.as_mut_ptr ())? };// INVARIANT: `this.value` is initialized above. this.is_init =true ;// SAFETY: The slot is now pinned, since we will never give access to `&mut T`.
@@ -289,7 +289,7 @@ pub fn init<E>(self, init: impl PinInit<T, E>) -> Result<DropGuard<Pinned, T>, E// - when `Err` is returned, we also propagate the error without touching `ptr`; // also `self` is consumed so it cannot be touched further. // - the drop guard will not hand out `&mut` (only `Pin<&mut T>`). -unsafe { init.__pinned_init (self.ptr)? }; +unsafe { init.__init (self.ptr)? };// SAFETY: // - `self.ptr` is valid, properly aligned and pinned per type invariant.
@@ -396,9 +396,9 @@ fn default() -> Self { } } -// SAFETY: `__pinned_init` always fails, which is always okay. +// SAFETY: `__init` always fails, which is always okay. unsafe impl <T : ?Sized >PinInit <T , ()>for AlwaysFail <T > { -unsafe fn __pinned_init (self, _slot: *mut T ) ->Result <(), ()> { +unsafe fn __init (self, _slot: *mut T ) ->Result <(), ()> {Err (()) } }
rust/pin-init/src/alloc.rs +3 -3
@@ -38,7 +38,7 @@ fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>fn pin_init (init:impl PinInit <T >) ->Result <Pin <Self >,AllocError > {// SAFETY: We delegate to `init` and only change the error type. let init =unsafe { -pin_init_from_closure (|slot|match init.__pinned_init (slot) { +pin_init_from_closure (|slot|match init.__init (slot) {Ok (()) =>Ok (()),Err (i) =>match i {}, })
@@ -109,7 +109,7 @@ fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E>let slot = slot.as_mut_ptr ();// SAFETY: When init errors/panics, slot will get deallocated but not dropped, // slot is valid and will not be moved, because we pin it later. -unsafe { init.__pinned_init (slot)? }; +unsafe { init.__init (slot)? };// SAFETY: All fields have been initialized and this is the only `Arc` to that data. Ok (unsafe {Pin ::new_unchecked (this.assume_init ()) }) }
@@ -149,7 +149,7 @@ fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Inilet slot = self.as_mut_ptr ();// SAFETY: When init errors/panics, slot will get deallocated but not dropped, // slot is valid and will not be moved, because we pin it later. -unsafe { init.__pinned_init (slot)? }; +unsafe { init.__init (slot)? };// SAFETY: All fields have been initialized. Ok (unsafe { self.assume_init () }.into ()) }
rust/pin-init/src/lib.rs +57 -89
280 lines not on this page · raw message
Signature · 1 line
2.54.0
Gary Guo
maintainerPATCH 2/4 rust: devres: use `cast_pin_init` instead of manual reimplementation
In reply to Gary GuoRemove the manual type-casting which is already available as cast_pin_init.
--- rust/kernel/devres.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-)
rust/kernel/devres.rs +1 -5
@@ -435,11 +435,7 @@ pub unsafe fn new<'a, E>(// SAFETY: The caller guarantees the data is valid for the device's full bound scope. // Lifetimes do not affect layout, so F::Of<'a> and F::Of<'static> have identical // representation; casting the slot pointer is sound. -let data =unsafe { - pin_init::pin_init_from_closure ::<F ::Of <'static>,E >(move |slot| { - data.__pinned_init (slot.cast ()) - }) - }; +let data =unsafe { pin_init::cast_pin_init (data) };Ok (Self (Devres ::new (dev, data)?)) }
Signature · 1 line
2.54.0
Gary Guo
maintainerPATCH 3/4 rust: treewide: replace `__pinned_init` with `__init`
In reply to Gary GuoThe __pinned_init is being merged with __init and is soft-deprecated and is to be removed. Replace the users with __init.
--- rust/kernel/alloc/kbox.rs | 6 +++--- rust/kernel/drm/device.rs | 2 +- rust/kernel/drm/gpuvm/va.rs | 2 +- rust/kernel/drm/gpuvm/vm_bo.rs | 2 +- rust/kernel/init.rs | 10 ++++------ rust/kernel/pwm.rs | 2 +- rust/kernel/sync/arc.rs | 4 ++-- rust/kernel/types.rs | 2 +- rust/macros/module.rs | 2 +- 9 files changed, 15 insertions(+), 17 deletions(-)
rust/kernel/alloc/kbox.rs +3 -3
@@ -372,13 +372,13 @@ pub fn pin_slice<Func, Item, E>(// - `ptr` is a valid pointer to uninitialized memory. // - `ptr` is not used if an error is returned. // - `ptr` won't be moved until it is dropped, i.e. it is pinned. -unsafe {init (i).__pinned_init (ptr)? }; +unsafe {init (i).__init (ptr)? };// SAFETY: // - `i + 1 <= len`, hence we don't exceed the capacity, due to the call to // `with_capacity()` above. // - The new value at index buffer.len() + 1 is the only element being added here, and -// it has been initialized above by `init(i).__pinned_init(ptr)`. +// it has been initialized above by `init(i).__init(ptr)`. unsafe { buffer.inc_len (1 ) }; }
@@ -473,7 +473,7 @@ fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Inilet slot = self.as_mut_ptr ();// SAFETY: When init errors/panics, slot will get deallocated but not dropped, // slot is valid and will not be moved, because we pin it later. -unsafe { init.__pinned_init (slot)? }; +unsafe { init.__init (slot)? };// SAFETY: All fields have been initialized. Ok (unsafe {Box ::assume_init (self) }.into ()) }
rust/kernel/drm/device.rs +1 -1
@@ -239,7 +239,7 @@ pub fn new(// SAFETY: // - `raw_data` is a valid pointer to uninitialized memory. // - `raw_data` will not move until it is dropped. -unsafe { data.__pinned_init (raw_data) }.inspect_err (|_| { +unsafe { data.__init (raw_data) }.inspect_err (|_| {// SAFETY: `__drm_dev_alloc()` was successful, hence `drm_dev` must be valid and the // refcount must be non-zero. unsafe { bindings::drm_dev_put (drm_dev) };
rust/kernel/drm/gpuvm/va.rs +1 -1
@@ -124,7 +124,7 @@ pub fn new(flags: AllocFlags) -> Result<GpuVaAlloc<T>, AllocError> {pub (super )fn prepare (mut self, va_data:impl PinInit <T ::VaData >) -> *mut bindings::drm_gpuva {let va_ptr =MaybeUninit ::as_mut_ptr (&mut self.0 );// SAFETY: The `data` field is pinned. -let Ok (()) =unsafe { va_data.__pinned_init (&raw mut (*va_ptr).data) }; +let Ok (()) =unsafe { va_data.__init (&raw mut (*va_ptr).data) };KBox ::into_raw (self.0 ).cast () } }
rust/kernel/drm/gpuvm/vm_bo.rs +1 -1
@@ -190,7 +190,7 @@ pub(super) fn new( };let ptr =NonNull ::new (raw_ptr).ok_or (AllocError )?;// SAFETY: `ptr->data` is a valid pinned location. -let Ok (()) =unsafe { value.__pinned_init (&raw mut (*raw_ptr).data) }; +let Ok (()) =unsafe { value.__init (&raw mut (*raw_ptr).data) };// INVARIANTS: We just created the vm_bo so it's absent from lists, and the data is valid // as we just initialized it. Ok (GpuVmBoAlloc (ptr))
rust/kernel/init.rs +4 -6
@@ -157,9 +157,8 @@ fn pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> error::Result<Self::Pi Error: From<E>, {// SAFETY: We delegate to `init` and only change the error type. -let init =unsafe { -pin_init_from_closure (|slot| init.__pinned_init (slot).map_err (|e|Error ::from (e))) - }; +let init = +unsafe {pin_init_from_closure (|slot| init.__init (slot).map_err (|e|Error ::from (e))) };Self ::try_pin_init (init, flags) }
@@ -175,9 +174,8 @@ fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self> Error: From<E>, {// SAFETY: We delegate to `init` and only change the error type. -let init =unsafe { -init_from_closure (|slot| init.__pinned_init (slot).map_err (|e|Error ::from (e))) - }; +let init = +unsafe {init_from_closure (|slot| init.__init (slot).map_err (|e|Error ::from (e))) };Self ::try_init (init, flags) } }
rust/kernel/pwm.rs +1 -1
@@ -600,7 +600,7 @@ pub fn new<'a>(let drvdata_ptr =unsafe { bindings::pwmchip_get_drvdata (c_chip_ptr) };// SAFETY: We construct the `T` object in-place in the allocated private memory. -unsafe { data.__pinned_init (drvdata_ptr.cast ()) }.inspect_err (|_| { +unsafe { data.__init (drvdata_ptr.cast ()) }.inspect_err (|_| {// SAFETY: It is safe to call `pwmchip_put()` with a valid pointer obtained // from `pwmchip_alloc()`. We will not use pointer after this. unsafe { bindings::pwmchip_put (c_chip_ptr) }
rust/kernel/sync/arc.rs +2 -2
@@ -727,7 +727,7 @@ fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Inilet slot = self.as_mut_ptr ();// SAFETY: When init errors/panics, slot will get deallocated but not dropped, // slot is valid and will not be moved, because we pin it later. -unsafe { init.__pinned_init (slot)? }; +unsafe { init.__init (slot)? };// SAFETY: All fields have been initialized. Ok (unsafe { self.assume_init () }.into ()) }
@@ -810,7 +810,7 @@ pub fn pin_init_with<E>( ) -> core::result::Result<Pin<UniqueArc<T>>, E> {// SAFETY: The supplied pointer is valid for initialization and we will later pin the value // to ensure it does not move. -match unsafe { init.__pinned_init (self.as_mut_ptr ()) } { +match unsafe { init.__init (self.as_mut_ptr ()) } {// SAFETY: Initialization completed successfully. Ok (()) =>Ok (unsafe { self.assume_init () }.into ()),Err (err) =>Err (err),
rust/kernel/types.rs +1 -1
@@ -426,7 +426,7 @@ fn pin_init<E>(slot: impl PinInit<T, E>) -> impl PinInit<Self, E> {// - `ptr` is a valid pointer to uninitialized memory, // - `slot` is not accessed on error, // - `slot` is pinned in memory. -unsafe {PinInit ::<T ,E >::__pinned_init (slot, ptr) } +unsafe {PinInit ::<T ,E >::__init (slot, ptr) } }) } }
rust/macros/module.rs +1 -1
@@ -622,7 +622,7 @@ unsafe fn __init() -> ::kernel::ffi::c_int {// SAFETY: No data race, since `__MOD` can only be accessed by this module // and there only `__init` and `__exit` access it. These functions are only // called once and `__exit` cannot be called before or during `__init`. -match unsafe { initer.__pinned_init (__MOD.as_mut_ptr ()) } { +match unsafe { initer.__init (__MOD.as_mut_ptr ()) } {Ok (m) =>0 ,Err (e) => e.to_errno (), }
Signature · 1 line
2.54.0
Re: [PATCH 3/4] rust: treewide: replace `__pinned_init` with `__init`
Quoted 4 lines · Gary Guo
rust/kernel/alloc/kbox.rs | 6 +++--- rust/kernel/drm/device.rs | 2 +- rust/kernel/drm/gpuvm/va.rs | 2 +- rust/kernel/drm/gpuvm/vm_bo.rs | 2 +-
Gary Guo
maintainerPATCH 4/4 rust: pin-init: remove `__pinned_init` method for `cfg(kernel)`
In reply to Gary GuoRemove __pinned_init for kernel configuration, with all users gone. Still perserve it temporarily as deprecated so other users have time to move off it.
--- rust/pin-init/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
rust/pin-init/src/lib.rs +2 -1
@@ -917,7 +917,8 @@ pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {/// /// Same as `__init`. #[inline(always)] -#[cfg_attr(not(kernel), deprecated = "use `__init` instead" )] +#[cfg(not(kernel))] +#[deprecated = "use `__init` instead" ] unsafe fn __pinned_init (self, slot: *mut T ) ->Result <(),E > {// SAFETY: Per safety requirement. unsafe { self.__init (slot) }
Signature · 1 line
2.54.0
Re: (subset) [PATCH 0/4] rust: pin-init: merge `__init` and `__pinned_init`
In reply to Gary GuoQuoted 1 line · Gary Guo
[PATCH 0/4] rust: pin-init: merge
__initand__pinned_init
Applied, thanks!
Branch: driver-core-testing
Tree: git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
[2/4] rust: devres: use cast_pin_init instead of manual reimplementation
commit: a1f1b3b478b4
The patch will appear in the next linux-next integration (typically within 24 hours on weekdays).
The patch is in the driver-core-testing branch and will be promoted to driver-core-next after validation.