rust: add `Ownable` trait and `Owned` type
Subsystems (23)
Andreas Hindborg
maintainerv18 cover rust: add `Ownable` trait and `Owned` type
Add a new trait Ownable and type Owned for types that specify their own way of performing allocation and destruction. This is useful for types from the C side.
Implement ForeignOwnable for Owned.
Convert Page to be Ownable and add a from_raw method.
Add the trait OwnableRefCounted that allows conversion between ARef and Owned. This is analogous to conversion between Arc and UniqueArc.
Patches 1-4 implement Ownable and applies it to Page. These patches can be merged on their own.
Patches 5-7 add Ownable -> ARef interop and can be merged later if consensus on their shape cannot be reached.
---
Changes in v18:
- Rebase on rust-next (2026-06-24).
- Drop the 'static bound on ForeignOwnable for Owned (Gary).
- Make Ownable::release take a raw pointer instead of &mut self (Alice, Sashiko).
- Drop types::ARef re-export (Alice).
- Drop unneeded #[repr(transparent)] on Owned (Gary).
- Fix FOREIGN_ALIGN for Owned to report the pointee alignment (Sashiko).
- Remove BorrowedPage; use &Page directly (Alice).
- Update Rust Binder for the Owned<Page> conversion (Alice).
- Update pwm.rs for the RefCounted/AlwaysRefCounted split (Sashiko).
- Fix documentation nits: missing // INVARIANT: comments, stale Page docs, and a stray mut (Sashiko).
- Expand the use statements touched by the rename patch to the multi-line style (Onur).
- Link to v17: https://msgid.link/[email protected]
Changes in v17:
- Rebase on v7.1-rc2.
- Reorder patches so that Ownable can merge without OwnableRefCounted (Alice).
- Add #[inline] directives to short functions added by the series (Gary).
- Link to v16: https://msgid.link/[email protected]
Changes in v16:
- Simplify pointer to reference cast in Page::from_raw.
- Use NonNull<Page> rather than Owned<Page> for BorrowedPage internals.
- Use "convertible to reference" wording when converting pointers to references.
- Fix formatting for Page::from_raw docs.
- Leave imports alone when adding safety comment to aref example.
- Use KBox::into_nonnull for examples.
- Add patch for KBox::into_nonnull.
- Change invariants and safety comments of Ownable and make the trait safe.
- Make Ownable::release take a mutable reference.
- Fix error handling in example for Ownable
- Link to v15: https://msgid.link/[email protected]
Changes in v15:
- Update series with original SoB's.
- Rename AlwaysRefCounted in kernel::usb.
- Rename Owned::get_pin_mut to Owned::as_pin_mut.
- Link to v14: https://msgid.link/[email protected]
Changes in v14:
- Rebase on v6.19-rc7.
- Rewrite cover letter.
- Update documentation and safety comments based on v13 feedback.
- Update commit messages.
- Reorder implementation blocks in owned.rs.
- Update example in owned.rs to use try operator rather than expect.
- Reformat use statements.
- Add patch: rust: page: convert to Ownable.
- Add patch: rust: implement ForeignOwnable for Owned.
- Add patch: rust: page: add from_raw().
- Link to v13: https://lore.kernel.org/r/[email protected]
Changes in v13:
- Rebase onto v6.18-rc1 (Andreas's work).
- Documentation and style fixes contributed by Andreas
- Link to v12: https://lore.kernel.org/r/[email protected]
Changes in v12:
-
- Rebase onto v6.17-rc1 (Andreas's work).
- moved kernel/types/ownable.rs to kernel/owned.rs
- Drop OwnableMut, make DerefMut depend on Unpin instead. I understood ML discussion as that being okay, but probably needs further scrunity.
- Lots of more documentation changes suggested by reviewers.
- Usage example for Ownable/Owned.
- Link to v11: https://lore.kernel.org/r/[email protected]
Changes in v11:
- Rework of documentation. I tried to honor all requests for changes "in spirit" plus some clearifications and corrections of my own.
- Dropping SimpleOwnedRefCounted by request from Alice, as it creates a potentially problematic blanket implementation (which a derive macro that could be created later would not have).
- Dropping Miguel's "kbuild: provide RUSTC_HAS_DO_NOT_RECOMMEND symbol" patch, as it is not needed anymore after dropping SimpleOwnedRefCounted. (I can add it again, if it is considered useful anyway).
- Link to v10: https://lore.kernel.org/r/[email protected]
Changes in v10:
- Moved kernel/ownable.rs to kernel/types/ownable.rs
- Fixes in documentation / comments as suggested by Andreas Hindborg
- Added Reviewed-by comment for Andreas Hindborg
- Fix rustfmt of pid_namespace.rs
- Link to v9: https://lore.kernel.org/r/[email protected]
Changes in v9:
- Rebase onto v6.14-rc7
- Move Ownable/OwnedRefCounted/Ownable, etc., into separate module
- Documentation fixes to Ownable/OwnableMut/OwnableRefCounted
- Add missing SAFETY documentation to ARef example
- Link to v8: https://lore.kernel.org/r/[email protected]
Changes in v8:
- Fix Co-developed-by and Suggested-by tags as suggested by Miguel and Boqun
- Some small documentation fixes in Owned/Ownable patch
- removing redundant trait constraint on DerefMut for Owned as suggested by Boqun Feng
- make SimpleOwnedRefCounted no longer implement RefCounted as suggested by Boqun Feng
- documentation for RefCounted as suggested by Boqun Feng
- Link to v7: https://lore.kernel.org/r/[email protected]
Changes in v7:
- Squash patch to make Owned::from_raw/into_raw public into parent
- Added Signed-off-by to other people's commits
- Link to v6: https://lore.kernel.org/r/[email protected]
Changes in v6:
- Changed comments/formatting as suggested by Miguel Ojeda
- Included and used new config flag RUSTC_HAS_DO_NOT_RECOMMEND,
thus no changes to types.rs will be needed when the attribute becomes available.
- Fixed commit message for Owned patch.
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Rebase the whole thing on top of the Ownable/Owned traits by Asahi Lina.
- Rename AlwaysRefCounted to RefCounted and make AlwaysRefCounted a marker trait instead to allow to obtain an ARef<T> from an &T,
which (as Alice pointed out) is unsound when combined with UniqueRef/Owned.
- Change the Trait design and naming to implement this feature, UniqueRef/UniqueRefCounted is dropped in favor of Ownable/Owned and OwnableRefCounted is used to provide the functions to convert between Owned and ARef.
- Link to v4: https://lore.kernel.org/r/[email protected]
Changes in v4:
- Just a minor change in naming by request from Andreas Hindborg, try_shared_to_unique() -> try_from_shared(), unique_to_shared() -> into_shared(),
which is more in line with standard Rust naming conventions.
- Link to v3: https://lore.kernel.org/r/Z8Wuud2UQX6Yukyr@mango
To: Danilo Krummrich <[email protected]>
To: Lorenzo Stoakes <[email protected]>
To: Vlastimil Babka <[email protected]>
To: "Liam R. Howlett" <[email protected]>
To: Uladzislau Rezki <[email protected]>
To: Miguel Ojeda <[email protected]>
To: Boqun Feng <[email protected]>
To: Gary Guo <[email protected]>
To: Björn Roy Baron <[email protected]>
To: Benno Lossin <[email protected]>
To: Andreas Hindborg <[email protected]>
To: Alice Ryhl <[email protected]>
To: Trevor Gross <[email protected]>
To: Daniel Almeida <[email protected]>
To: Tamir Duberstein <[email protected]>
To: Alexandre Courbot <[email protected]>
To: Onur Özkan <[email protected]>
To: Lyude Paul <[email protected]>
To: Greg Kroah-Hartman <[email protected]>
To: Arve Hjønnevåg <[email protected]>
To: Todd Kjos <[email protected]>
To: Christian Brauner <[email protected]>
To: Carlos Llamas <[email protected]>
To: "Rafael J. Wysocki" <[email protected]>
To: Dave Ertman <[email protected]>
To: Ira Weiny <[email protected]>
To: Leon Romanovsky <[email protected]>
To: Paul Moore <[email protected]>
To: Serge Hallyn <[email protected]>
To: David Airlie <[email protected]>
To: Simona Vetter <[email protected]>
To: Alexander Viro <[email protected]>
To: Jan Kara <[email protected]>
To: Igor Korotin <[email protected]>
To: Viresh Kumar <[email protected]>
To: Nishanth Menon <[email protected]>
To: Stephen Boyd <[email protected]>
To: Bjorn Helgaas <[email protected]>
To: Krzysztof Wilczyński <[email protected]>
To: Pavel Tikhomirov <[email protected]>
To: Michal Wilczynski <[email protected]>
Cc: Philipp Stanner <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
---
Andreas Hindborg (3):
rust: alloc: add KBox::into_non_null
rust: implement ForeignOwnable for Owned
rust: page: add from_raw()
Asahi Lina (2):
rust: types: Add Ownable/Owned types
rust: page: convert to Ownable
Oliver Mangold (3):
rust: rename AlwaysRefCounted to RefCounted.
rust: Add missing SAFETY documentation for ARef example
rust: Add OwnableRefCounted
drivers/android/binder/page_range.rs | 10 +- rust/kernel/alloc/allocator.rs | 19 +- rust/kernel/alloc/allocator/iter.rs | 6 +- rust/kernel/alloc/kbox.rs | 9 + rust/kernel/auxiliary.rs | 10 +- rust/kernel/block/mq/request.rs | 19 +- rust/kernel/cred.rs | 16 +- rust/kernel/device.rs | 12 +- rust/kernel/device/property.rs | 11 +- rust/kernel/drm/device.rs | 9 +- rust/kernel/drm/gem/mod.rs | 16 +- rust/kernel/fs/file.rs | 23 ++- rust/kernel/i2c.rs | 13 +- rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 22 ++- rust/kernel/mm/mmput_async.rs | 12 +- rust/kernel/opp.rs | 16 +- rust/kernel/owned.rs | 371 +++++++++++++++++++++++++++++++++++ rust/kernel/page.rs | 136 +++++-------- rust/kernel/pci.rs | 10 +- rust/kernel/pid_namespace.rs | 15 +- rust/kernel/platform.rs | 10 +- rust/kernel/pwm.rs | 12 +- rust/kernel/sync/aref.rs | 82 +++++--- rust/kernel/task.rs | 13 +- rust/kernel/types.rs | 12 ++ rust/kernel/usb.rs | 17 +- 27 files changed, 721 insertions(+), 181 deletions(-)
---
base-commit: 43a393185e33e573a374c1d4f7ddf6481484ef8d
change-id: 20250305-unique-ref-29fcd675f9e9
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
maintainerPATCH v18 1/8 rust: alloc: add `KBox::into_non_null`
Add a method to consume a Box<T, A> and return a NonNull<T>. This is a convenience wrapper around Self::into_raw for callers that need a NonNull pointer rather than a raw pointer.
--- rust/kernel/alloc/kbox.rs | 9 +++++++++ 1 file changed, 9 insertions(+)
rust/kernel/alloc/kbox.rs +9 -0
@@ -211,6 +211,15 @@ pub fn leak<'a>(b: Self) -> &'a mut T {// which points to an initialized instance of `T`. unsafe { &mut *Box ::into_raw (b) } } + +/// Consumes the `Box<T,A>` and returns a `NonNull<T>`. +/// +/// Like [`Self::into_raw`], but returns a `NonNull`. +#[inline] +pub fn into_non_null (b:Self ) ->NonNull <T > { +// SAFETY: `KBox::into_raw` returns a valid pointer. +unsafe {NonNull ::new_unchecked (Self ::into_raw (b)) } + } }impl <T ,A >Box <MaybeUninit <T >,A >
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 1/8] rust: alloc: add `KBox::into_non_null`
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Mismatch between SAFETY comment and executed code in `into_non_null`. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Mismatch between SAFETY comment and executed code in into_non_null. --
commit c2c9f847b4c97663dbc3f96c92652dbd5698f0aa
Author: Andreas Hindborg <[email protected]>
rust: alloc: add KBox::into_non_null
This commit adds an into_non_null() method to Box<T, A> that consumes the box and returns a NonNull<T>. It acts as a convenience wrapper around Self::into_raw() for callers requiring a NonNull pointer.
Quoted 4 lines
rust/kernel/alloc/kbox.rs +0
-0
[ ... ]
rust/kernel/alloc/kbox.rs pub fn leak<'a>(b: Self) -> &'a mut T { · line 221
Quoted 12 lines
rust/kernel/alloc/kbox.rs +8
-0@@ -211,6 +211,15 @@ pub fn leak<'a>(b: Self) -> &'a mut T {// which points to an initialized instance of `T`. unsafe { &mut *Box ::into_raw (b) } } + +/// Consumes the `Box<T,A>` and returns a `NonNull<T>`. +/// +/// Like [`Self::into_raw`], but returns a `NonNull`. +#[inline] +pub fn into_non_null (b:Self ) ->NonNull <T > { +// SAFETY: `KBox::into_raw` returns a valid pointer. +unsafe {NonNull ::new_unchecked (Self ::into_raw (b)) }
[Severity: Low]
This isn't a bug, but there is a mismatch between the safety comment and the executed code in into_non_null(). The safety comment specifies KBox::into_raw, but the code executes Self::into_raw(b) on the generic Box<T, A>.
Would it be better for the comment to reference the actual generic type method being called to prevent reader confusion?
Quoted 2 lines
rust/kernel/alloc/kbox.rs +1
-0+ } }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Andreas Hindborg
maintainerPATCH v18 2/8 rust: types: Add Ownable/Owned types
In reply to Andreas HindborgFrom: Asahi Lina <[email protected]>
By analogy to AlwaysRefCounted and ARef, an Ownable type is a (typically C FFI) type that *may* be owned by Rust, but need not be. Unlike AlwaysRefCounted, this mechanism expects the reference to be unique within Rust, and does not allow cloning.
Conceptually, this is similar to a KBox<T>, except that it delegates resource management to the T instead of using a generic allocator.
[ om:
- Split code into separate file and pub use it from types.rs.
- Make from_raw() and into_raw() public.
- Remove OwnableMut, and make DerefMut dependent on Unpin instead.
- Usage example/doctest for Ownable/Owned.
- Fixes to documentation and commit message.
]
[ Andreas: Updated documentation, examples, and formatting. Change safety
requirements, safety comments. ]
--- rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 188 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 5 ++ 4 files changed, 199 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -101,6 +101,7 @@pub mod of;#[cfg( CONFIG_PM_OPP )] pub mod opp; +pub mod owned;pub mod page;#[cfg( CONFIG_PCI )] pub mod pci;
rust/kernel/owned.rs new file +188 -0
188 lines not on this page · raw message
rust/kernel/sync/aref.rs +5 -0
@@ -34,6 +34,11 @@/// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted /// instances of a type. /// +/// Note: Implementing this trait allows types to be wrapped in an [`ARef<Self>`]. It requires an +/// internal reference count and provides only shared references. If unique references are required +/// [`Ownable`](crate::types::Ownable) should be implemented which allows types to be wrapped in an +/// [`Owned<Self>`](crate::types::Owned). +/// /// # Safety /// /// Implementers must ensure that increments to the reference count keep the object alive in memory
rust/kernel/types.rs +5 -0
@@ -15,6 +15,11 @@pub mod for_lt;pub use for_lt::ForLt ; +pub use crate ::owned::{ +Ownable , +Owned ,// +}; +/// Used to transfer ownership to and from foreign (non-Rust) languages. /// /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 2/8] rust: types: Add Ownable/Owned types
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] `Owned<T>` unconditionally structurally pins `T` by exposing `Pin<&mut T>`, but its API lacks the…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Owned<T> unconditionally structurally pins T by exposing Pin<&mut T>, but its API lacks the necessary documentation and safety bounds to enforce the pinning invariants. Specifically, Owned::from_raw(ptr) takes ownership without requiring the caller to promise the memory is or can be pinned; Owned::into_raw(me) safely extracts the pointer without documenting that the returned pointer's referent is still pinned; and Ownable::release(this) doesn't forbid the implementer from moving the pinned Self before dropping it. This omission allows an Ownable implementer or a user correctly following the explicit safety contracts to accidentally move a pinned !Unpin type, resulting in undefined behavior. --
commit b7329ea2c0525ffa6a63171ede0921ad2e6a23e5
Author: Asahi Lina <[email protected]>
rust: types: Add Ownable/Owned types
This commit introduces Ownable and Owned types for unique owned pointers with custom drop logic. These types allow C-allocated objects owned by Rust to be freed through the C API. It also updates documentation and adds usage examples.
Quoted 5 lines
rust/kernel/owned.rs new file +0
-0
[ ... ]
rust/kernel/owned.rs line 100
Quoted 12 lines
rust/kernel/owned.rs new file +12
-0+pub trait Ownable { +/// Tear down this `Ownable`. +/// +/// Implementers of `Ownable` can use this function to clean up the use of `Self`. This can +/// include freeing the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that they have exclusive ownership of the `Self` pointed to by `this`, +/// and that this ownership is transferred to the `release` method. `this` must not be used +/// after calling this method, as the underlying object may have been freed. +unsafe fn release (this:NonNull <Self >);
[Severity: High]
Since Owned<T> treats T as pinned (exposing Pin<&mut T> via as_pin_mut()), should the safety contract here also require that implementers treat this as pointing to pinned memory?
If an implementer moves the value during cleanup (for example, by reading it onto the stack), it could violate the pinning guarantees for !Unpin types and cause memory corruption due to self-reference invalidation.
Quoted 1 line
+}
[ ... ]
rust/kernel/owned.rs line 127
Quoted 12 lines
rust/kernel/owned.rs new file +12
-0+impl <T :Ownable >Owned <T > { +/// Creates a new instance of [`Owned`]. +/// +/// This function takes over ownership of the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. +/// - Until `T::release` is called, the returned `Owned<T>` exclusively owns the underlying `T`. +#[inline] +pub unsafe fn from_raw (ptr:NonNull <T >) ->Self {
[Severity: High]
Does this safety contract need to require that the pointer is permanently pinned?
Because Owned<T> can expose a pinned mutable reference, callers should be aware that they cannot assume the memory remains unpinned after calling this function.
rust/kernel/owned.rs line 138
Quoted 11 lines
rust/kernel/owned.rs new file +11
-0+// INVARIANT: By function safety requirement we satisfy the first invariant of `Self`. +// We treat `T` as pinned from now on. +Self { ptr } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not drop the underlying `T`. When this function returns, ownership of the +/// underlying `T` is with the caller. +#[inline] +pub fn into_raw (me:Self ) ->NonNull <T > {
[Severity: High]
Since into_raw() safely strips the Owned wrapper, should there be documentation stating that the caller remains bound by the pin invariant established by Owned?
Without this, a caller might extract the pointer and safely move the previously pinned object, resulting in undefined behavior.
Quoted 2 lines
rust/kernel/owned.rs new file +2
-0+ManuallyDrop ::new (me).ptr + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Andreas Hindborg
maintainerRe: [PATCH v18 2/8] rust: types: Add Ownable/Owned types
Quoted 35 lines · <[email protected]> writes:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High]Owned<T>unconditionally structurally pinsTby exposingPin<&mut T>, but its API lacks the necessary documentation and safety bounds to enforce the pinning invariants. Specifically,Owned::from_raw(ptr)takes ownership without requiring the caller to promise the memory is or can be pinned;Owned::into_raw(me)safely extracts the pointer without documenting that the returned pointer's referent is still pinned; andOwnable::release(this)doesn't forbid the implementer from moving the pinnedSelfbefore dropping it. This omission allows anOwnableimplementer or a user correctly following the explicit safety contracts to accidentally move a pinned!Unpintype, resulting in undefined behavior. --commit
b7329ea2c0525ffa6a63171ede0921ad2e6a23e5
Author: Asahi Lina <[email protected]>rust: types: Add Ownable/Owned types
This commit introduces Ownable and Owned types for unique owned pointers with custom drop logic. These types allow C-allocated objects owned by Rust to be freed through the C API. It also updates documentation and adds usage examples.
Quoted 5 lines
rust/kernel/owned.rs new file +0
-0[ ... ]
rust/kernel/owned.rs line 100
Quoted 12 lines
rust/kernel/owned.rs new file +12
-0+pub trait Ownable { +/// Tear down this `Ownable`. +/// +/// Implementers of `Ownable` can use this function to clean up the use of `Self`. This can +/// include freeing the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that they have exclusive ownership of the `Self` pointed to by `this`, +/// and that this ownership is transferred to the `release` method. `this` must not be used +/// after calling this method, as the underlying object may have been freed. +unsafe fn release (this:NonNull <Self >);
Quoted 8 lines
[Severity: High]
Since Owned<T> treats T as pinned (exposing Pin<&mut T> viaas_pin_mut()), should the safety contract here also require that implementers treatthisas pointing to pinned memory?If an implementer moves the value during cleanup (for example, by reading it onto the stack), it could violate the pinning guarantees for !Unpin types and cause memory corruption due to self-reference invalidation.
No. this is a pointer, and the value cannot be accessed or moved with safe code. Moving out of this requires an unsafe block with proper safety comments.
Quoted 16 lines
Quoted 2 lines
+}
[ ... ]
rust/kernel/owned.rs line 127
Quoted 12 lines
rust/kernel/owned.rs new file +12
-0+impl <T :Ownable >Owned <T > { +/// Creates a new instance of [`Owned`]. +/// +/// This function takes over ownership of the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. +/// - Until `T::release` is called, the returned `Owned<T>` exclusively owns the underlying `T`. +#[inline] +pub unsafe fn from_raw (ptr:NonNull <T >) ->Self {
Quoted 7 lines
[Severity: High]
Does this safety contract need to require that the pointer is permanently pinned?Because Owned<T> can expose a pinned mutable reference, callers should be aware that they cannot assume the memory remains unpinned after calling this function.
No. The documentation clearly state that this function takes ownership of the underlying object. The caller no longer has authority to access the object.
Quoted 13 lines
rust/kernel/owned.rs line 138
Quoted 12 lines
rust/kernel/owned.rs new file +11
-0+// INVARIANT: By function safety requirement we satisfy the first invariant of `Self`. +// We treat `T` as pinned from now on. +Self { ptr } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not drop the underlying `T`. When this function returns, ownership of the +/// underlying `T` is with the caller. +#[inline] +pub fn into_raw (me:Self ) ->NonNull <T > {
Quoted 8 lines
[Severity: High]
Sinceinto_raw()safely strips the Owned wrapper, should there be documentation stating that the caller remains bound by the pin invariant established by Owned?Without this, a caller might extract the pointer and safely move the previously pinned object, resulting in undefined behavior.
No. the return value is a pointer, and the pointee cannot be accessed or moved with safe code. Moving out of this requires an unsafe block with proper safety comments.
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH v18 3/8 rust: implement `ForeignOwnable` for `Owned`
In reply to Andreas HindborgImplement ForeignOwnable for Owned<T>. This allows use of Owned<T> in places such as the XArray.
Note that T does not need to implement ForeignOwnable for Owned<T> to implement ForeignOwnable.
--- rust/kernel/owned.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+)
rust/kernel/owned.rs +53 -0
@@ -15,6 +15,8 @@ ptr::NonNull, // }; +use kernel::types::ForeignOwnable ; +/// Types that specify their own way of performing allocation and destruction. Typically, this trait /// is implemented on types from the C side. ///
@@ -186,3 +188,54 @@ fn drop(&mut self) {unsafe {T ::release (self.ptr) }; } } + +// SAFETY: We derive the pointer to `T` from a valid `T`, so the returned +// pointer satisfy alignment requirements of `T`. +unsafe impl <T :Ownable >ForeignOwnable for Owned <T > { +const FOREIGN_ALIGN :usize = core::mem::align_of ::<T >(); + +type Borrowed <'a> + = &'aT +where +Self : 'a; +type BorrowedMut <'a> + =Pin <&'amut T > +where +Self : 'a; + +#[inline] +fn into_foreign (self) -> *mut kernel::ffi::c_void { +let ptr = self.ptr.as_ptr ().cast (); + core::mem::forget (self); + ptr + } + +#[inline] +unsafe fn from_foreign (ptr: *mut kernel::ffi::c_void ) ->Self { +// INVARIANT: By the function safety contract, `ptr` was returned by `into_foreign`, which +// gave up exclusive ownership of a valid, pinned `T`; we retake that ownership here. +Self { +// SAFETY: By function safety contract, `ptr` came from +// `into_foreign` and cannot be null. + ptr:unsafe {NonNull ::new_unchecked (ptr.cast ()) }, + } + } + +#[inline] +unsafe fn borrow <'a>(ptr: *mut kernel::ffi::c_void ) ->Self ::Borrowed <'a> { +// SAFETY: By function safety requirements, `ptr` is valid for use as a +// reference for `'a`. +unsafe { &*ptr.cast () } + } + +#[inline] +unsafe fn borrow_mut <'a>(ptr: *mut kernel::ffi::c_void ) ->Self ::BorrowedMut <'a> { +// SAFETY: By function safety requirements, `ptr` is valid for use as a +// unique reference for `'a`. +let inner =unsafe { &mut *ptr.cast () }; + +// SAFETY: We never move out of inner, and we do not hand out mutable +// references when `T: !Unpin`. +unsafe {Pin ::new_unchecked (inner) } + } +}
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 3/8] rust: implement `ForeignOwnable` for `Owned`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines
Implement
ForeignOwnableforOwned<T>. This allows use ofOwned<T>in places such as theXArray.Note that
Tdoes not need to implementForeignOwnableforOwned<T>to implementForeignOwnable.Signed-off-by Andreas Hindborg <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v18 3/8] rust: implement `ForeignOwnable` for `Owned`
In reply to Andreas HindborgQuoted 38 lines · Andreas Hindborg
Implement
ForeignOwnableforOwned<T>. This allows use ofOwned<T>in places such as theXArray.Note that
Tdoes not need to implementForeignOwnableforOwned<T>to implementForeignOwnable.Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/owned.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+)rust/kernel/owned.rs +12
-0@@ -15,6 +15,8 @@ ptr::NonNull, // }; +use kernel::types::ForeignOwnable ; +/// Types that specify their own way of performing allocation and destruction. Typically, this trait /// is implemented on types from the C side. /// @@ -186,3 +188,54 @@ fn drop(&mut self) {unsafe {T ::release (self.ptr) }; } } + +// SAFETY: We derive the pointer to `T` from a valid `T`, so the returned +// pointer satisfy alignment requirements of `T`. +unsafe impl <T :Ownable >ForeignOwnable for Owned <T > { +const FOREIGN_ALIGN :usize = core::mem::align_of ::<T >(); + +type Borrowed <'a> + = &'aT +where +Self : 'a;
rust/kernel/owned.rs fn drop(&mut self) { · line 210
Quoted 10 lines
rust/kernel/owned.rs +10
-0+type BorrowedMut <'a> + =Pin <&'amut T > +where +Self : 'a; + +#[inline] +fn into_foreign (self) -> *mut kernel::ffi::c_void { +let ptr = self.ptr.as_ptr ().cast (); + core::mem::forget (self); + ptr
I think the pattern in into_raw is better:
ManuallyDrop::new(self).ptr.as_ptr().cast()
Or perhaps this can just use Self::into_raw(self).as_ptr().cast().
rust/kernel/owned.rs fn drop(&mut self) { · line 222
Quoted 12 lines
rust/kernel/owned.rs +12
-0+ } + +#[inline] +unsafe fn from_foreign (ptr: *mut kernel::ffi::c_void ) ->Self { +// INVARIANT: By the function safety contract, `ptr` was returned by `into_foreign`, which +// gave up exclusive ownership of a valid, pinned `T`; we retake that ownership here. +Self { +// SAFETY: By function safety contract, `ptr` came from +// `into_foreign` and cannot be null. + ptr:unsafe {NonNull ::new_unchecked (ptr.cast ()) }, + } + }
Same here, could be using Self::from_raw.
However, the current code looks correct to me regardless, so:
Best,
Gary
Quoted 19 lines
rust/kernel/owned.rs +19
-0+ +#[inline] +unsafe fn borrow <'a>(ptr: *mut kernel::ffi::c_void ) ->Self ::Borrowed <'a> { +// SAFETY: By function safety requirements, `ptr` is valid for use as a +// reference for `'a`. +unsafe { &*ptr.cast () } + } + +#[inline] +unsafe fn borrow_mut <'a>(ptr: *mut kernel::ffi::c_void ) ->Self ::BorrowedMut <'a> { +// SAFETY: By function safety requirements, `ptr` is valid for use as a +// unique reference for `'a`. +let inner =unsafe { &mut *ptr.cast () }; + +// SAFETY: We never move out of inner, and we do not hand out mutable +// references when `T: !Unpin`. +unsafe {Pin ::new_unchecked (inner) } + } +}
Andreas Hindborg
maintainerRe: [PATCH v18 3/8] rust: implement `ForeignOwnable` for `Owned`
Quoted 69 lines · Gary Guo
Quoted 38 lines · Andreas Hindborg
Implement
ForeignOwnableforOwned<T>. This allows use ofOwned<T>in places such as theXArray.Note that
Tdoes not need to implementForeignOwnableforOwned<T>to implementForeignOwnable.Signed-off-by Andreas Hindborg <[email protected]>--- rust/kernel/owned.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+)rust/kernel/owned.rs +12
-0@@ -15,6 +15,8 @@ ptr::NonNull, // }; +use kernel::types::ForeignOwnable ; +/// Types that specify their own way of performing allocation and destruction. Typically, this trait /// is implemented on types from the C side. /// @@ -186,3 +188,54 @@ fn drop(&mut self) {unsafe {T ::release (self.ptr) }; } } + +// SAFETY: We derive the pointer to `T` from a valid `T`, so the returned +// pointer satisfy alignment requirements of `T`. +unsafe impl <T :Ownable >ForeignOwnable for Owned <T > { +const FOREIGN_ALIGN :usize = core::mem::align_of ::<T >(); + +type Borrowed <'a> + = &'aT +where +Self : 'a;rust/kernel/owned.rs fn drop(&mut self) { · line 210
Quoted 10 lines
rust/kernel/owned.rs +10
-0+type BorrowedMut <'a> + =Pin <&'amut T > +where +Self : 'a; + +#[inline] +fn into_foreign (self) -> *mut kernel::ffi::c_void { +let ptr = self.ptr.as_ptr ().cast (); + core::mem::forget (self); + ptrI think the pattern in
into_rawis better:ManuallyDrop::new(self).ptr.as_ptr().cast()Or perhaps this can just use
Self::into_raw(self).as_ptr().cast().rust/kernel/owned.rs fn drop(&mut self) { · line 222
Quoted 12 lines
rust/kernel/owned.rs +12
-0+ } + +#[inline] +unsafe fn from_foreign (ptr: *mut kernel::ffi::c_void ) ->Self { +// INVARIANT: By the function safety contract, `ptr` was returned by `into_foreign`, which +// gave up exclusive ownership of a valid, pinned `T`; we retake that ownership here. +Self { +// SAFETY: By function safety contract, `ptr` came from +// `into_foreign` and cannot be null. + ptr:unsafe {NonNull ::new_unchecked (ptr.cast ()) }, + } + }
Quoted 5 lines
Same here, could be using
Self::from_raw.However, the current code looks correct to me regardless, so:
Reviewed-by Gary Guo <[email protected]>
I'll defer to {into,from}_raw. Keeping your tag.
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH v18 4/8 rust: page: convert to `Ownable`
In reply to Andreas HindborgFrom: Asahi Lina <[email protected]>
This allows Page references to be returned as borrowed references, without necessarily owning the struct page.
Remove BorrowedPage and update users to use Owned<Page>.
--- drivers/android/binder/page_range.rs | 10 +-- rust/kernel/alloc/allocator.rs | 19 +++--- rust/kernel/alloc/allocator/iter.rs | 6 +- rust/kernel/page.rs | 122 +++++++++-------------------------- 4 files changed, 46 insertions(+), 111 deletions(-)
drivers/android/binder/page_range.rs +5 -5
@@ -33,7 +33,7 @@ sync::{aref::ARef, Mutex, SpinLock}, task::Pid, transmute::FromBytes, - types::Opaque, + types::{Opaque, Owned}, uaccess::UserSliceReader, };
@@ -198,7 +198,7 @@ unsafe impl Send for Inner {}#[repr( C )] struct PageInfo { lru: bindings::list_head , - page:Option <Page >, + page:Option <Owned <Page >>, range: *const ShrinkablePageRange , }
@@ -206,7 +206,7 @@ impl PageInfo {/// # Safety /// /// The caller ensures that writing to `me.page` is ok, and that the page is not currently set. -unsafe fn set_page (me: *mut PageInfo , page:Page ) { +unsafe fn set_page (me: *mut PageInfo , page:Owned <Page >) {// SAFETY: This pointer offset is in bounds. let ptr =unsafe { &raw mut (*me).page };
@@ -229,13 +229,13 @@ unsafe fn get_page<'a>(me: *const PageInfo) -> Option<&'a Page> {let ptr =unsafe { &raw const (*me).page };// SAFETY: The pointer is valid for reading. -unsafe { (*ptr).as_ref () } +unsafe { (*ptr).as_deref () } }/// # Safety /// /// The caller ensures that writing to `me.page` is ok for the duration of 'a. -unsafe fn take_page (me: *mut PageInfo ) ->Option <Page > { +unsafe fn take_page (me: *mut PageInfo ) ->Option <Owned <Page >> {// SAFETY: This pointer offset is in bounds. let ptr =unsafe { &raw mut (*me).page };
rust/kernel/alloc/allocator.rs +8 -11
@@ -169,7 +169,7 @@ unsafe fn realloc( }impl Vmalloc { -/// Convert a pointer to a [`Vmalloc`] allocation to a [`page::BorrowedPage`]. +/// Convert a pointer to a [`Vmalloc`] allocation to a [`Page`](page::Page) reference. /// /// # Examples ///
@@ -202,20 +202,17 @@ impl Vmalloc {/// /// - `ptr` must be a valid pointer to a [`Vmalloc`] allocation. /// - `ptr` must remain valid for the entire duration of `'a`. -pub unsafe fn to_page <'a>(ptr:NonNull <u8 >) -> page::BorrowedPage <'a> { +pub unsafe fn to_page <'a>(ptr:NonNull <u8 >) -> &'a page::Page {// SAFETY: `ptr` is a valid pointer to `Vmalloc` memory. let page =unsafe { bindings::vmalloc_to_page (ptr.as_ptr ().cast ()) }; -// SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid pointer -// to `Vmalloc` memory. -let page =unsafe {NonNull ::new_unchecked (page) }; -// SAFETY: -// - `page` is a valid pointer to a `struct page`, given that by the safety requirements of -// this function `ptr` is a valid pointer to a `Vmalloc` allocation. -// - By the safety requirements of this function `ptr` is valid for the entire lifetime of -// `'a`. -unsafe { page::BorrowedPage ::from_raw (page) } +// - `vmalloc_to_page` returns a valid, non-null pointer to a `struct page` for a valid +// pointer to `Vmalloc` memory, given that by the safety requirements of this function +// `ptr` is a valid pointer to a `Vmalloc` allocation. +// - By the safety requirements of this function `ptr`, and hence the `struct page`, is +// valid for the entire lifetime of `'a`. +unsafe { &*page.cast () } } }
rust/kernel/alloc/allocator/iter.rs +3 -3
@@ -9,7 +9,7 @@ ptr::NonNull, // }; -/// An [`Iterator`] of [`page::BorrowedPage`] items owned by a [`Vmalloc`] allocation. +/// An [`Iterator`] of [`Page`](page::Page) references owned by a [`Vmalloc`] allocation. /// /// # Guarantees ///
@@ -28,11 +28,11 @@ pub struct VmallocPageIter<'a> { size: usize,/// The current page index of the [`Iterator`]. index: usize, - _p: PhantomData<page::BorrowedPage<'a>>, + _p: PhantomData<&'a page::Page>, }impl <'a>Iterator for VmallocPageIter <'a> { -type Item = page::BorrowedPage <'a>; +type Item = &'a page::Page ;fn next (&mut self) ->Option <Self ::Item > {let offset = self.index.checked_mul (page::PAGE_SIZE )?;
rust/kernel/page.rs +30 -92
168 lines not on this page · raw message
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 4/8] rust: page: convert to `Ownable`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines
From: Asahi Lina <[email protected]>
This allows Page references to be returned as borrowed references, without necessarily owning the struct page.
Remove
BorrowedPageand update users to useOwned<Page>.Signed-off-by Asahi Lina <[email protected]>[ Andreas: Fix formatting and add a safety comment, update users. ]Signed-off-by Andreas Hindborg <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Re: [PATCH v18 4/8] rust: page: convert to `Ownable`
In reply to Andreas HindborgQuoted 10 lines · Andreas Hindborg
From: Asahi Lina <[email protected]>
This allows Page references to be returned as borrowed references, without necessarily owning the struct page.
Remove
BorrowedPageand update users to useOwned<Page>.Signed-off-by Asahi Lina <[email protected]>[ Andreas: Fix formatting and add a safety comment, update users. ]Signed-off-by Andreas Hindborg <[email protected]>
Nice to see BorrowedPage going away.
Quoted 6 lines
--- drivers/android/binder/page_range.rs | 10 +-- rust/kernel/alloc/allocator.rs | 19 +++--- rust/kernel/alloc/allocator/iter.rs | 6 +- rust/kernel/page.rs | 122 +++++++++-------------------------- 4 files changed, 46 insertions(+), 111 deletions(-)
Andreas Hindborg
maintainerPATCH v18 5/8 rust: rename `AlwaysRefCounted` to `RefCounted`.
In reply to Andreas HindborgFrom: Oliver Mangold <[email protected]>
There are types where it may both be reference counted in some cases and owned in others. In such cases, obtaining ARef<T> from &T would be unsound as it allows creation of ARef<T> copy from &Owned<T>.
Therefore, we split AlwaysRefCounted into RefCounted (which ARef<T> would require) and a marker trait to indicate that the type is always reference counted (and not Ownable) so the &T -> ARef<T> conversion is possible.
- Rename AlwaysRefCounted to RefCounted.
- Add a new unsafe trait AlwaysRefCounted.
- Implement the new trait AlwaysRefCounted for the newly renamed RefCounted implementations. This leaves functionality of existing implementers of AlwaysRefCounted intact.
--- rust/kernel/auxiliary.rs | 10 +++++++- rust/kernel/block/mq/request.rs | 19 +++++++++----- rust/kernel/cred.rs | 16 ++++++++++-- rust/kernel/device.rs | 12 +++++++-- rust/kernel/device/property.rs | 11 ++++++-- rust/kernel/drm/device.rs | 9 +++++-- rust/kernel/drm/gem/mod.rs | 16 +++++++++--- rust/kernel/fs/file.rs | 23 ++++++++++++++--- rust/kernel/i2c.rs | 13 +++++++--- rust/kernel/mm.rs | 22 +++++++++++++--- rust/kernel/mm/mmput_async.rs | 12 +++++++-- rust/kernel/opp.rs | 16 +++++++++--- rust/kernel/owned.rs | 2 +- rust/kernel/pci.rs | 10 +++++++- rust/kernel/pid_namespace.rs | 15 +++++++++-- rust/kernel/platform.rs | 10 +++++++- rust/kernel/pwm.rs | 12 +++++++-- rust/kernel/sync/aref.rs | 57 +++++++++++++++++++++++++---------------- rust/kernel/task.rs | 13 ++++++++-- rust/kernel/types.rs | 12 ++++++--- rust/kernel/usb.rs | 17 +++++++++--- 21 files changed, 255 insertions(+), 72 deletions(-)
rust/kernel/auxiliary.rs +9 -1
@@ -19,6 +19,10 @@ to_result, // }, prelude::*, + sync::aref::{ + AlwaysRefCounted, + RefCounted, // + }, types::{ForLt ,ForeignOwnable ,
@@ -344,7 +348,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> kernel::impl_device_context_into_aref!(Device );// SAFETY: Instances of `Device` are always reference-counted. -unsafe impl crate ::sync::aref::AlwaysRefCounted for Device { +unsafe impl RefCounted for Device {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::get_device (self.as_ref ().as_raw ()) };
@@ -363,6 +367,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl AlwaysRefCounted for Device {} +impl <Ctx : device::DeviceContext >AsRef <device::Device <Ctx >>for Device <Ctx > {fn as_ref (&self) -> &device::Device <Ctx > {// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
rust/kernel/block/mq/request.rs +13 -6
@@ -9,7 +9,11 @@ block::mq::Operations, error::Result, sync::{ - aref::{ARef, AlwaysRefCounted}, + aref::{ + ARef, + AlwaysRefCounted, + RefCounted, // + }, atomic::Relaxed, Refcount, },
@@ -229,11 +233,10 @@ unsafe impl<T: Operations> Send for Request<T> {}// mutate `self` are internally synchronized` unsafe impl <T :Operations >Sync for Request <T > {} -// SAFETY: All instances of `Request<T>` are reference counted. This -// implementation of `AlwaysRefCounted` ensure that increments to the ref count -// keeps the object alive in memory at least until a matching reference count -// decrement is executed. -unsafe impl <T :Operations >AlwaysRefCounted for Request <T > { +// SAFETY: All instances of `Request<T>` are reference counted. This implementation of `RefCounted` +// ensure that increments to the ref count keeps the object alive in memory at least until a +// matching reference count decrement is executed. +unsafe impl <T :Operations >RefCounted for Request <T > {fn inc_ref (&self) { self.wrapper_ref ().refcount ().inc (); }
@@ -255,3 +258,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) { } } } + +// SAFETY: We currently do not implement `Ownable`, thus it is okay to obtain an `ARef<Request>` +// from a `&Request` (but this will change in the future). +unsafe impl <T :Operations >AlwaysRefCounted for Request <T > {}
rust/kernel/cred.rs +14 -2
@@ -8,7 +8,15 @@//! //! Reference: <https://www.kernel.org/doc/html/latest/security/credentials.html> -use crate ::{bindings, sync::aref::AlwaysRefCounted , task::Kuid , types::Opaque }; +use crate ::{ + bindings, + sync::aref::RefCounted , + task::Kuid , + types::{ +AlwaysRefCounted , +Opaque ,// + },// +};/// Wraps the kernel's `struct cred`. ///
@@ -76,7 +84,7 @@ pub fn euid(&self) -> Kuid { }// SAFETY: The type invariants guarantee that `Credential` is always ref-counted. -unsafe impl AlwaysRefCounted for Credential { +unsafe impl RefCounted for Credential {#[inline] fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -90,3 +98,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Credential>) {unsafe { bindings::put_cred (obj.cast ().as_ptr ()) }; } } + +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Credential>` from a +// `&Credential`. +unsafe impl AlwaysRefCounted for Credential {}
rust/kernel/device.rs +10 -2
@@ -8,8 +8,12 @@ bindings, fmt, prelude::*, - sync::aref::ARef, + sync::aref::{ + ARef, + RefCounted, // + }, types::{ +AlwaysRefCounted ,ForeignOwnable ,Opaque ,// }, //
@@ -448,7 +452,7 @@ pub fn name(&self) -> &CStr { kernel::impl_device_context_into_aref!(Device );// SAFETY: Instances of `Device` are always reference-counted. -unsafe impl crate ::sync::aref::AlwaysRefCounted for Device { +unsafe impl RefCounted for Device {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::get_device (self.as_raw ()) };
@@ -460,6 +464,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl AlwaysRefCounted for Device {} +// SAFETY: As by the type invariant `Device` can be sent to any thread. unsafe impl Send for Device {}
rust/kernel/device/property.rs +9 -2
@@ -14,7 +14,10 @@ fmt, prelude::*, str::{CStr, CString}, - sync::aref::ARef, + sync::aref::{ + ARef, + AlwaysRefCounted, // + }, types::Opaque, };
@@ -360,7 +363,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { }// SAFETY: Instances of `FwNode` are always reference-counted. -unsafe impl crate ::sync::aref::AlwaysRefCounted for FwNode { +unsafe impl crate ::sync::aref::RefCounted for FwNode {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the // refcount is non-zero.
@@ -374,6 +377,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<FwNode>` from a +// `&FwNode`. +unsafe impl AlwaysRefCounted for FwNode {} +enum Node <'a> {Borrowed (&'aFwNode ),Owned (ARef <FwNode >),
rust/kernel/drm/device.rs +7 -2
@@ -15,7 +15,8 @@ prelude::*, sync::aref::{ARef , - AlwaysRefCounted, // +AlwaysRefCounted , +RefCounted ,// }, types::Opaque, workqueue::{
@@ -227,7 +228,7 @@ fn deref(&self) -> &Self::Target {// SAFETY: DRM device objects are always reference counted and the get/put functions // satisfy the requirements. -unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > { +unsafe impl <T : drm::Driver >RefCounted for Device <T > {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_dev_get (self.as_raw ()) };
@@ -242,6 +243,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > {} +impl <T : drm::Driver >AsRef <device::Device >for Device <T > {fn as_ref (&self) -> &device::Device {// SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
rust/kernel/drm/gem/mod.rs +12 -4
@@ -17,7 +17,7 @@ prelude::*, sync::aref::{ ARef, - AlwaysRefCounted, // + RefCounted, // }, types::Opaque, };
@@ -29,7 +29,7 @@#[cfg( CONFIG_RUST_DRM_GEM_SHMEM_HELPER )] pub mod shmem; -/// A macro for implementing [`AlwaysRefCounted`] for any GEM object type. +/// A macro for implementing [`RefCounted`] for any GEM object type. /// /// Since all GEM objects use the same refcounting scheme. #[macro_export]
@@ -42,7 +42,7 @@ impl $( <$( $tparam_id:ident ),+> )? for $type:ty )? ) => {// SAFETY: All GEM objects are refcounted. - unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $type + unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::RefCounted for $type where Self: IntoGEMObject, $( $( $bind_param : $bind_trait ),+ )?
@@ -61,6 +61,14 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {unsafe { bindings::drm_gem_object_put (obj) }; } } + +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<$type>` from a +// `&$type`. + unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $type + where + Self: IntoGEMObject, + $( $( $bind_param : $bind_trait ),+ )? + {} }; } #[cfg_attr(not(CONFIG_RUST_DRM_GEM_SHMEM_HELPER), allow(unused))]
@@ -98,7 +106,7 @@ fn close(_obj: &<Self::Driver as drm::Driver>::Object, _file: &DriverFile<Self>) }/// Trait that represents a GEM object subtype -pub trait IntoGEMObject :Sized +super ::private::Sealed +AlwaysRefCounted { +pub trait IntoGEMObject :Sized +super ::private::Sealed +RefCounted {/// Returns a reference to the raw `drm_gem_object` structure, which must be valid as long as /// this owning object is valid. fn as_raw (&self) -> *mut bindings::drm_gem_object ;
rust/kernel/fs/file.rs +19 -4
@@ -12,8 +12,15 @@ cred::Credential, error::{code::*, to_result, Error, Result}, fmt, - sync::aref::{ARef, AlwaysRefCounted}, - types::{NotThreadSafe, Opaque}, + sync::aref::{ + ARef, + RefCounted, // + }, + types::{ +AlwaysRefCounted , +NotThreadSafe , +Opaque ,// + }, // };use core::ptr;
@@ -197,7 +204,7 @@ unsafe impl Sync for File {}// SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation // makes `ARef<File>` own a normal refcount. -unsafe impl AlwaysRefCounted for File { +unsafe impl RefCounted for File {#[inline] fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -212,6 +219,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<File>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<File>` from a +// `&File`. +unsafe impl AlwaysRefCounted for File {} +/// Wraps the kernel's `struct file`. Not thread safe. /// /// This type represents a file that is not known to be safe to transfer across thread boundaries.
@@ -233,7 +244,7 @@ pub struct LocalFile {// SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation // makes `ARef<LocalFile>` own a normal refcount. -unsafe impl AlwaysRefCounted for LocalFile { +unsafe impl RefCounted for LocalFile {#[inline] fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -249,6 +260,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<LocalFile>` from a +// `&LocalFile`. +unsafe impl AlwaysRefCounted for LocalFile {} +impl LocalFile {/// Constructs a new `struct file` wrapper from a file descriptor. ///
rust/kernel/i2c.rs +10 -3
@@ -18,7 +18,8 @@ prelude::*, sync::aref::{ARef , - AlwaysRefCounted, // +AlwaysRefCounted , +RefCounted ,// }, types::Opaque, // };
@@ -424,7 +425,7 @@ pub fn get(index: i32) -> Result<ARef<Self>> { kernel::impl_device_context_into_aref!(I2cAdapter );// SAFETY: Instances of `I2cAdapter` are always reference-counted. -unsafe impl AlwaysRefCounted for I2cAdapter { +unsafe impl RefCounted for I2cAdapter {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::i2c_get_adapter (self.index ()) };
@@ -435,6 +436,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) {unsafe { bindings::i2c_put_adapter (obj.as_ref ().as_raw ()) } } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from an +// `&I2cAdapter`. +unsafe impl AlwaysRefCounted for I2cAdapter {}/// The i2c board info representation ///
@@ -500,7 +504,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<C kernel::impl_device_context_into_aref!(I2cClient );// SAFETY: Instances of `I2cClient` are always reference-counted. -unsafe impl AlwaysRefCounted for I2cClient { +unsafe impl RefCounted for I2cClient {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::get_device (self.as_ref ().as_raw ()) };
@@ -511,6 +515,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) {unsafe { bindings::put_device (&raw mut (*obj.as_ref ().as_raw ()).dev) } } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from an +// `&I2cClient`. +unsafe impl AlwaysRefCounted for I2cClient {}impl <Ctx : device::DeviceContext >AsRef <device::Device <Ctx >>for I2cClient <Ctx > {fn as_ref (&self) -> &device::Device <Ctx > {
rust/kernel/mm.rs +18 -4
@@ -13,8 +13,15 @@use crate ::{ bindings, - sync::aref::{ARef ,AlwaysRefCounted }, - types::{NotThreadSafe ,Opaque }, + sync::aref::{ +ARef , +RefCounted ,// + }, + types::{ +AlwaysRefCounted , +NotThreadSafe , +Opaque ,// + },// };use core::{ops::Deref , ptr::NonNull };
@@ -55,7 +62,7 @@ unsafe impl Send for Mm {}unsafe impl Sync for Mm {}// SAFETY: By the type invariants, this type is always refcounted. -unsafe impl AlwaysRefCounted for Mm { +unsafe impl RefCounted for Mm {#[inline] fn inc_ref (&self) {// SAFETY: The pointer is valid since self is a reference.
@@ -69,6 +76,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Mm>` from a `&Mm`. +unsafe impl AlwaysRefCounted for Mm {} +/// A wrapper for the kernel's `struct mm_struct`. /// /// This type is like [`Mm`], but with non-zero `mm_users`. It can only be used when `mm_users` can
@@ -91,7 +101,7 @@ unsafe impl Send for MmWithUser {}unsafe impl Sync for MmWithUser {}// SAFETY: By the type invariants, this type is always refcounted. -unsafe impl AlwaysRefCounted for MmWithUser { +unsafe impl RefCounted for MmWithUser {#[inline] fn inc_ref (&self) {// SAFETY: The pointer is valid since self is a reference.
@@ -105,6 +115,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<MmWithUser>` from a +// `&MmWithUser`. +unsafe impl AlwaysRefCounted for MmWithUser {} +// Make all `Mm` methods available on `MmWithUser`. impl Deref for MmWithUser {type Target =Mm ;
rust/kernel/mm/mmput_async.rs +10 -2
@@ -10,7 +10,11 @@use crate ::{ bindings, mm::MmWithUser , - sync::aref::{ARef ,AlwaysRefCounted }, + sync::aref::{ +ARef , +RefCounted ,// + }, + types::AlwaysRefCounted , };use core::{ops::Deref , ptr::NonNull };
@@ -34,7 +38,7 @@ unsafe impl Send for MmWithUserAsync {}unsafe impl Sync for MmWithUserAsync {}// SAFETY: By the type invariants, this type is always refcounted. -unsafe impl AlwaysRefCounted for MmWithUserAsync { +unsafe impl RefCounted for MmWithUserAsync {#[inline] fn inc_ref (&self) {// SAFETY: The pointer is valid since self is a reference.
@@ -48,6 +52,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<MmWithUserAsync>` +// from a `&MmWithUserAsync`. +unsafe impl AlwaysRefCounted for MmWithUserAsync {} +// Make all `MmWithUser` methods available on `MmWithUserAsync`. impl Deref for MmWithUserAsync {type Target =MmWithUser ;
rust/kernel/opp.rs +13 -3
@@ -16,8 +16,14 @@ ffi::{c_char, c_ulong}, prelude::*, str::CString, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::{ + ARef, + RefCounted, // + }, + types::{ +AlwaysRefCounted , +Opaque ,// + }, // };#[cfg( CONFIG_CPU_FREQ )]
@@ -1041,7 +1047,7 @@ unsafe impl Send for OPP {}unsafe impl Sync for OPP {}/// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted. -unsafe impl AlwaysRefCounted for OPP { +unsafe impl RefCounted for OPP {#[inline] fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -1055,6 +1061,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<OPP>` from an +// `&OPP`. +unsafe impl AlwaysRefCounted for OPP {} +impl OPP {/// Creates an owned reference to a [`OPP`] from a valid pointer. ///
rust/kernel/owned.rs +1 -1
@@ -27,7 +27,7 @@/// /// Note: The underlying object is not required to provide internal reference counting, because it /// represents a unique, owned reference. If reference counting (on the Rust side) is required, -/// [`AlwaysRefCounted`](crate::sync::aref::AlwaysRefCounted) should be implemented. +/// [`RefCounted`](crate::types::RefCounted) should be implemented. /// /// # Examples ///
rust/kernel/pci.rs +9 -1
@@ -19,6 +19,10 @@ }, prelude::*, str::CStr, + sync::aref::{ + AlwaysRefCounted, + RefCounted, // + }, types::Opaque, ThisModule, // };
@@ -481,7 +485,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>impl <'a>crate ::dma::Device <'a>for Device <device::Core <'a>> {}// SAFETY: Instances of `Device` are always reference-counted. -unsafe impl crate ::sync::aref::AlwaysRefCounted for Device { +unsafe impl RefCounted for Device {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::pci_dev_get (self.as_raw ()) };
@@ -493,6 +497,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl AlwaysRefCounted for Device {} +impl <Ctx : device::DeviceContext >AsRef <device::Device <Ctx >>for Device <Ctx > {fn as_ref (&self) -> &device::Device <Ctx > {// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
rust/kernel/pid_namespace.rs +13 -2
@@ -7,7 +7,14 @@//! C header: [`include/linux/pid_namespace.h`](srctree/include/linux/pid_namespace.h) and //! [`include/linux/pid.h`](srctree/include/linux/pid.h) -use crate ::{bindings, sync::aref::AlwaysRefCounted , types::Opaque }; +use crate ::{ + bindings, + sync::aref::RefCounted , + types::{ +AlwaysRefCounted , +Opaque ,// + },// +};use core::ptr;/// Wraps the kernel's `struct pid_namespace`. Thread safe.
@@ -41,7 +48,7 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::pid_namespace) -> &'a Self { }// SAFETY: Instances of `PidNamespace` are always reference-counted. -unsafe impl AlwaysRefCounted for PidNamespace { +unsafe impl RefCounted for PidNamespace {#[inline] fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -55,6 +62,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<PidNamespace>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<PidNamespace>` from +// a `&PidNamespace`. +unsafe impl AlwaysRefCounted for PidNamespace {} +// SAFETY: // - `PidNamespace::dec_ref` can be called from any thread. // - It is okay to send ownership of `PidNamespace` across thread boundaries.
rust/kernel/platform.rs +9 -1
@@ -27,6 +27,10 @@ }, of, prelude::*, + sync::aref::{ + AlwaysRefCounted, + RefCounted, // + }, types::Opaque, ThisModule, // };
@@ -518,7 +522,7 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {impl <'a>crate ::dma::Device <'a>for Device <device::Core <'a>> {}// SAFETY: Instances of `Device` are always reference-counted. -unsafe impl crate ::sync::aref::AlwaysRefCounted for Device { +unsafe impl RefCounted for Device {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::get_device (self.as_ref ().as_raw ()) };
@@ -530,6 +534,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl AlwaysRefCounted for Device {} +impl <Ctx : device::DeviceContext >AsRef <device::Device <Ctx >>for Device <Ctx > {fn as_ref (&self) -> &device::Device <Ctx > {// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
rust/kernel/pwm.rs +10 -2
@@ -13,7 +13,11 @@ devres, error::{self, to_result}, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, + sync::aref::{ + ARef, + AlwaysRefCounted, + RefCounted, // + }, types::Opaque, // };use core::{
@@ -629,7 +633,7 @@ pub fn new<'a>( }// SAFETY: Implements refcounting for `Chip` using the embedded `struct device`. -unsafe impl <T :PwmOps >AlwaysRefCounted for Chip <T > { +unsafe impl <T :PwmOps >RefCounted for Chip <T > {#[inline] fn inc_ref (&self) {// SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists.
@@ -647,6 +651,10 @@ unsafe fn dec_ref(obj: NonNull<Chip<T>>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Chip<T>>` from a +// `&Chip<T>`. +unsafe impl <T :PwmOps >AlwaysRefCounted for Chip <T > {} +// SAFETY: `Chip` is a wrapper around `*mut bindings::pwm_chip`. The underlying C // structure's state is managed and synchronized by the kernel's device model // and PWM core locking mechanisms. Therefore, it is safe to move the `Chip`
rust/kernel/sync/aref.rs +35 -22
144 lines not on this page · raw message
rust/kernel/task.rs +11 -2
@@ -10,7 +10,12 @@ pid_namespace::PidNamespace, prelude::*, sync::aref::ARef, - types::{NotThreadSafe, Opaque}, + types::{ +AlwaysRefCounted , +NotThreadSafe , +Opaque , +RefCounted ,// + }, };use core::{ ops::Deref ,
@@ -347,7 +352,7 @@ pub fn group_leader(&self) -> &Task { }// SAFETY: The type invariants guarantee that `Task` is always refcounted. -unsafe impl crate ::sync::aref::AlwaysRefCounted for Task { +unsafe impl RefCounted for Task {#[inline] fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -361,6 +366,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Task>` from a +// `&Task`. +unsafe impl AlwaysRefCounted for Task {} +impl PartialEq for Task {#[inline] fn eq (&self, other: &Self ) ->bool {
rust/kernel/types.rs +9 -3
@@ -15,9 +15,15 @@pub mod for_lt;pub use for_lt::ForLt ; -pub use crate ::owned::{ -Ownable , -Owned ,// +pub use crate ::{ + owned::{ +Ownable , +Owned ,// + }, + sync::aref::{ +AlwaysRefCounted , +RefCounted ,// + },// };/// Used to transfer ownership to and from foreign (non-Rust) languages.
rust/kernel/usb.rs +14 -3
@@ -18,7 +18,10 @@ to_result, // }, prelude::*, - sync::aref::AlwaysRefCounted, + sync::aref::{ + AlwaysRefCounted, + RefCounted, // + }, types::Opaque, ThisModule, // };
@@ -392,7 +395,7 @@ fn as_ref(&self) -> &Device { }// SAFETY: Instances of `Interface` are always reference-counted. -unsafe impl AlwaysRefCounted for Interface { +unsafe impl RefCounted for Interface {fn inc_ref (&self) {// SAFETY: The invariants of `Interface` guarantee that `self.as_raw()` // returns a valid `struct usb_interface` pointer, for which we will
@@ -406,6 +409,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Interface>` from a +// `&Interface`. +unsafe impl AlwaysRefCounted for Interface {} +// SAFETY: A `Interface` is always reference-counted and can be released from any thread. unsafe impl Send for Interface {}
@@ -443,7 +450,7 @@ fn as_raw(&self) -> *mut bindings::usb_device { kernel::impl_device_context_into_aref!(Device );// SAFETY: Instances of `Device` are always reference-counted. -unsafe impl AlwaysRefCounted for Device { +unsafe impl RefCounted for Device {fn inc_ref (&self) {// SAFETY: The invariants of `Device` guarantee that `self.as_raw()` // returns a valid `struct usb_device` pointer, for which we will
@@ -457,6 +464,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl AlwaysRefCounted for Device {} +impl <Ctx : device::DeviceContext >AsRef <device::Device <Ctx >>for Device <Ctx > {fn as_ref (&self) -> &device::Device <Ctx > {// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 5/8] rust: rename `AlwaysRefCounted` to `RefCounted`.
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Incomplete Refactoring / Trait Bound Violation for workqueue items - [Medium] Stale and…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Incomplete Refactoring / Trait Bound Violation for workqueue items
- [Medium] Stale and misleading documentation for ARef usage
--
commit 46d36a47415ab0722d334e8010242374e8bba94c
Author: Oliver Mangold <[email protected]>
rust: rename AlwaysRefCounted to RefCounted.
This commit splits the AlwaysRefCounted trait into RefCounted (for actual reference counting logic) and a new AlwaysRefCounted marker trait. This change allows types that can be both reference-counted and owned to safely use ARef<T> conversions without violating ownership constraints.
rust/kernel/sync/aref.rs
Quoted 4 lines
rust/kernel/sync/aref.rs +0
-0
[Severity: Medium]
In the module documentation which isn't included in this diff, it states:
//! To make use of [ARef<MyType>], MyType needs to implement //! [AlwaysRefCounted].
Should this documentation be updated to reference RefCounted instead?
Leaving this as AlwaysRefCounted might mislead developers into implementing the marker trait for new types, which could violate the safety contract if their type is also Ownable.
Quoted 10 lines
rust/kernel/sync/aref.rs +1
-3@@ -24,11 +24,9 @@ ptr::NonNull, // }; -/// Types that are _always_ reference counted. +/// Types that are internally reference counted. /// /// It allows such types to define their own custom ref increment and decrement functions. -/// Additionally, it allows users to convert from a shared reference `&T` to an owned reference -/// [`ARef<T>`].
[ ... ]
rust/kernel/sync/aref.rs line 49
Quoted 11 lines
rust/kernel/sync/aref.rs +2
-3@@ -45,9 +43,8 @@/// at least until matching decrements are performed. /// /// Implementers must also ensure that all instances are reference-counted. (Otherwise they -/// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object -/// alive.) -pub unsafe trait AlwaysRefCounted { +/// won't be able to honour the requirement that [`RefCounted::inc_ref`] keep the object alive.) +pub unsafe trait RefCounted {/// Increments the reference count on the object. fn inc_ref (&self);
[Severity: Medium]
Since this patch renames AlwaysRefCounted to RefCounted and re-adds AlwaysRefCounted as a marker trait, does rust/kernel/workqueue.rs need to be updated to use the new bound?
Currently, rust/kernel/workqueue.rs enforces T: AlwaysRefCounted for work items using ARef<T>:
rust/kernel/workqueue.rs:
unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T> where
T: AlwaysRefCounted,
The same bound is used for RawWorkItem and RawDelayedWorkItem.
Does keeping this bound unnecessarily prevent purely RefCounted types from being scheduled as work items via ARef<T>? It appears this might defeat the goal of the trait split for workqueue users.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Andreas Hindborg
maintainerRe: [PATCH v18 5/8] rust: rename `AlwaysRefCounted` to `RefCounted`.
Quoted 23 lines · <[email protected]> writes:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Incomplete Refactoring / Trait Bound Violation for workqueue items
- [Medium] Stale and misleading documentation forARefusage
--commit
46d36a47415ab0722d334e8010242374e8bba94c
Author: Oliver Mangold <[email protected]>rust: rename AlwaysRefCounted to RefCounted.
This commit splits the AlwaysRefCounted trait into RefCounted (for actual reference counting logic) and a new AlwaysRefCounted marker trait. This change allows types that can be both reference-counted and owned to safely use ARef<T> conversions without violating ownership constraints.
rust/kernel/sync/aref.rs
Quoted 4 lines
rust/kernel/sync/aref.rs +0
-0[Severity: Medium]
In the module documentation which isn't included in this diff, it states:
Quoted 8 lines
//! To make use of [
ARef<MyType>],MyTypeneeds to implement //! [AlwaysRefCounted].Should this documentation be updated to reference RefCounted instead?
Leaving this as AlwaysRefCounted might mislead developers into implementing the marker trait for new types, which could violate the safety contract if their type is also Ownable.
I will fix this.
Quoted 34 lines
Quoted 11 lines
rust/kernel/sync/aref.rs +1
-3@@ -24,11 +24,9 @@ ptr::NonNull, // }; -/// Types that are _always_ reference counted. +/// Types that are internally reference counted. /// /// It allows such types to define their own custom ref increment and decrement functions. -/// Additionally, it allows users to convert from a shared reference `&T` to an owned reference -/// [`ARef<T>`]. [ ... ]
rust/kernel/sync/aref.rs line 49
Quoted 11 lines
rust/kernel/sync/aref.rs +2
-3@@ -45,9 +43,8 @@/// at least until matching decrements are performed. /// /// Implementers must also ensure that all instances are reference-counted. (Otherwise they -/// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object -/// alive.) -pub unsafe trait AlwaysRefCounted { +/// won't be able to honour the requirement that [`RefCounted::inc_ref`] keep the object alive.) +pub unsafe trait RefCounted {/// Increments the reference count on the object. fn inc_ref (&self);[Severity: Medium]
Since this patch renames AlwaysRefCounted to RefCounted and re-adds AlwaysRefCounted as a marker trait, doesrust/kernel/workqueue.rsneed to be updated to use the new bound?Currently,
rust/kernel/workqueue.rsenforces T: AlwaysRefCounted for work items using ARef<T>:
Quoted 6 lines
rust/kernel/workqueue.rs:
unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T> where
T: AlwaysRefCounted,The same bound is used for RawWorkItem and RawDelayedWorkItem.
Yes, they should be changed to RefCounted. I will fix this.
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH v18 6/8 rust: Add missing SAFETY documentation for `ARef` example
In reply to Andreas HindborgFrom: Oliver Mangold <[email protected]>
SAFETY comment in rustdoc example was just 'TODO'. Fixed.
--- rust/kernel/sync/aref.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
rust/kernel/sync/aref.rs +4 -2
@@ -142,7 +142,9 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// struct Empty {} /// -/// # // SAFETY: TODO. +/// // SAFETY: The `RefCounted` implementation for `Empty` does not count references and never +/// // frees the underlying object. Thus we can act as owning an increment on the refcount for +/// // the object that we pass to the newly created `ARef`. /// unsafe impl RefCounted for Empty { /// fn inc_ref(&self) {} /// unsafe fn dec_ref(_obj: NonNull<Self>) {}
@@ -150,7 +152,7 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// let mut data = Empty {}; /// let ptr = NonNull::<Empty>::new(&mut data).unwrap(); -/// # // SAFETY: TODO. +/// // SAFETY: We keep `data` around longer than the `ARef`. /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) }; /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref); ///
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 6/8] rust: Add missing SAFETY documentation for `ARef` example
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines
From: Oliver Mangold <[email protected]>
SAFETY comment in rustdoc example was just 'TODO'. Fixed.
Signed-off-by Oliver Mangold <[email protected]>Reviewed-by Daniel Almeida <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Andreas Hindborg
maintainerPATCH v18 7/8 rust: Add `OwnableRefCounted`
In reply to Andreas HindborgFrom: Oliver Mangold <[email protected]>
Types implementing one of these traits can safely convert between an ARef<T> and an Owned<T>.
This is useful for types which generally are accessed through an ARef but have methods which can only safely be called when the reference is unique, like e.g. block::mq::Request::end_ok().
[ Andreas: Fix formatting, update documentation, fix error handling in
examples. ]
--- rust/kernel/owned.rs | 140 +++++++++++++++++++++++++++++++++++++++++++++-- rust/kernel/sync/aref.rs | 16 +++++- rust/kernel/types.rs | 1 + 3 files changed, 151 insertions(+), 6 deletions(-)
rust/kernel/owned.rs +135 -5
@@ -14,20 +14,26 @@ pin::Pin, ptr::NonNull, // }; +use kernel::{ + sync::aref::ARef , + types::RefCounted ,// +};use kernel::types::ForeignOwnable ;/// Types that specify their own way of performing allocation and destruction. Typically, this trait /// is implemented on types from the C side. /// -/// Implementing this trait allows types to be referenced via the [`Owned<Self>`] pointer type. This -/// is useful when it is desirable to tie the lifetime of the reference to an owned object, rather -/// than pass around a bare reference. [`Ownable`] types can define custom drop logic that is -/// executed when the owned reference [`Owned<Self>`] pointing to the object is dropped. +/// Implementing this trait allows types to be referenced via the [`Owned<Self>`] pointer type. +/// - This is useful when it is desirable to tie the lifetime of an object reference to an owned +/// object, rather than pass around a bare reference. +/// - [`Ownable`] types can define custom drop logic that is executed when the owned reference +/// of type [`Owned<_>`] pointing to the object is dropped. /// /// Note: The underlying object is not required to provide internal reference counting, because it /// represents a unique, owned reference. If reference counting (on the Rust side) is required, -/// [`RefCounted`](crate::types::RefCounted) should be implemented. +/// [`RefCounted`] should be implemented. [`OwnableRefCounted`] should be implemented if conversion +/// between unique and shared (reference counted) ownership is needed. /// /// # Examples ///
@@ -239,3 +245,127 @@ unsafe fn borrow_mut<'a>(ptr: *mut kernel::ffi::c_void) -> Self::BorrowedMut<'a>unsafe {Pin ::new_unchecked (inner) } } } + +/// A trait for objects that can be wrapped in either one of the reference types [`Owned`] and +/// [`ARef`]. +/// +/// # Examples +/// +/// A minimal example implementation of [`OwnableRefCounted`], [`Ownable`] and its usage with +/// [`ARef`] and [`Owned`] looks like this: +/// +/// ``` +/// # #![expect(clippy::disallowed_names)] +/// # use core::cell::Cell; +/// # use core::ptr::NonNull; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::sync::aref::{ARef, RefCounted}; +/// # use kernel::types::{Owned, Ownable, OwnableRefCounted}; +/// +/// // An internally refcounted struct for demonstration purposes. +/// // +/// // # Invariants +/// // +/// // - `refcount` is always non-zero for a valid object. +/// // - `refcount` is >1 if there is more than one Rust reference to it. +/// // +/// struct Foo { +/// refcount: Cell<usize>, +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// // INVARIANT: We initialize `refcount` to 1, satisfying the invariants. +/// let result = KBox::new( +/// Foo { +/// refcount: Cell::new(1), +/// }, +/// flags::GFP_KERNEL, +/// )?; +/// let result = KBox::into_non_null(result); +/// // SAFETY: +/// // - We just allocated the `Self`, thus it is valid and we own it. +/// // - We can transfer this ownership to the `from_raw` method. +/// Ok(unsafe { Owned::from_raw(result) }) +/// } +/// } +/// +/// // SAFETY: We increment and decrement each time the respective function is called and only free +/// // the `Foo` when the refcount reaches zero. +/// unsafe impl RefCounted for Foo { +/// fn inc_ref(&self) { +/// self.refcount.replace(self.refcount.get() + 1); +/// } +/// +/// unsafe fn dec_ref(this: NonNull<Self>) { +/// // SAFETY: By requirement on calling this function, the refcount is non-zero, +/// // implying the underlying object is valid. +/// let refcount = unsafe { &this.as_ref().refcount }; +/// let new_refcount = refcount.get() - 1; +/// if new_refcount == 0 { +/// // The `Foo` will be dropped when `KBox` goes out of scope. +/// // SAFETY: The [`KBox<Foo>`] is still alive as the old refcount is 1. We can pass +/// // ownership to the [`KBox`] as by requirement on calling this function, +/// // the `Self` will no longer be used by the caller. +/// unsafe { KBox::from_raw(this.as_ptr()) }; +/// } else { +/// refcount.replace(new_refcount); +/// } +/// } +/// } +/// +/// impl OwnableRefCounted for Foo { +/// fn try_from_shared(this: ARef<Self>) -> Result<Owned<Self>, ARef<Self>> { +/// if this.refcount.get() == 1 { +/// // SAFETY: The `Foo` is still alive and has no other Rust references as the refcount +/// // is 1. +/// Ok(unsafe { Owned::from_raw(ARef::into_raw(this)) }) +/// } else { +/// Err(this) +/// } +/// } +/// } +/// +/// impl Ownable for Foo { +/// unsafe fn release(this: NonNull<Self>) { +/// // SAFETY: Using `dec_ref()` from [`RefCounted`] to release is okay, as the refcount is +/// // always 1 for an [`Owned<Foo>`]. +/// unsafe { Foo::dec_ref(this) }; +/// } +/// } +/// +/// let foo = Foo::new()?; +/// let foo = ARef::from(foo); +/// { +/// let bar = foo.clone(); +/// assert!(Owned::try_from(bar).is_err()); +/// } +/// assert!(Owned::try_from(foo).is_ok()); +/// # Ok::<(), Error>(()) +/// ``` +pub trait OwnableRefCounted :RefCounted +Ownable +Sized { +/// Checks if the [`ARef`] is unique and converts it to an [`Owned`] if that is the case. +/// Otherwise it returns again an [`ARef`] to the same underlying object. +fn try_from_shared (this:ARef <Self >) ->Result <Owned <Self >,ARef <Self >>; + +/// Converts the [`Owned`] into an [`ARef`]. +#[inline] +fn into_shared (this:Owned <Self >) ->ARef <Self > { +// SAFETY: `Owned::into_raw` returns a pointer to a valid `Self`, and the `Owned` owned the +// reference count that we now transfer to the new `ARef`. +unsafe {ARef ::from_raw (Owned ::into_raw (this)) } + } +} + +impl <T :OwnableRefCounted >TryFrom <ARef <T >>for Owned <T > { +type Error =ARef <T >; +/// Tries to convert the [`ARef`] to an [`Owned`] by calling +/// [`try_from_shared()`](OwnableRefCounted::try_from_shared). In case the [`ARef`] is not +/// unique, it returns again an [`ARef`] to the same underlying object. +#[inline] +fn try_from (b:ARef <T >) ->Result <Owned <T >,Self ::Error > { +T ::try_from_shared (b) + } +}
rust/kernel/sync/aref.rs +15 -1
@@ -23,6 +23,10 @@ ops::Deref, ptr::NonNull, // }; +use kernel::types::{ +OwnableRefCounted , +Owned ,// +};/// Types that are internally reference counted. ///
@@ -35,7 +39,10 @@/// Note: Implementing this trait allows types to be wrapped in an [`ARef<Self>`]. It requires an /// internal reference count and provides only shared references. If unique references are required /// [`Ownable`](crate::types::Ownable) should be implemented which allows types to be wrapped in an -/// [`Owned<Self>`](crate::types::Owned). +/// [`Owned<Self>`](crate::types::Owned). Implementing the trait +/// [`OwnableRefCounted`] allows to convert between unique and +/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and +/// [`ARef<Self>`](crate::types::Owned)). /// /// # Safety ///
@@ -188,6 +195,13 @@ fn from(b: &T) -> Self { } } +impl <T :OwnableRefCounted >From <Owned <T >>for ARef <T > { +#[inline] +fn from (b:Owned <T >) ->Self { +T ::into_shared (b) + } +} +impl <T :RefCounted >Drop for ARef <T > {fn drop (&mut self) {// SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to
rust/kernel/types.rs +1 -0
@@ -18,6 +18,7 @@pub use crate ::{ owned::{Ownable , +OwnableRefCounted ,Owned ,// }, sync::aref::{
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 7/8] rust: Add `OwnableRefCounted`
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The `OwnableRefCounted` trait is a safe trait but its default `into_shared` method contains an…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The OwnableRefCounted trait is a safe trait but its default into_shared method contains an unsafe block relying on unenforced invariants, violating Rust's soundness rules.
- [Low] Incorrect documentation link for ARef<Self> in aref.rs.
--
commit b7dc8070575155be9312b255a20879f2e905b00f
Author: Oliver Mangold <[email protected]>
rust: Add OwnableRefCounted
Types implementing one of these traits can safely convert between an ARef<T> and an Owned<T>.
Quoted 4 lines
rust/kernel/owned.rs +0
-0
[ ... ]
rust/kernel/owned.rs unsafe fn borrow_mut<'a>(ptr: *mut kernel::ffi::c_void) -> Self::BorrowedMut<'a> · line 360
Quoted 13 lines
rust/kernel/owned.rs +13
-0+pub trait OwnableRefCounted :RefCounted +Ownable +Sized { +/// Checks if the [`ARef`] is unique and converts it to an [`Owned`] if that is the case. +/// Otherwise it returns again an [`ARef`] to the same underlying object. +fn try_from_shared (this:ARef <Self >) ->Result <Owned <Self >,ARef <Self >>; + +/// Converts the [`Owned`] into an [`ARef`]. +#[inline] +fn into_shared (this:Owned <Self >) ->ARef <Self > { +// SAFETY: `Owned::into_raw` returns a pointer to a valid `Self`, and the `Owned` owned the +// reference count that we now transfer to the new `ARef`. +unsafe {ARef ::from_raw (Owned ::into_raw (this)) } + } +}
[Severity: High]
Does this trait need to be marked unsafe?
The OwnableRefCounted trait is currently safe to implement, but the default into_shared() method contains an unsafe block that assumes the Owned<Self> implicitly holds a reference count of 1.
If a developer implements this safe trait for a type whose Owned<Self> does not account for one RefCounted increment, calling into_shared() will pass a pointer to ARef::from_raw() without a corresponding reference increment.
When the resulting ARef is dropped, it will blindly call dec_ref(), which could lead to a reference count underflow, double-free, or use-after-free.
Should OwnableRefCounted be an unsafe trait so that implementers are required to guarantee the reference count invariant?
Quoted 4 lines
rust/kernel/sync/aref.rs +0
-0
[ ... ]
rust/kernel/sync/aref.rs line 45
Quoted 9 lines
rust/kernel/sync/aref.rs +4
-1@@ -35,7 +39,10 @@/// Note: Implementing this trait allows types to be wrapped in an [`ARef<Self>`]. It requires an /// internal reference count and provides only shared references. If unique references are required /// [`Ownable`](crate::types::Ownable) should be implemented which allows types to be wrapped in an -/// [`Owned<Self>`](crate::types::Owned). +/// [`Owned<Self>`](crate::types::Owned). Implementing the trait +/// [`OwnableRefCounted`] allows to convert between unique and +/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and +/// [`ARef<Self>`](crate::types::Owned)).
[Severity: Low]
This isn't a bug, but there appears to be a copy-paste typo in the rustdoc link.
The documentation for ARef<Self> points to crate::types::Owned instead of ARef.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Andreas Hindborg
maintainerRe: [PATCH v18 7/8] rust: Add `OwnableRefCounted`
Quoted 46 lines · <[email protected]> writes:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] TheOwnableRefCountedtrait is a safe trait but its defaultinto_sharedmethod contains anunsafeblock relying on unenforced invariants, violating Rust's soundness rules.
- [Low] Incorrect documentation link forARef<Self>inaref.rs.
--commit
b7dc8070575155be9312b255a20879f2e905b00f
Author: Oliver Mangold <[email protected]>rust: Add
OwnableRefCountedTypes implementing one of these traits can safely convert between an
ARef<T>and anOwned<T>.Quoted 4 lines
rust/kernel/owned.rs +0
-0[ ... ]
rust/kernel/owned.rs unsafe fn borrow_mut<'a>(ptr: *mut kernel::ffi::c_void) -> Self::BorrowedMut<'a> · line 360
Quoted 13 lines
rust/kernel/owned.rs +13
-0+pub trait OwnableRefCounted :RefCounted +Ownable +Sized { +/// Checks if the [`ARef`] is unique and converts it to an [`Owned`] if that is the case. +/// Otherwise it returns again an [`ARef`] to the same underlying object. +fn try_from_shared (this:ARef <Self >) ->Result <Owned <Self >,ARef <Self >>; + +/// Converts the [`Owned`] into an [`ARef`]. +#[inline] +fn into_shared (this:Owned <Self >) ->ARef <Self > { +// SAFETY: `Owned::into_raw` returns a pointer to a valid `Self`, and the `Owned` owned the +// reference count that we now transfer to the new `ARef`. +unsafe {ARef ::from_raw (Owned ::into_raw (this)) } + } +}[Severity: High]
Does this trait need to be marked unsafe?The OwnableRefCounted trait is currently safe to implement, but the default
into_shared()method contains an unsafe block that assumes the Owned<Self> implicitly holds a reference count of 1.If a developer implements this safe trait for a type whose Owned<Self> does not account for one RefCounted increment, calling
into_shared()will pass a pointer toARef::from_raw()without a corresponding reference increment.
Quoted 5 lines
When the resulting ARef is dropped, it will blindly call
dec_ref(), which could lead to a reference count underflow, double-free, or use-after-free.Should OwnableRefCounted be an unsafe trait so that implementers are required to guarantee the reference count invariant?
I will remove the default implementation to solve this issue.
Quoted 22 lines
Quoted 5 lines
rust/kernel/sync/aref.rs +0
-0[ ... ]
rust/kernel/sync/aref.rs line 45
Quoted 9 lines
rust/kernel/sync/aref.rs +4
-1@@ -35,7 +39,10 @@/// Note: Implementing this trait allows types to be wrapped in an [`ARef<Self>`]. It requires an /// internal reference count and provides only shared references. If unique references are required /// [`Ownable`](crate::types::Ownable) should be implemented which allows types to be wrapped in an -/// [`Owned<Self>`](crate::types::Owned). +/// [`Owned<Self>`](crate::types::Owned). Implementing the trait +/// [`OwnableRefCounted`] allows to convert between unique and +/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and +/// [`ARef<Self>`](crate::types::Owned)). [Severity: Low]
This isn't a bug, but there appears to be a copy-paste typo in the rustdoc link.
Quoted 2 lines
The documentation for ARef<Self> points to
crate::types::Ownedinstead of ARef.
Will fix.
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH v18 8/8 rust: page: add `from_raw()`
In reply to Andreas HindborgFrom: Andreas Hindborg <[email protected]>
Add a method to Page that allows construction of an instance from struct page pointer.
--- rust/kernel/page.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
rust/kernel/page.rs +14 -0
@@ -143,6 +143,20 @@ pub fn nid(&self) -> i32 {unsafe { bindings::page_to_nid (self.as_ptr ()) } } +/// Create a `&Page` from a raw `struct page` pointer. +/// +/// # Safety +/// +/// `ptr` must be convertible to a shared reference with a lifetime of `'a`. +#[inline] +pub unsafe fn from_raw <'a>(ptr: *const bindings::page ) -> &'aSelf { +// INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`, so +// the returned reference upholds the type invariant of `Page`. +// SAFETY: By function safety requirements, `ptr` is not null and is convertible to a shared +// reference. +unsafe { &*ptr.cast () } + } +/// Runs a piece of code with this page mapped to an address. /// /// The page is unmapped when this call returns.
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v18 8/8] rust: page: add `from_raw()`
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The `# Safety` documentation for `Page::from_raw` is missing the precondition that `ptr` must…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The # Safety documentation for Page::from_raw is missing the precondition that ptr must point to a valid struct page. --
commit f6aeebdd661d4004190de07e9d991442f793517a
Author: Andreas Hindborg <[email protected]>
rust: page: add from_raw()
This commit adds a from_raw() method to the Page abstraction. It allows the construction of a shared reference to a Page instance directly from a raw struct page pointer.
Quoted 4 lines
rust/kernel/page.rs +0
-0
[ ... ]
rust/kernel/page.rs pub fn nid(&self) -> i32 { · line 152
Quoted 11 lines
rust/kernel/page.rs +7
-0@@ -143,6 +143,20 @@ pub fn nid(&self) -> i32 {unsafe { bindings::page_to_nid (self.as_ptr ()) } } +/// Create a `&Page` from a raw `struct page` pointer. +/// +/// # Safety +/// +/// `ptr` must be convertible to a shared reference with a lifetime of `'a`. +#[inline] +pub unsafe fn from_raw <'a>(ptr: *const bindings::page ) -> &'aSelf {
[Severity: Medium]
Is the safety documentation missing a requirement here?
The # Safety section only requires that ptr is convertible to a shared reference. Under Rust's rules, an uninitialized or dummy pointer could technically be converted to a shared reference if properly aligned.
rust/kernel/page.rs pub fn nid(&self) -> i32 { · line 154
Quoted 2 lines
rust/kernel/page.rs +2
-0+// INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`, so +// the returned reference upholds the type invariant of `Page`.
The invariant justification inside the function explicitly relies on the caller guaranteeing that ptr refers to a valid struct page. Could the # Safety documentation be updated to explicitly require that ptr points to a valid, initialized struct page so that callers do not inadvertently violate the Page type invariant?
Quoted 4 lines
rust/kernel/page.rs +4
-0+// SAFETY: By function safety requirements, `ptr` is not null and is convertible to a shared +// reference. +unsafe { &*ptr.cast () } + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Andreas Hindborg
maintainerRe: [PATCH v18 8/8] rust: page: add `from_raw()`
Quoted 35 lines · <[email protected]> writes:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The# Safetydocumentation forPage::from_rawis missing the precondition thatptrmust point to a validstruct page. --commit
f6aeebdd661d4004190de07e9d991442f793517a
Author: Andreas Hindborg <[email protected]>rust: page: add
from_raw()This commit adds a
from_raw()method to the Page abstraction. It allows the construction of a shared reference to a Page instance directly from a raw struct page pointer.Quoted 4 lines
rust/kernel/page.rs +0
-0[ ... ]
rust/kernel/page.rs pub fn nid(&self) -> i32 { · line 152
Quoted 11 lines
rust/kernel/page.rs +7
-0@@ -143,6 +143,20 @@ pub fn nid(&self) -> i32 {unsafe { bindings::page_to_nid (self.as_ptr ()) } } +/// Create a `&Page` from a raw `struct page` pointer. +/// +/// # Safety +/// +/// `ptr` must be convertible to a shared reference with a lifetime of `'a`. +#[inline] +pub unsafe fn from_raw <'a>(ptr: *const bindings::page ) -> &'aSelf {[Severity: Medium]
Is the safety documentation missing a requirement here?
Quoted 3 lines
The # Safety section only requires that ptr is convertible to a shared reference. Under Rust's rules, an uninitialized or dummy pointer could technically be converted to a shared reference if properly aligned.
This is not correct. A pointer is only convertible to a shared reference if it is pointing to properly initialized data [1].
Quoted 9 lines
rust/kernel/page.rs pub fn nid(&self) -> i32 { · line 154
Quoted 3 lines
rust/kernel/page.rs +2
-0+// INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`, so +// the returned reference upholds the type invariant of `Page`. The invariant justification inside the function explicitly relies on the caller guaranteeing that ptr refers to a valid struct page. Could the # Safety documentation be updated to explicitly require that ptr points to a valid, initialized struct page so that callers do not inadvertently violate the Page type invariant?
For ptr to be convertible to a shared reference, it must point to valid and initialized data.
Best regards,
Andreas Hindborg
[1] https://doc.rust-lang.org/stable/core/ptr/index.html#pointer-to-reference-conversion