rust: add `Ownable` trait and `Owned` type
Subsystems (23)
Andreas Hindborg
maintainerv20 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 v20:
- Fix a few copy/paste errors in safety comments (Sashiko).
- Use self.page.get() rather than Opaque::cast_into (Alice).
- Add a space between generics in a comment (Sashiko).
- Change a safety comment to reference Box rather than KBox (Sashiko).
- Link to v19: https://msgid.link/[email protected]
Changes in v19:
- Update workqueue.rs and the aref module docs to use RefCounted instead of AlwaysRefCounted (Sashiko).
- Remove the default OwnableRefCounted::into_shared implementation to keep the trait safe (Sashiko).
- Fix the ARef<Self> rustdoc link (Sashiko).
- Reuse Owned::into_raw/from_raw in the ForeignOwnable implementation (Gary).
- Link to v18: https://msgid.link/[email protected]
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]>
To: Ira Weiny <[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]
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 | 373 +++++++++++++++++++++++++++++++++++ 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 | 84 +++++--- rust/kernel/task.rs | 13 +- rust/kernel/types.rs | 12 ++ rust/kernel/usb.rs | 17 +- rust/kernel/workqueue.rs | 8 +- 28 files changed, 728 insertions(+), 186 deletions(-)
---
base-commit: 8d3ae59288f1e7d58d76558a6ee96d533bc5019f
change-id: 20250305-unique-ref-29fcd675f9e9
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
maintainerPATCH v20 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: `Box::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 v20 1/8] rust: alloc: add `KBox::into_non_null`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
Add a method to consume a
Box<T, A>and return aNonNull<T>. This is a convenience wrapper aroundSelf::into_rawfor callers that need aNonNullpointer rather than a raw pointer.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=1
Re: [PATCH v20 1/8] rust: alloc: add `KBox::into_non_null`
In reply to Andreas HindborgQuoted 7 lines · Andreas Hindborg
Add a method to consume a
Box<T, A>and return aNonNull<T>. This is a convenience wrapper aroundSelf::into_rawfor callers that need aNonNullpointer rather than a raw pointer.Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Gary Guo <[email protected]>
Andreas Hindborg
maintainerPATCH v20 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 v20 2/8] rust: types: Add Ownable/Owned types
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The safety documentation for `Owned::from_raw` fails to require the caller to uphold the pinning…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The safety documentation for Owned::from_raw fails to require the caller to uphold the pinning invariant. --
--- Patch [2]: [PATCH v20 2/8] rust: types: Add Ownable/Owned types --- commit 82ccf756b593f4c76a8a6694855add1d65c27d53
Author: Asahi Lina <[email protected]>
rust: types: Add Ownable/Owned types
This commit introduces Ownable and Owned types for unique ownership of objects with custom drop logic. It provides a mechanism for C-allocated objects to be owned by Rust without generic allocators, delegating resource management to the type itself.
Quoted 5 lines
rust/kernel/owned.rs new file +0
-0
[ ... ]
rust/kernel/owned.rs line 127
Quoted 11 lines
rust/kernel/owned.rs new file +11
-0+/// 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: Medium]
Should the safety documentation for from_raw() explicitly require the caller to uphold the pinning invariant?
Since as_pin_mut() returns a Pin<&mut T> and the internal comments note that T is treated as pinned from now on, it seems the caller must guarantee this.
If a caller provides an unpinned allocation, retrieves the pointer later with into_raw(), and safely moves the object, it could violate the pinning assumptions established here. Could this lead to memory corruption if the pinned object is self-referential or registered elsewhere?
Quoted 4 lines
rust/kernel/owned.rs new file +4
-0+// INVARIANT: By function safety requirement we satisfy the first invariant of `Self`. +// We treat `T` as pinned from now on. +Self { ptr } + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Andreas Hindborg
maintainerPATCH v20 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 | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+)
rust/kernel/owned.rs +50 -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,51 @@ 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 { +Owned ::into_raw (self).as_ptr ().cast () + } + +#[inline] +unsafe fn from_foreign (ptr: *mut kernel::ffi::c_void ) ->Self { +// SAFETY: By function safety contract, `ptr` came from `into_foreign` and cannot be null. +let ptr =unsafe {NonNull ::new_unchecked (ptr.cast ()) }; + +// SAFETY: 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. +unsafe {Owned ::from_raw (ptr) } + } + +#[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 v20 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
Andreas Hindborg
maintainerPATCH v20 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 v20 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
Alice Ryhl
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
In reply to Andreas Hindborgrust/kernel/page.rs impl Page { · line 132
Quoted 4 lines · Andreas Hindborg
rust/kernel/page.rs +4
-0+// SAFETY: We just successfully allocated a page, so we now have ownership of the newly +// allocated page. We transfer that ownership to the new `Owned<Page>` object. +// Since `Page` is transparent, we can cast the pointer directly. +Ok (unsafe {Owned ::from_raw (page.cast ()) })
This doesn't satisfy the safety requirements of Owned::from_raw() because the page may be used with vm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs before Page::release() is called.
Alice
Gary Guo
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 10 lines · Alice Ryhl
rust/kernel/page.rs impl Page { · line 132
Quoted 4 lines · Andreas Hindborg
rust/kernel/page.rs +4
-0+// SAFETY: We just successfully allocated a page, so we now have ownership of the newly +// allocated page. We transfer that ownership to the new `Owned<Page>` object. +// Since `Page` is transparent, we can cast the pointer directly. +Ok (unsafe {Owned ::from_raw (page.cast ()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.
I suppose the existing vm_insert_page() abstraction we have is already problematic, because it uses &Page?
Maybe we want to change the API to use ARef<Page> so it already has to be shared? Conceptually it takes a reference count from a &Page, which isn't possible because Page is not AlwaysRefCounted, so it needs a &ARef<Page> to be able to do that op.
Best,
Gary
Alice Ryhl
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
rust/kernel/page.rs impl Page { · line 132
Quoted 4 lines · Andreas Hindborg
rust/kernel/page.rs +4
-0+// SAFETY: We just successfully allocated a page, so we now have ownership of the newly +// allocated page. We transfer that ownership to the new `Owned<Page>` object. +// Since `Page` is transparent, we can cast the pointer directly. +Ok (unsafe {Owned ::from_raw (page.cast ()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.
Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.
Honestly, the problem is the safety requirements of Owned::from_raw(). Pages have a "special" main reference, and free_page() does more than put_page(). It even does something when the refcount does not hit zero.
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls free_page(), *plus* any number of ARef<Page> references that invoke put_page() on drop. This way, the owned page controls the special drop codepath.
Alice
Andreas Hindborg
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
rust/kernel/page.rs impl Page { · line 132
Quoted 4 lines · Andreas Hindborg
rust/kernel/page.rs +4
-0+// SAFETY: We just successfully allocated a page, so we now have ownership of the newly +// allocated page. We transfer that ownership to the new `Owned<Page>` object. +// Since `Page` is transparent, we can cast the pointer directly. +Ok (unsafe {Owned ::from_raw (page.cast ()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.
This does not mesh well with the model of Owned behaving like UniqueArc to ARef behaving like an Arc.
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single Owned<Page> and a number of ARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?
My intuition here would be to follow Garry's suggestion and have vm_insert_page take an ARef<Page>. Can you elaborate why this is not an option?
Best regards,
Andreas Hindborg
Alice Ryhl
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 30 lines · Andreas Hindborg
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
rust/kernel/page.rs impl Page { · line 132
Quoted 4 lines · Andreas Hindborg
rust/kernel/page.rs +4
-0+// SAFETY: We just successfully allocated a page, so we now have ownership of the newly +// allocated page. We transfer that ownership to the new `Owned<Page>` object. +// Since `Page` is transparent, we can cast the pointer directly. +Ok (unsafe {Owned ::from_raw (page.cast ()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.
Quoted 7 lines
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.This does not mesh well with the model of
Ownedbehaving likeUniqueArctoARefbehaving like anArc.
It's a different case, I agree.
Quoted 4 lines
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single
Owned<Page>and a number ofARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?
Yes, it's legal.
Quoted 3 lines
My intuition here would be to follow Garry's suggestion and have
vm_insert_pagetake anARef<Page>. Can you elaborate why this is not an option?
That would be the wrong ownership semantics. The C side increments the refcount rather than take ownership of a passed-in refcount, so the correct argument type is &Page.
Now, for the use-case in Binder I believe we could switch to put_page(), as we don't need the extra stuff from free_page(), in which case we only want ARef<Page> and do not require Owned support. But as long as we are calling free_page(), it needs to not be clonable.
Alice
Andreas Hindborg
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 48 lines · Alice Ryhl
Quoted 30 lines · Andreas Hindborg
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
rust/kernel/page.rs impl Page { · line 132
Quoted 4 lines · Andreas Hindborg
rust/kernel/page.rs +4
-0+// SAFETY: We just successfully allocated a page, so we now have ownership of the newly +// allocated page. We transfer that ownership to the new `Owned<Page>` object. +// Since `Page` is transparent, we can cast the pointer directly. +Ok (unsafe {Owned ::from_raw (page.cast ()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.Quoted 7 lines
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.This does not mesh well with the model of
Ownedbehaving likeUniqueArctoARefbehaving like anArc.It's a different case, I agree.
Quoted 4 lines
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single
Owned<Page>and a number ofARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?Yes, it's legal.
Quoted 7 lines
Quoted 3 lines
My intuition here would be to follow Garry's suggestion and have
vm_insert_pagetake anARef<Page>. Can you elaborate why this is not an option?That would be the wrong ownership semantics. The C side increments the refcount rather than take ownership of a passed-in refcount, so the correct argument type is &Page.
Or &ARef<Page>? Because with Page being Ownable it would not be OK to increment the refcount from just a &Page.
Quoted 5 lines
Now, for the use-case in Binder I believe we could switch to
put_page(), as we don't need the extra stuff fromfree_page(), in which case we only want ARef<Page> and do not require Owned support. But as long as we are callingfree_page(), it needs to not be clonable.
You are calling __free_page directly in binder? I could not find this with grep except in the C binder. Is this code you are calling into from Rust binder?
From __free_pages() kernel-doc (mm/page_alloc.c):
Quoted 6 lines
If the last reference to this page is speculative, it will be released by
put_page()which only frees the first page of a non-compound allocation. [...] **If you want to use the page's reference count to decide when to free the allocation, you should allocate a compound page, and useput_page()instead of __free_pages().**
I guess this is what you are referring to? We could change Page to this style as well and all would be fine I think?
At any rate, today I learned about Pfn walkers, compaction, memory-failure, etc. that take transient refcounts pages. With that in mind we need to reformulate the invariant of Ownable to exclude optimistic transient references.
Best regards,
Andreas Hindborg
Alice Ryhl
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 55 lines · Andreas Hindborg
Quoted 52 lines · Alice Ryhl
Quoted 30 lines · Andreas Hindborg
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
Review
Quoted 4 lines · Andreas Hindborg
(quoted diff) +4
-0+ // SAFETY: We just successfully allocated a page, so we now have ownership of the newly + // allocated page. We transfer that ownership to the new `Owned<Page>` object. + // Since `Page` is transparent, we can cast the pointer directly. + Ok(unsafe { Owned::from_raw(page.cast()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.Quoted 7 lines
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.This does not mesh well with the model of
Ownedbehaving likeUniqueArctoARefbehaving like anArc.It's a different case, I agree.
Quoted 4 lines
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single
Owned<Page>and a number ofARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?Yes, it's legal.
Quoted 3 lines
My intuition here would be to follow Garry's suggestion and have
vm_insert_pagetake anARef<Page>. Can you elaborate why this is not an option?
Quoted 6 lines
Quoted 3 lines
That would be the wrong ownership semantics. The C side increments the refcount rather than take ownership of a passed-in refcount, so the correct argument type is &Page.
Or
&ARef<Page>? Because withPagebeingOwnableit would not be OK to increment the refcount from just a&Page.
That's just a limitation in your traits. There is no problem with creating a refcount from just a &Page.
Quoted 9 lines
Quoted 5 lines
Now, for the use-case in Binder I believe we could switch to
put_page(), as we don't need the extra stuff fromfree_page(), in which case we only want ARef<Page> and do not require Owned support. But as long as we are callingfree_page(), it needs to not be clonable.You are calling
__free_pagedirectly in binder? I could not find this with grep except in the C binder. Is this code you are calling into from Rust binder?
Via the Drop of Page, not directly of course.
Quoted 9 lines
From
__free_pages()kernel-doc (mm/page_alloc.c):Quoted 6 lines
If the last reference to this page is speculative, it will be released by
put_page()which only frees the first page of a non-compound allocation. [...] **If you want to use the page's reference count to decide when to free the allocation, you should allocate a compound page, and useput_page()instead of __free_pages().**
Quoted 7 lines
I guess this is what you are referring to? We could change
Pageto this style as well and all would be fine I think?At any rate, today I learned about Pfn walkers, compaction, memory-failure, etc. that take transient refcounts pages. With that in mind we need to reformulate the invariant of
Ownableto exclude optimistic transient references.
Yes we can switch Rust Binder to use put_page() and have Page not implement Ownable at all. That would be okay, because Binder's pages are not higher order. But this case still does highlight that Ownable<_> currently does not address the use-case where the Ownable<T> is a special reference there can only be one of, rather than a completely unique reference.
For instance, the GPUVM abstraction would be another case where Ownable<_> could be used if we have this other model where Ownable<_> and ARef<_> are legal at the same time. Currently GPUVM uses a special UniqueRefGpuVm type to solve this problem.
Alice
Andreas Hindborg
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 60 lines · Alice Ryhl
Quoted 59 lines · Andreas Hindborg
Quoted 55 lines · Alice Ryhl
Quoted 30 lines · Andreas Hindborg
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
Review
Quoted 4 lines · Andreas Hindborg
(quoted diff) +4
-0+ // SAFETY: We just successfully allocated a page, so we now have ownership of the newly + // allocated page. We transfer that ownership to the new `Owned<Page>` object. + // Since `Page` is transparent, we can cast the pointer directly. + Ok(unsafe { Owned::from_raw(page.cast()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.Quoted 7 lines
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.This does not mesh well with the model of
Ownedbehaving likeUniqueArctoARefbehaving like anArc.It's a different case, I agree.
Quoted 4 lines
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single
Owned<Page>and a number ofARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?Yes, it's legal.
Quoted 3 lines
My intuition here would be to follow Garry's suggestion and have
vm_insert_pagetake anARef<Page>. Can you elaborate why this is not an option?That would be the wrong ownership semantics. The C side increments the refcount rather than take ownership of a passed-in refcount, so the correct argument type is &Page.
Quoted 5 lines
Quoted 2 lines
Or
&ARef<Page>? Because withPagebeingOwnableit would not be OK to increment the refcount from just a&Page.That's just a limitation in your traits. There is no problem with creating a refcount from just a &Page.
Yes, I agree. The limitation is by design. My point is, vm_insert_page can work fine with the &ARef<Page> type. So if that would be OK with you, I would patch that as part of this patch.
Quoted 25 lines
Quoted 10 lines
Quoted 6 lines
Now, for the use-case in Binder I believe we could switch to
put_page(), as we don't need the extra stuff fromfree_page(), in which case we only want ARef<Page> and do not require Owned support. But as long as we are callingfree_page(), it needs to not be clonable.You are calling
__free_pagedirectly in binder? I could not find this with grep except in the C binder. Is this code you are calling into from Rust binder?Via the Drop of Page, not directly of course.
Quoted 12 lines
From
__free_pages()kernel-doc (mm/page_alloc.c):Quoted 6 lines
If the last reference to this page is speculative, it will be released by
put_page()which only frees the first page of a non-compound allocation. [...] **If you want to use the page's reference count to decide when to free the allocation, you should allocate a compound page, and useput_page()instead of __free_pages().**I guess this is what you are referring to? We could change
Pageto this style as well and all would be fine I think?
Quoted 8 lines
Quoted 4 lines
At any rate, today I learned about Pfn walkers, compaction, memory-failure, etc. that take transient refcounts pages. With that in mind we need to reformulate the invariant of
Ownableto exclude optimistic transient references.Yes we can switch Rust Binder to use
put_page()and have Page not implement Ownable at all. That would be okay, because Binder's pages are not higher order.
As far as I can tell, we can also switch Owned<Page> to allocate the page with __GFP_COMP and use put_page in drop.
Quoted 4 lines
But this case still does highlight that
Ownable<_> currently does not address the use-case where the Ownable<T> is a special reference there can only be one of, rather than a completely unique reference.
This is not the use case Ownable aims to solve.
Quoted 4 lines
For instance, the GPUVM abstraction would be another case where Ownable<_> could be used if we have this other model where Ownable<_> and ARef<_> are legal at the same time. Currently GPUVM uses a special UniqueRefGpuVm type to solve this problem.
I am wondering if we can make case I intend to solve (Ownable is a unique reference) coexist with the "at most one of this ref can exist". The "at most one of this kind" sounds similar to the ListArc use case to me, which is a different problem.
Best regards,
Andreas Hindborg
Alice Ryhl
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 66 lines · Andreas Hindborg
Quoted 63 lines · Alice Ryhl
Quoted 61 lines · Andreas Hindborg
Quoted 48 lines · Alice Ryhl
Quoted 30 lines · Andreas Hindborg
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
Review
Quoted 4 lines · Andreas Hindborg
(quoted diff) +4
-0+ // SAFETY: We just successfully allocated a page, so we now have ownership of the newly + // allocated page. We transfer that ownership to the new `Owned<Page>` object. + // Since `Page` is transparent, we can cast the pointer directly. + Ok(unsafe { Owned::from_raw(page.cast()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.Quoted 7 lines
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.This does not mesh well with the model of
Ownedbehaving likeUniqueArctoARefbehaving like anArc.It's a different case, I agree.
Quoted 4 lines
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single
Owned<Page>and a number ofARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?Yes, it's legal.
Quoted 7 lines
Quoted 3 lines
My intuition here would be to follow Garry's suggestion and have
vm_insert_pagetake anARef<Page>. Can you elaborate why this is not an option?That would be the wrong ownership semantics. The C side increments the refcount rather than take ownership of a passed-in refcount, so the correct argument type is &Page.
Or
&ARef<Page>? Because withPagebeingOwnableit would not be OK to increment the refcount from just a&Page.
Quoted 6 lines
Quoted 2 lines
That's just a limitation in your traits. There is no problem with creating a refcount from just a &Page.
Yes, I agree. The limitation is by design. My point is,
vm_insert_pagecan work fine with the&ARef<Page>type. So if that would be OK with you, I would patch that as part of this patch.
IMO, Page should implement AlwaysRefcounted and this method should take &Page. Anything else just adds limitations that are not needed. But I'm ok not implementing Ownable for it.
Quoted 29 lines
Quoted 29 lines
Quoted 9 lines
Quoted 5 lines
Now, for the use-case in Binder I believe we could switch to
put_page(), as we don't need the extra stuff fromfree_page(), in which case we only want ARef<Page> and do not require Owned support. But as long as we are callingfree_page(), it needs to not be clonable.You are calling
__free_pagedirectly in binder? I could not find this with grep except in the C binder. Is this code you are calling into from Rust binder?Via the Drop of Page, not directly of course.
Quoted 16 lines
From
__free_pages()kernel-doc (mm/page_alloc.c):Quoted 6 lines
If the last reference to this page is speculative, it will be released by
put_page()which only frees the first page of a non-compound allocation. [...] **If you want to use the page's reference count to decide when to free the allocation, you should allocate a compound page, and useput_page()instead of __free_pages().**I guess this is what you are referring to? We could change
Pageto this style as well and all would be fine I think?At any rate, today I learned about Pfn walkers, compaction, memory-failure, etc. that take transient refcounts pages. With that in mind we need to reformulate the invariant of
Ownableto exclude optimistic transient references.
Quoted 6 lines
Quoted 3 lines
Yes we can switch Rust Binder to use
put_page()and have Page not implement Ownable at all. That would be okay, because Binder's pages are not higher order.As far as I can tell, we can also switch
Owned<Page>to allocate the page with__GFP_COMPand useput_pagein drop.
I'm not entirely sure if __GFP_COMP is needed, since the page is order zero to begin with, so I don't think it makes a difference.
Quoted 6 lines
Quoted 4 lines
But this case still does highlight that
Ownable<_> currently does not address the use-case where the Ownable<T> is a special reference there can only be one of, rather than a completely unique reference.This is not the use case
Ownableaims to solve.
Maybe not, but then it doesn't apply to Page.
Quoted 9 lines
Quoted 4 lines
For instance, the GPUVM abstraction would be another case where Ownable<_> could be used if we have this other model where Ownable<_> and ARef<_> are legal at the same time. Currently GPUVM uses a special UniqueRefGpuVm type to solve this problem.
I am wondering if we can make case I intend to solve (Ownable is a unique reference) coexist with the "at most one of this ref can exist". The "at most one of this kind" sounds similar to the
ListArcuse case to me, which is a different problem.
I think they can co-exist. If AlwaysRefcounted is implemented, it is the ListArc use-case. If Refcounted but not AlwaysRefcounted is implemented, it is UniqueArc use-case.
Alice
Andreas Hindborg
maintainerRe: [PATCH v20 4/8] rust: page: convert to `Ownable`'
Quoted 70 lines · Alice Ryhl
Quoted 69 lines · Andreas Hindborg
Quoted 65 lines · Alice Ryhl
Quoted 55 lines · Andreas Hindborg
Quoted 52 lines · Alice Ryhl
Quoted 30 lines · Andreas Hindborg
Quoted 27 lines · Alice Ryhl
Quoted 13 lines · Gary Guo
Quoted 10 lines · Alice Ryhl
Review
Quoted 4 lines · Andreas Hindborg
(quoted diff) +4
-0+ // SAFETY: We just successfully allocated a page, so we now have ownership of the newly + // allocated page. We transfer that ownership to the new `Owned<Page>` object. + // Since `Page` is transparent, we can cast the pointer directly. + Ok(unsafe { Owned::from_raw(page.cast()) })This doesn't satisfy the safety requirements of
Owned::from_raw()because the page may be used withvm_insert_page(), which increments its refcount and causes it to be shared the vma system, and this occurs beforePage::release()is called.Quoted 7 lines
I suppose the existing
vm_insert_page()abstraction we have is already problematic, because it uses&Page?Maybe we want to change the API to use
ARef<Page>so it already has to be shared? Conceptually it takes a reference count from a&Page, which isn't possible becausePageis notAlwaysRefCounted, so it needs a&ARef<Page>to be able to do that op.Honestly, the problem is the safety requirements of
Owned::from_raw(). Pages have a "special" main reference, andfree_page()does more thanput_page(). It even does something when the refcount does not hit zero.Quoted 7 lines
Quoted 4 lines
The correct behavior for Page is to allow the user to hold one Owned<Page> whose drop calls
free_page(), *plus* any number of ARef<Page> references that invokeput_page()on drop. This way, the owned page controls the special drop codepath.This does not mesh well with the model of
Ownedbehaving likeUniqueArctoARefbehaving like anArc.It's a different case, I agree.
Quoted 4 lines
Please help me understand; with page having a main ref and an auxiliary refcount, if we model that with a single
Owned<Page>and a number ofARef<Page>, what would happen in the case where the main ref (Owned) is dropped first? Is this legal?Yes, it's legal.
Quoted 3 lines
My intuition here would be to follow Garry's suggestion and have
vm_insert_pagetake anARef<Page>. Can you elaborate why this is not an option?Quoted 6 lines
Quoted 3 lines
That would be the wrong ownership semantics. The C side increments the refcount rather than take ownership of a passed-in refcount, so the correct argument type is &Page.
Or
&ARef<Page>? Because withPagebeingOwnableit would not be OK to increment the refcount from just a&Page.That's just a limitation in your traits. There is no problem with creating a refcount from just a &Page.
Quoted 7 lines
Quoted 3 lines
Yes, I agree. The limitation is by design. My point is,
vm_insert_pagecan work fine with the&ARef<Page>type. So if that would be OK with you, I would patch that as part of this patch.IMO, Page should implement AlwaysRefcounted and this method should take &Page. Anything else just adds limitations that are not needed. But I'm ok not implementing Ownable for it.
Ok, I think you have me convinced. Mainly because Page as it is has no benefit of exclusive access.
Quoted 33 lines
Quoted 33 lines
Quoted 32 lines
Quoted 9 lines
Quoted 5 lines
Now, for the use-case in Binder I believe we could switch to
put_page(), as we don't need the extra stuff fromfree_page(), in which case we only want ARef<Page> and do not require Owned support. But as long as we are callingfree_page(), it needs to not be clonable.You are calling
__free_pagedirectly in binder? I could not find this with grep except in the C binder. Is this code you are calling into from Rust binder?Via the Drop of Page, not directly of course.
Quoted 9 lines
From
__free_pages()kernel-doc (mm/page_alloc.c):Quoted 6 lines
If the last reference to this page is speculative, it will be released by
put_page()which only frees the first page of a non-compound allocation. [...] **If you want to use the page's reference count to decide when to free the allocation, you should allocate a compound page, and useput_page()instead of __free_pages().**Quoted 7 lines
I guess this is what you are referring to? We could change
Pageto this style as well and all would be fine I think?At any rate, today I learned about Pfn walkers, compaction, memory-failure, etc. that take transient refcounts pages. With that in mind we need to reformulate the invariant of
Ownableto exclude optimistic transient references.Yes we can switch Rust Binder to use
put_page()and have Page not implement Ownable at all. That would be okay, because Binder's pages are not higher order.
Quoted 5 lines
Quoted 2 lines
As far as I can tell, we can also switch
Owned<Page>to allocate the page with__GFP_COMPand useput_pagein drop.I'm not entirely sure if
__GFP_COMPis needed, since the page is order zero to begin with, so I don't think it makes a difference.
With alignment on Page: AlwaysRefCounted, I think this becomes orthogonal. When we want to support allocations of more than one page, we should probably make them compound pages (folios) and manage them with the refcount (put_page), rather than non-compound high-order pages. But this can wait.
Quoted 8 lines
Quoted 6 lines
Quoted 4 lines
But this case still does highlight that
Ownable<_> currently does not address the use-case where the Ownable<T> is a special reference there can only be one of, rather than a completely unique reference.This is not the use case
Ownableaims to solve.Maybe not, but then it doesn't apply to Page.
I agree.
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
For instance, the GPUVM abstraction would be another case where Ownable<_> could be used if we have this other model where Ownable<_> and ARef<_> are legal at the same time. Currently GPUVM uses a special UniqueRefGpuVm type to solve this problem.
Quoted 8 lines
Quoted 4 lines
I am wondering if we can make case I intend to solve (Ownable is a unique reference) coexist with the "at most one of this ref can exist". The "at most one of this kind" sounds similar to the
ListArcuse case to me, which is a different problem.I think they can co-exist. If AlwaysRefcounted is implemented, it is the ListArc use-case. If Refcounted but not AlwaysRefcounted is implemented, it is UniqueArc use-case.
I see.
So for v21 I will implement RefCounted + AlwaysRefCounted for Page and drop the Ownable implementation, have alloc_page() return ARef<Page>, keep vm_insert_page() taking &Page, and switch Rust Binder to hold ARef<Page>.
I will also include the SafePage/ExclusivePage series [1] in v21 as a user of Ownable with a few modifications. It will no longer be possible for this type to deref to &Page, due to Page: AlwaysRefCounted and vm_insert_page taking refcounts through &Page.
Best regards,
Andreas Hindborg
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Re: [PATCH v20 4/8] rust: page: convert to `Ownable`
In reply to Andreas HindborgQuoted 2 lines · Andreas Hindborg
rust/kernel/alloc/allocator.rs | 19 +++--- rust/kernel/alloc/allocator/iter.rs | 6 +-
rust/kernel/alloc/allocator.rs impl Vmalloc { · line 205
Quoted 2 lines
rust/kernel/alloc/allocator.rs +1
-1-pub unsafe fn to_page <'a>(ptr:NonNull <u8 >) -> page::BorrowedPage <'a> { +pub unsafe fn to_page <'a>(ptr:NonNull <u8 >) -> &'a page::Page {
Of course the mechanical conversion is fine as is, but while at it, mind to just import Page, such that the odd page::Page thing goes away?
Thanks,
Danilo
Andreas Hindborg
maintainerPATCH v20 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 | 59 +++++++++++++++++++++++++---------------- rust/kernel/task.rs | 13 +++++++-- rust/kernel/types.rs | 12 ++++++--- rust/kernel/usb.rs | 17 +++++++++--- rust/kernel/workqueue.rs | 8 +++--- 22 files changed, 260 insertions(+), 77 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
@@ -17,7 +17,8 @@ prelude::*, sync::aref::{ARef , -AlwaysRefCounted ,// +AlwaysRefCounted , +RefCounted ,// }, types::{ NotThreadSafe,
@@ -362,7 +363,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 ,C :DeviceContext >AlwaysRefCounted for Device <T ,C > { +unsafe impl <T : drm::Driver ,C :DeviceContext >RefCounted for Device <T ,C > {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 ()) };
@@ -377,6 +378,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 ,C :DeviceContext >AlwaysRefCounted for Device <T ,C > {} +impl <T : drm::Driver ,C :DeviceContext >AsRef <device::Device >for Device <T ,C > {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
@@ -21,7 +21,7 @@ prelude::*, sync::aref::{ ARef, - AlwaysRefCounted, // + RefCounted, // }, types::Opaque, };
@@ -34,7 +34,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]
@@ -47,7 +47,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 ),+ )?
@@ -66,6 +66,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))]
@@ -109,7 +117,7 @@ fn close(_obj: &DriverAllocImpl<Self>, _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<I2cAdapter>` 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<I2cClient>` 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
@@ -24,6 +24,10 @@ }, of, prelude::*, + sync::aref::{ + AlwaysRefCounted, + RefCounted, // + }, types::Opaque, ThisModule, // };
@@ -519,7 +523,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 ()) };
@@ -531,6 +535,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 +36 -23
152 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
rust/kernel/workqueue.rs +4 -4
@@ -192,7 +192,7 @@ sync::{ aref::{ARef , -AlwaysRefCounted ,// +RefCounted ,// }, Arc, LockClassKey, //
@@ -954,7 +954,7 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Pin<KBox<T>>// implementation of `WorkItemPointer` for `ARef<T>`. unsafe impl <T ,const ID :u64 >WorkItemPointer <ID >for ARef <T >where -T :AlwaysRefCounted , +T :RefCounted ,T :WorkItem <ID ,Pointer =Self >,T :HasWork <T ,ID >, {
@@ -987,7 +987,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T>// requirements of `WorkItemPointer`. unsafe impl <T ,const ID :u64 >RawWorkItem <ID >for ARef <T >where -T :AlwaysRefCounted , +T :RefCounted ,T :WorkItem <ID ,Pointer =Self >,T :HasWork <T ,ID >, {
@@ -1020,7 +1020,7 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for ARef<T> where T: WorkItem<ID, Pointer = Self>, T: HasDelayedWork<T, ID>, - T: AlwaysRefCounted, + T: RefCounted, { }
Signature · 1 line
2.51.2
[email protected]
AI reviewRe: [PATCH v20 5/8] rust: rename `AlwaysRefCounted` to `RefCounted`.
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The `GpuVm` and `GpuVmBo` types in the DRM GPUVM subsystem were not updated to reflect the…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The GpuVm and GpuVmBo types in the DRM GPUVM subsystem were not updated to reflect the AlwaysRefCounted and RefCounted trait split, resulting in a compilation failure. --
--- Patch [5]: [PATCH v20 5/8] rust: rename AlwaysRefCounted to RefCounted. --- commit 7d343e09ba4b06050b444e30c1113ca349f25a78
Author: Oliver Mangold <[email protected]>
rust: rename AlwaysRefCounted to RefCounted.
This commit splits the AlwaysRefCounted trait into RefCounted and a new marker trait AlwaysRefCounted. It updates several subsystems to implement the new RefCounted trait while preserving the AlwaysRefCounted marker where appropriate.
Quoted 4 lines
rust/kernel/sync/aref.rs +0
-0
[ ... ]
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: Low]
Did this patch miss updating the DRM GPUVM subsystem?
When CONFIG_RUST_DRM_GPUVM is enabled, the build fails because GpuVm and GpuVmBo are still trying to implement inc_ref() and dec_ref() under the AlwaysRefCounted trait instead of RefCounted.
For example, in rust/kernel/drm/gpuvm/mod.rs:
unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVm<T> {
fn inc_ref(&self) {
// SAFETY: By type invariants, the allocation is managed by the refcount in self.vm.
unsafe { bindings::drm_gpuvm_get(self.vm.get()) };
}
...
}And similarly in rust/kernel/drm/gpuvm/vm_bo.rs for GpuVmBo:
unsafe impl<T: DriverGpuVm> AlwaysRefCounted for GpuVmBo<T> {
fn inc_ref(&self) {
// SAFETY: By type invariants, the allocation is managed by the refcount in self.inner.
unsafe { bindings::drm_gpuvm_bo_get(self.inner.get()) };
}
...
}Should these implementations be updated to use the new RefCounted trait to match the changes made to the other subsystems?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Re: [PATCH v20 5/8] rust: rename `AlwaysRefCounted` to `RefCounted`.
In reply to Andreas HindborgHello,
Quoted 27 lines · Andreas Hindborg
rust/kernel/pwm.rs +6
-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.
rust/kernel/pwm.rs unsafe fn dec_ref(obj: NonNull<Chip<T>>) { · line 660
Quoted 10 lines
rust/kernel/pwm.rs +4
-0@@ -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`
I don't understand that, but if this is considered ok by the Rust folks, I'm fine with merging it via their tree.
Best regards
Uwe
Andreas Hindborg
maintainerPATCH v20 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 v20 6/8] rust: Add missing SAFETY documentation for `ARef` example
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Mismatched and incorrect SAFETY comments in the `ARef::into_raw` doctest, alongside an unsound…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Mismatched and incorrect SAFETY comments in the ARef::into_raw doctest, alongside an unsound RefCounted trait implementation. --
--- Patch [6]: [PATCH v20 6/8] rust: Add missing SAFETY documentation for ARef example --- commit 1891eeeba9b2ed0af7d99f9518dcd85941d2518c
Author: Oliver Mangold <[email protected]>
rust: Add missing SAFETY documentation for ARef example
This commit updates the rustdoc example for ARef to replace the "TODO" SAFETY comments with explanations for the RefCounted trait implementation and ARef::from_raw call.
Quoted 4 lines
rust/kernel/sync/aref.rs pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { · line 150
Quoted 10 lines
rust/kernel/sync/aref.rs +3
-1@@ -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>) {}
[Severity: Low]
Are the SAFETY comments for the trait implementation and from_raw call swapped here?
This comment justifies the caller requirement of ARef::from_raw (owning an increment), rather than the trait's own safety requirement (that increments keep the object alive).
Additionally, does this explanation overlook the fact that the stack-allocated variable data will eventually go out of scope and be freed?
If a developer copies this pattern and calls ARef::clone(), could it extend the pointer's lifetime beyond the stack frame without keeping the underlying object alive?
rust/kernel/sync/aref.rs pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { · line 156
Quoted 7 lines
rust/kernel/sync/aref.rs +1
-1@@ -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) };
[Severity: Low]
Does this comment justify the object's lifetime (which is the responsibility of the RefCounted trait implementation) instead of addressing the specific safety requirement of ARef::from_raw?
The from_raw method requires the caller to own a reference count increment.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Re: [PATCH v20 6/8] rust: Add missing SAFETY documentation for `ARef` example
In reply to Andreas HindborgQuoted 9 lines · Andreas Hindborg
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]>
Please see/link https://github.com/Rust-for-Linux/linux/issues/351.
Thanks!
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v20 6/8] rust: Add missing SAFETY documentation for `ARef` example
Quoted 4 lines · Miguel Ojeda
Quoted 3 lines · Andreas Hindborg
From: Oliver Mangold <[email protected]>
Quoted 8 lines
Quoted 6 lines
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]>Please see/link https://github.com/Rust-for-Linux/linux/issues/351.
Do you want a link to this issue with a regular Link: tag?
Best regards,
Andreas Hindborg
Re: [PATCH v20 6/8] rust: Add missing SAFETY documentation for `ARef` example
Quoted 2 lines · Andreas Hindborg
Do you want a link to this issue with a regular
Link:tag?
Yeah, thanks!
Cheers,
Miguel
Andreas Hindborg
maintainerPATCH v20 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 | 145 +++++++++++++++++++++++++++++++++++++++++++++-- rust/kernel/sync/aref.rs | 16 +++++- rust/kernel/types.rs | 1 + 3 files changed, 156 insertions(+), 6 deletions(-)
rust/kernel/owned.rs +140 -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 ///
@@ -99,6 +105,8 @@ pub trait Ownable {/// 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. +/// +/// `this` is pinned and implementers of this method must observe this constraint. unsafe fn release (this:NonNull <Self >); }
@@ -136,6 +144,8 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// This function does not drop the underlying `T`. When this function returns, ownership of the /// underlying `T` is with the caller. +/// +/// Note that the returned pointer is pinned. #[inline] pub fn into_raw (me:Self ) ->NonNull <T > {ManuallyDrop ::new (me).ptr
@@ -236,3 +246,128 @@ 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) +/// } +/// } +/// +/// fn into_shared(this: Owned<Self>) -> ARef<Self> { +/// // SAFETY: An `Owned<Foo>` holds the unique reference (refcount 1), which we transfer to +/// // the new `ARef`. +/// unsafe { ARef::from_raw(Owned::into_raw(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`]. +fn into_shared (this:Owned <Self >) ->ARef <Self >; +} + +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>`]). /// /// # 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 v20 7/8] rust: Add `OwnableRefCounted`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
From: Oliver Mangold <[email protected]>
Types implementing one of these traits can safely convert between an
ARef<T>and anOwned<T>.This is useful for types which generally are accessed through an
ARefbut have methods which can only safely be called when the reference is unique, like e.g.block::mq::Request::end_ok().
Quoted 5 lines
Signed-off-by Oliver Mangold <[email protected]>[ Andreas: Fix formatting, update documentation, fix error handling in
examples. ]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=7
Danilo Krummrich
maintainerRe: [PATCH v20 7/8] rust: Add `OwnableRefCounted`
In reply to Andreas HindborgQuoted 36 lines · Andreas Hindborg
rust/kernel/owned.rs +36
-0+/// 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 {
rust/kernel/owned.rs unsafe fn borrow_mut<'a>(ptr: *mut kernel::ffi::c_void) -> Self::BorrowedMut<'a> · line 318
Quoted 10 lines
rust/kernel/owned.rs +10
-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); +/// } +/// } +/// }
This is valid as Foo is !Sync, but I think it does look racy on casual reading and possibly even encourages people to do the wrong thing, i.e. to peek a reference count and subsequently act on the read value.
Besides that, if the value can't be shared across tasks it's not overly useful in the kernel to reference count it in the first place. Do you have a better example for this? Maybe a broken down version of the one that motivates the patch?
Gary Guo
maintainerRe: [PATCH v20 7/8] rust: Add `OwnableRefCounted`
Quoted 52 lines · Danilo Krummrich
Quoted 36 lines · Andreas Hindborg
rust/kernel/owned.rs +36
-0+/// 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 { rust/kernel/owned.rs unsafe fn borrow_mut<'a>(ptr: *mut kernel::ffi::c_void) -> Self::BorrowedMut<'a> · line 318
Quoted 10 lines
rust/kernel/owned.rs +10
-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); +/// } +/// } +/// } This is valid as Foo is !Sync, but I think it does look racy on casual reading and possibly even encourages people to do the wrong thing, i.e. to peek a reference count and subsequently act on the read value.
Quoted 4 lines
Besides that, if the value can't be shared across tasks it's not overly useful in the kernel to reference count it in the first place. Do you have a better example for this? Maybe a broken down version of the one that motivates the patch?
I think the series is very old and might even predate the sync::Refcount. But given that we have that type now, the example should do the correct thing and use that instead.
Best,
Gary
Andreas Hindborg
maintainerPATCH v20 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
@@ -144,6 +144,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 v20 8/8] rust: page: add `from_raw()`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 6 lines
From: Andreas Hindborg <[email protected]>
Add a method to
Pagethat allows construction of an instance fromstruct pagepointer.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=8