New trait OwnableRefCounted for ARef<->Owned conversion.
Subsystems (17)
v13 cover New trait OwnableRefCounted for ARef<->Owned conversion.
This allows to convert between ARef<T> and Owned<T> by implementing the new trait OwnedRefCounted.
This way we will have a shared/unique reference counting scheme for types with built-in refcounts in analogy to Arc/UniqueArc.
---
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
---
Asahi Lina (1):
rust: types: Add Ownable/Owned types
Oliver Mangold (3):
rust: AlwaysRefCounted is renamed to RefCounted.
rust: Add missing SAFETY documentation for ARef example
rust: Add OwnableRefCounted
rust/kernel/auxiliary.rs | 7 +- rust/kernel/block/mq/request.rs | 15 +- rust/kernel/cred.rs | 13 +- rust/kernel/device.rs | 13 +- rust/kernel/device/property.rs | 7 +- rust/kernel/drm/device.rs | 10 +- rust/kernel/drm/gem/mod.rs | 10 +- rust/kernel/fs/file.rs | 16 +- rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 15 +- rust/kernel/mm/mmput_async.rs | 9 +- rust/kernel/opp.rs | 10 +- rust/kernel/owned.rs | 317 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/pci.rs | 10 +- rust/kernel/pid_namespace.rs | 12 +- rust/kernel/platform.rs | 7 +- rust/kernel/sync/aref.rs | 69 ++++++--- rust/kernel/task.rs | 10 +- rust/kernel/types.rs | 4 +- 19 files changed, 492 insertions(+), 63 deletions(-)
---
base-commit: dcb6fa37fd7bc9c3d2b066329b0d27dedf8becaa
change-id: 20250305-unique-ref-29fcd675f9e9
Best regards,
Signature · 1 line
Oliver Mangold <[email protected]>
PATCH v13 1/4 rust: types: Add Ownable/Owned types
From: 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.
]
--- rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 195 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 2 + 4 files changed, 203 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -112,6 +112,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 +195 -0
195 lines not on this page · raw message
rust/kernel/sync/aref.rs +5 -0
@@ -29,6 +29,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 +2 -0
@@ -11,6 +11,8 @@ };use pin_init::{PinInit ,Wrapper ,Zeroable }; +pub use crate ::owned::{Ownable ,Owned }; +pub use crate ::sync::aref::{ARef ,AlwaysRefCounted };/// Used to transfer ownership to and from foreign (non-Rust) languages.
Signature · 1 line
2.51.2
Re: [PATCH v13 1/4] rust: types: Add Ownable/Owned types
Hi Oliver,
Quoted 94 lines · Oliver Mangold
From: Asahi Lina <[email protected]>
By analogy to
AlwaysRefCountedandARef, anOwnabletype is a (typically C FFI) type that *may* be owned by Rust, but need not be. UnlikeAlwaysRefCounted, 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 theTinstead of using a generic allocator.[ om:
- Split code into separate file andpub useit fromtypes.rs.
- Makefrom_raw()andinto_raw()public.
- Remove OwnableMut, and make DerefMut dependent on Unpin instead.
- Usage example/doctest for Ownable/Owned.
- Fixes to documentation and commit message.
]Signed-off-by Asahi Lina <[email protected]>Co-developed-by Oliver Mangold <[email protected]>Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Boqun Feng <[email protected]>---
rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 195 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 2 + 4 files changed, 203 insertions(+)rust/kernel/lib.rs +1
-0@@ -112,6 +112,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 +42
-0@@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Unique owned pointer types for objects with custom drop logic. +//! +//! These pointer types are useful for C-allocated objects which by API-contract +//! are owned by Rust, but need to be freed through the C API. + +use core::{ + mem::ManuallyDrop , + ops::{Deref ,DerefMut }, + pin::Pin , + ptr::NonNull , +}; + +/// Type allocated and destroyed on the C side, but owned by Rust. +/// +/// 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. +/// +/// 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::types::AlwaysRefCounted) should be implemented. +/// +/// # Safety +/// +/// Implementers must ensure that the [`release()`](Self::release) function frees the underlying +/// object in the correct way for a valid, owned object of this type. +/// +/// # Examples +/// +/// A minimal example implementation of [`Ownable`] and its usage with [`Owned`] looks like this: +/// +/// ``` +/// # #![expect(clippy::disallowed_names)] +/// # use core::cell::Cell; +/// # use core::ptr::NonNull; +/// # use kernel::sync::global_lock; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::types::{Owned, Ownable}; +///
rust/kernel/owned.rs line 52
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+/// // Let's count the allocations to see if freeing works. +/// kernel::sync::global_lock! { +/// // SAFETY: we call `init()` right below, before doing anything else. +/// unsafe(uninit) static FOO_ALLOC_COUNT: Mutex<usize> = 0; +/// } +/// // SAFETY: We call `init()` only once, here. +/// unsafe { FOO_ALLOC_COUNT.init() }; +/// +/// struct Foo { +/// }
nit: this can be simply:
struct Foo;
Quoted 63 lines
rust/kernel/owned.rs new file +63
-0+/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo {}, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // Count new allocation +/// *FOO_ALLOC_COUNT.lock() += 1; +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and we won't +/// // use the raw pointer anymore. Thus we can transfer ownership to the `Owned`. +/// Ok(unsafe { Owned::from_raw(result) }) +/// } +/// } +/// +/// // SAFETY: What out `release()` function does is safe of any valid `Self`. +/// unsafe impl Ownable for Foo { +/// unsafe fn release(this: NonNull<Self>) { +/// // The `Foo` will be dropped when `KBox` goes out of scope. +/// // SAFETY: The [`KBox<Self>`] is still alive. 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()) }; +/// // Count released allocation +/// *FOO_ALLOC_COUNT.lock() -= 1; +/// } +/// } +/// +/// { +/// let foo = Foo::new().expect("Failed to allocate a Foo. This shouldn't happen"); +/// assert!(*FOO_ALLOC_COUNT.lock() == 1); +/// } +/// // `foo` is out of scope now, so we expect no live allocations. +/// assert!(*FOO_ALLOC_COUNT.lock() == 0); +/// ``` +pub unsafe trait Ownable { +/// Releases the object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `this` points to a valid `Self`. +/// - `*this` is no longer used after this call. +unsafe fn release (this:NonNull <Self >); +} + +/// An owned reference to an owned `T`. +/// +/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is +/// dropped. +/// +/// # Invariants +/// +/// - The [`Owned<T>`] has exclusive access to the instance of `T`. +/// - The instance of `T` will stay alive at least as long as the [`Owned<T>`] is alive. +pub struct Owned <T :Ownable > { + ptr:NonNull <T >, +}
rust/kernel/owned.rs line 125
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+ +// SAFETY: It is safe to send an [`Owned<T>`] to another thread when the underlying `T` is [`Send`], +// because of the ownership invariant. Sending an [`Owned<T>`] is equivalent to sending the `T`. +unsafe impl <T :Ownable +Send >Send for Owned <T > {} + +// SAFETY: It is safe to send [`&Owned<T>`] to another thread when the underlying `T` is [`Sync`], +// because of the ownership invariant. Sending an [`&Owned<T>`] is equivalent to sending the `&T`. +unsafe impl <T :Ownable +Sync >Sync for Owned <T > {} + +impl <T :Ownable >Owned <T > {
Can you make sure that impl Owned<T> follows the struct declaration?
IOW: please move the Send and Sync impls to be after the impl above.
rust/kernel/owned.rs line 138
Quoted 13 lines
rust/kernel/owned.rs new file +13
-0+/// Creates a new instance of [`Owned`]. +/// +/// It takes over ownership of the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. +/// - Ownership of the underlying `T` can be transferred to the `Self<T>` (i.e. operations +/// which require ownership will be safe). +/// - No other Rust references to the underlying object exist. This implies that the underlying +/// object is not accessed through `ptr` anymore after the function call (at least until the +/// the `Self<T>` is dropped.
It looks like this can be written more succinctly as:
"This implies that the underlying object is not accessed through ptr anymore until Self<T> is dropped."
Quoted 92 lines
rust/kernel/owned.rs new file +57
-0+/// - The C code follows the usual shared reference requirements. That is, the kernel will never +/// mutate or free the underlying object (excluding interior mutability that follows the usual +/// rules) while Rust owns it. +/// - In case `T` implements [`Unpin`] the previous requirement is extended from shared to +/// mutable reference requirements. That is, the kernel will not mutate or free the underlying +/// object and is okay with it being modified by Rust code. +pub unsafe fn from_raw (ptr:NonNull <T >) ->Self { +Self { + ptr, + } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not actually relinquish ownership of the object. After calling this +/// function, the caller is responsible for ownership previously managed +/// by the [`Owned`]. +pub fn into_raw (me:Self ) ->NonNull <T > { +ManuallyDrop ::new (me).ptr + } + +/// Get a pinned mutable reference to the data owned by this `Owned<T>`. +pub fn get_pin_mut (&mut self) ->Pin <&mut T > { +// SAFETY: The type invariants guarantee that the object is valid, and that we can safely +// return a mutable reference to it. +let unpinned =unsafe { self.ptr.as_mut () }; + +// SAFETY: We never hand out unpinned mutable references to the data in +// `Self`, unless the contained type is `Unpin`. +unsafe {Pin ::new_unchecked (unpinned) } + } +} + +impl <T :Ownable >Deref for Owned <T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: The type invariants guarantee that the object is valid. +unsafe { self.ptr.as_ref () } + } +} + +impl <T :Ownable +Unpin >DerefMut for Owned <T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: The type invariants guarantee that the object is valid, and that we can safely +// return a mutable reference to it. +unsafe { self.ptr.as_mut () } + } +} + +impl <T :Ownable >Drop for Owned <T > { +fn drop (&mut self) { +// SAFETY: The type invariants guarantee that the `Owned` owns the object we're about to +// release. +unsafe {T ::release (self.ptr) }; + } +}rust/kernel/sync/aref.rs +5
-0@@ -29,6 +29,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 +2
-0@@ -11,6 +11,8 @@ };use pin_init::{PinInit ,Wrapper ,Zeroable }; +pub use crate ::owned::{Ownable ,Owned }; +pub use crate ::sync::aref::{ARef ,AlwaysRefCounted };/// Used to transfer ownership to and from foreign (non-Rust) languages. Signature · 2 lines
-- 2.51.2
With the changes above,
Andreas Hindborg
maintainerRe: [PATCH v13 1/4] rust: types: Add Ownable/Owned types
Hi Daniel,
I'll send the next iteration of this series.
Quoted 109 lines · Daniel Almeida
Hi Oliver,
Quoted 94 lines · Oliver Mangold
From: Asahi Lina <[email protected]>
By analogy to
AlwaysRefCountedandARef, anOwnabletype is a (typically C FFI) type that *may* be owned by Rust, but need not be. UnlikeAlwaysRefCounted, 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 theTinstead of using a generic allocator.[ om:
- Split code into separate file andpub useit fromtypes.rs.
- Makefrom_raw()andinto_raw()public.
- Remove OwnableMut, and make DerefMut dependent on Unpin instead.
- Usage example/doctest for Ownable/Owned.
- Fixes to documentation and commit message.
]Signed-off-by Asahi Lina <[email protected]>Co-developed-by Oliver Mangold <[email protected]>Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Boqun Feng <[email protected]>---
rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 195 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 2 + 4 files changed, 203 insertions(+)rust/kernel/lib.rs +1
-0@@ -112,6 +112,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 +42
-0@@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Unique owned pointer types for objects with custom drop logic. +//! +//! These pointer types are useful for C-allocated objects which by API-contract +//! are owned by Rust, but need to be freed through the C API. + +use core::{ + mem::ManuallyDrop , + ops::{Deref ,DerefMut }, + pin::Pin , + ptr::NonNull , +}; + +/// Type allocated and destroyed on the C side, but owned by Rust. +/// +/// 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. +/// +/// 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::types::AlwaysRefCounted) should be implemented. +/// +/// # Safety +/// +/// Implementers must ensure that the [`release()`](Self::release) function frees the underlying +/// object in the correct way for a valid, owned object of this type. +/// +/// # Examples +/// +/// A minimal example implementation of [`Ownable`] and its usage with [`Owned`] looks like this: +/// +/// ``` +/// # #![expect(clippy::disallowed_names)] +/// # use core::cell::Cell; +/// # use core::ptr::NonNull; +/// # use kernel::sync::global_lock; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::types::{Owned, Ownable}; +/// rust/kernel/owned.rs line 52
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+/// // Let's count the allocations to see if freeing works. +/// kernel::sync::global_lock! { +/// // SAFETY: we call `init()` right below, before doing anything else. +/// unsafe(uninit) static FOO_ALLOC_COUNT: Mutex<usize> = 0; +/// } +/// // SAFETY: We call `init()` only once, here. +/// unsafe { FOO_ALLOC_COUNT.init() }; +/// +/// struct Foo { +/// } nit: this can be simply:
Quoted 1 line
struct Foo;
Got it.
Quoted 77 lines
Quoted 64 lines
rust/kernel/owned.rs new file +63
-0+/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo {}, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // Count new allocation +/// *FOO_ALLOC_COUNT.lock() += 1; +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and we won't +/// // use the raw pointer anymore. Thus we can transfer ownership to the `Owned`. +/// Ok(unsafe { Owned::from_raw(result) }) +/// } +/// } +/// +/// // SAFETY: What out `release()` function does is safe of any valid `Self`. +/// unsafe impl Ownable for Foo { +/// unsafe fn release(this: NonNull<Self>) { +/// // The `Foo` will be dropped when `KBox` goes out of scope. +/// // SAFETY: The [`KBox<Self>`] is still alive. 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()) }; +/// // Count released allocation +/// *FOO_ALLOC_COUNT.lock() -= 1; +/// } +/// } +/// +/// { +/// let foo = Foo::new().expect("Failed to allocate a Foo. This shouldn't happen"); +/// assert!(*FOO_ALLOC_COUNT.lock() == 1); +/// } +/// // `foo` is out of scope now, so we expect no live allocations. +/// assert!(*FOO_ALLOC_COUNT.lock() == 0); +/// ``` +pub unsafe trait Ownable { +/// Releases the object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `this` points to a valid `Self`. +/// - `*this` is no longer used after this call. +unsafe fn release (this:NonNull <Self >); +} + +/// An owned reference to an owned `T`. +/// +/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is +/// dropped. +/// +/// # Invariants +/// +/// - The [`Owned<T>`] has exclusive access to the instance of `T`. +/// - The instance of `T` will stay alive at least as long as the [`Owned<T>`] is alive. +pub struct Owned <T :Ownable > { + ptr:NonNull <T >, +}rust/kernel/owned.rs line 125
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+ +// SAFETY: It is safe to send an [`Owned<T>`] to another thread when the underlying `T` is [`Send`], +// because of the ownership invariant. Sending an [`Owned<T>`] is equivalent to sending the `T`. +unsafe impl <T :Ownable +Send >Send for Owned <T > {} + +// SAFETY: It is safe to send [`&Owned<T>`] to another thread when the underlying `T` is [`Sync`], +// because of the ownership invariant. Sending an [`&Owned<T>`] is equivalent to sending the `&T`. +unsafe impl <T :Ownable +Sync >Sync for Owned <T > {} + +impl <T :Ownable >Owned <T > {Can you make sure that impl Owned<T> follows the struct declaration?
Quoted 1 line
IOW: please move the Send and Sync impls to be after the impl above.
I don't really see the point, but moving them is no problem, so let's do that.
Quoted 15 lines
Quoted 4 lines
rust/kernel/owned.rs new file +3
-0+/// Creates a new instance of [`Owned`]. +/// +/// It takes over ownership of the underlying object. rust/kernel/owned.rs line 138
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. +/// - Ownership of the underlying `T` can be transferred to the `Self<T>` (i.e. operations +/// which require ownership will be safe). +/// - No other Rust references to the underlying object exist. This implies that the underlying +/// object is not accessed through `ptr` anymore after the function call (at least until the +/// the `Self<T>` is dropped.
Quoted 3 lines
It looks like this can be written more succinctly as:
"This implies that the underlying object is not accessed through
ptranymore untilSelf<T>is dropped."
I'll rephrase with that text.
Quoted 96 lines
Quoted 93 lines
rust/kernel/owned.rs new file +57
-0+/// - The C code follows the usual shared reference requirements. That is, the kernel will never +/// mutate or free the underlying object (excluding interior mutability that follows the usual +/// rules) while Rust owns it. +/// - In case `T` implements [`Unpin`] the previous requirement is extended from shared to +/// mutable reference requirements. That is, the kernel will not mutate or free the underlying +/// object and is okay with it being modified by Rust code. +pub unsafe fn from_raw (ptr:NonNull <T >) ->Self { +Self { + ptr, + } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not actually relinquish ownership of the object. After calling this +/// function, the caller is responsible for ownership previously managed +/// by the [`Owned`]. +pub fn into_raw (me:Self ) ->NonNull <T > { +ManuallyDrop ::new (me).ptr + } + +/// Get a pinned mutable reference to the data owned by this `Owned<T>`. +pub fn get_pin_mut (&mut self) ->Pin <&mut T > { +// SAFETY: The type invariants guarantee that the object is valid, and that we can safely +// return a mutable reference to it. +let unpinned =unsafe { self.ptr.as_mut () }; + +// SAFETY: We never hand out unpinned mutable references to the data in +// `Self`, unless the contained type is `Unpin`. +unsafe {Pin ::new_unchecked (unpinned) } + } +} + +impl <T :Ownable >Deref for Owned <T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: The type invariants guarantee that the object is valid. +unsafe { self.ptr.as_ref () } + } +} + +impl <T :Ownable +Unpin >DerefMut for Owned <T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: The type invariants guarantee that the object is valid, and that we can safely +// return a mutable reference to it. +unsafe { self.ptr.as_mut () } + } +} + +impl <T :Ownable >Drop for Owned <T > { +fn drop (&mut self) { +// SAFETY: The type invariants guarantee that the `Owned` owns the object we're about to +// release. +unsafe {T ::release (self.ptr) }; + } +}rust/kernel/sync/aref.rs +5
-0@@ -29,6 +29,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 +2
-0@@ -11,6 +11,8 @@ };use pin_init::{PinInit ,Wrapper ,Zeroable }; +pub use crate ::owned::{Ownable ,Owned }; +pub use crate ::sync::aref::{ARef ,AlwaysRefCounted };/// Used to transfer ownership to and from foreign (non-Rust) languages. Signature · 2 lines
-- 2.51.2With the changes above,
Quoted 1 line
Reviewed-by Daniel Almeida <[email protected]>
Thanks!
Gary Guo
maintainerRe: [PATCH v13 1/4] rust: types: Add Ownable/Owned types
In reply to Oliver MangoldQuoted 55 lines · On Mon, 17 Nov 2025 10:07:40 +0000 Oliver Mangold <[email protected]> wrote:
From: Asahi Lina <[email protected]>
By analogy to
AlwaysRefCountedandARef, anOwnabletype is a (typically C FFI) type that *may* be owned by Rust, but need not be. UnlikeAlwaysRefCounted, 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 theTinstead of using a generic allocator.[ om:
- Split code into separate file andpub useit fromtypes.rs.
- Makefrom_raw()andinto_raw()public.
- Remove OwnableMut, and make DerefMut dependent on Unpin instead.
- Usage example/doctest for Ownable/Owned.
- Fixes to documentation and commit message.
]Signed-off-by Asahi Lina <[email protected]>Co-developed-by Oliver Mangold <[email protected]>Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Boqun Feng <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 195 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 2 + 4 files changed, 203 insertions(+)rust/kernel/lib.rs +1
-0@@ -112,6 +112,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 +5
-0@@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Unique owned pointer types for objects with custom drop logic. +//! +//! These pointer types are useful for C-allocated objects which by API-contract
rust/kernel/owned.rs line 15
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+//! are owned by Rust, but need to be freed through the C API. + +use core::{ + mem::ManuallyDrop , + ops::{Deref ,DerefMut }, + pin::Pin , + ptr::NonNull , +}; + +/// Type allocated and destroyed on the C side, but owned by Rust.
The example given in the documentation below shows a valid way of defining a type that's handled on the Rust side, so I think this message is somewhat inaccurate.
Perhaps something like
Types that specify their own way of performing allocation and destruction. Typically, this trait is implemented on types from the C side.
?
Quoted 48 lines
rust/kernel/owned.rs new file +48
-0+/// +/// 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. +/// +/// 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::types::AlwaysRefCounted) should be implemented. +/// +/// # Safety +/// +/// Implementers must ensure that the [`release()`](Self::release) function frees the underlying +/// object in the correct way for a valid, owned object of this type. +/// +/// # Examples +/// +/// A minimal example implementation of [`Ownable`] and its usage with [`Owned`] looks like this: +/// +/// ``` +/// # #![expect(clippy::disallowed_names)] +/// # use core::cell::Cell; +/// # use core::ptr::NonNull; +/// # use kernel::sync::global_lock; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::types::{Owned, Ownable}; +/// +/// // Let's count the allocations to see if freeing works. +/// kernel::sync::global_lock! { +/// // SAFETY: we call `init()` right below, before doing anything else. +/// unsafe(uninit) static FOO_ALLOC_COUNT: Mutex<usize> = 0; +/// } +/// // SAFETY: We call `init()` only once, here. +/// unsafe { FOO_ALLOC_COUNT.init() }; +/// +/// struct Foo { +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo {}, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen.");
rust/kernel/owned.rs line 73
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+/// // Count new allocation +/// *FOO_ALLOC_COUNT.lock() += 1; +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and we won't +/// // use the raw pointer anymore. Thus we can transfer ownership to the `Owned`. +/// Ok(unsafe { Owned::from_raw(result) }) +/// } +/// } +/// +/// // SAFETY: What out `release()` function does is safe of any valid `Self`.
I can't parse this sentence. Is "out" supposed to be a different word?
rust/kernel/owned.rs line 76
Quoted 3 lines
rust/kernel/owned.rs new file +3
-0+/// unsafe impl Ownable for Foo { +/// unsafe fn release(this: NonNull<Self>) { +/// // The `Foo` will be dropped when `KBox` goes out of scope.
I would just write drop(unsafe { ... }) to make drop explicit instead of commenting about the implicit drop.
Quoted 52 lines
rust/kernel/owned.rs new file +52
-0+/// // SAFETY: The [`KBox<Self>`] is still alive. 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()) }; +/// // Count released allocation +/// *FOO_ALLOC_COUNT.lock() -= 1; +/// } +/// } +/// +/// { +/// let foo = Foo::new().expect("Failed to allocate a Foo. This shouldn't happen"); +/// assert!(*FOO_ALLOC_COUNT.lock() == 1); +/// } +/// // `foo` is out of scope now, so we expect no live allocations. +/// assert!(*FOO_ALLOC_COUNT.lock() == 0); +/// ``` +pub unsafe trait Ownable { +/// Releases the object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `this` points to a valid `Self`. +/// - `*this` is no longer used after this call. +unsafe fn release (this:NonNull <Self >); +} + +/// An owned reference to an owned `T`. +/// +/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is +/// dropped. +/// +/// # Invariants +/// +/// - The [`Owned<T>`] has exclusive access to the instance of `T`. +/// - The instance of `T` will stay alive at least as long as the [`Owned<T>`] is alive. +pub struct Owned <T :Ownable > { + ptr:NonNull <T >, +} + +// SAFETY: It is safe to send an [`Owned<T>`] to another thread when the underlying `T` is [`Send`], +// because of the ownership invariant. Sending an [`Owned<T>`] is equivalent to sending the `T`. +unsafe impl <T :Ownable +Send >Send for Owned <T > {} + +// SAFETY: It is safe to send [`&Owned<T>`] to another thread when the underlying `T` is [`Sync`], +// because of the ownership invariant. Sending an [`&Owned<T>`] is equivalent to sending the `&T`. +unsafe impl <T :Ownable +Sync >Sync for Owned <T > {} + +impl <T :Ownable >Owned <T > { +/// Creates a new instance of [`Owned`]. +/// +/// It takes over ownership of the underlying object.
rust/kernel/owned.rs line 138
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. +/// - Ownership of the underlying `T` can be transferred to the `Self<T>` (i.e. operations +/// which require ownership will be safe). +/// - No other Rust references to the underlying object exist. This implies that the underlying +/// object is not accessed through `ptr` anymore after the function call (at least until the +/// the `Self<T>` is dropped.
Is this correct? If Self<T> is dropped then T::release is called so the pointer should also not be accessed further?
rust/kernel/owned.rs line 141
Quoted 3 lines
rust/kernel/owned.rs new file +3
-0+/// - The C code follows the usual shared reference requirements. That is, the kernel will never +/// mutate or free the underlying object (excluding interior mutability that follows the usual +/// rules) while Rust owns it.
The concept "interior mutability" doesn't really exist on the C side. Also, use of interior mutability (by UnsafeCell) would be incorrect if the type is implemented in the rust side (as this requires a UnsafePinned).
Interior mutability means things can be mutated behind a shared reference -- however in this case, we have a mutable reference (either Pin<&mut Self> or &mut Self)!
Perhaps together with the next line, they could be just phrased like this?
- The underlying object must not be accessed (read or mutated) through any pointer other than the created Owned<T>.
Opt-out is still possbile similar to a mutable reference (e.g. by using pOpaque]).
I think we should just tell the user "this is just a unique reference similar to &mut". They should be able to deduce that all the !Unpin that opts out from uniqueness of mutable reference applies here too.
rust/kernel/owned.rs line 144
Quoted 3 lines
rust/kernel/owned.rs new file +3
-0+/// - In case `T` implements [`Unpin`] the previous requirement is extended from shared to +/// mutable reference requirements. That is, the kernel will not mutate or free the underlying +/// object and is okay with it being modified by Rust code.
- If T implements [Unpin], the structure must not be mutated for the entire lifetime of Owned<T>.
rust/kernel/owned.rs line 145
Quoted 1 line
rust/kernel/owned.rs new file +1
-0+pub unsafe fn from_raw (ptr:NonNull <T >) ->Self {
This needs a (rather trivial) INVARIANT comment.
rust/kernel/owned.rs line 153
Quoted 8 lines
rust/kernel/owned.rs new file +8
-0+Self { + ptr, + } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not actually relinquish ownership of the object. After calling this
Perhaps "relinquish" isn't the best word here? In my mental model this function is pretty much relinquishing ownership as Owned<T> no longer exists. It just doesn't release the object.
Quoted 7 lines
rust/kernel/owned.rs new file +7
-0+/// function, the caller is responsible for ownership previously managed +/// by the [`Owned`]. +pub fn into_raw (me:Self ) ->NonNull <T > { +ManuallyDrop ::new (me).ptr + } + +/// Get a pinned mutable reference to the data owned by this `Owned<T>`.
rust/kernel/owned.rs line 170
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+pub fn get_pin_mut (&mut self) ->Pin <&mut T > { +// SAFETY: The type invariants guarantee that the object is valid, and that we can safely +// return a mutable reference to it. +let unpinned =unsafe { self.ptr.as_mut () }; + +// SAFETY: We never hand out unpinned mutable references to the data in +// `Self`, unless the contained type is `Unpin`. +unsafe {Pin ::new_unchecked (unpinned) } + } +}
Best,
Gary
Andreas Hindborg
maintainerRe: [PATCH v13 1/4] rust: types: Add Ownable/Owned types
Quoted 73 lines · Gary Guo
Quoted 55 lines · On Mon, 17 Nov 2025 10:07:40 +0000 Oliver Mangold <[email protected]> wrote:
From: Asahi Lina <[email protected]>
By analogy to
AlwaysRefCountedandARef, anOwnabletype is a (typically C FFI) type that *may* be owned by Rust, but need not be. UnlikeAlwaysRefCounted, 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 theTinstead of using a generic allocator.[ om:
- Split code into separate file andpub useit fromtypes.rs.
- Makefrom_raw()andinto_raw()public.
- Remove OwnableMut, and make DerefMut dependent on Unpin instead.
- Usage example/doctest for Ownable/Owned.
- Fixes to documentation and commit message.
]Signed-off-by Asahi Lina <[email protected]>Co-developed-by Oliver Mangold <[email protected]>Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Boqun Feng <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 195 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 2 + 4 files changed, 203 insertions(+)rust/kernel/lib.rs +1
-0@@ -112,6 +112,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 +5
-0@@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Unique owned pointer types for objects with custom drop logic. +//! +//! These pointer types are useful for C-allocated objects which by API-contract rust/kernel/owned.rs line 15
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+//! are owned by Rust, but need to be freed through the C API. + +use core::{ + mem::ManuallyDrop , + ops::{Deref ,DerefMut }, + pin::Pin , + ptr::NonNull , +}; + +/// Type allocated and destroyed on the C side, but owned by Rust. The example given in the documentation below shows a valid way of defining a type that's handled on the Rust side, so I think this message is somewhat inaccurate.
Quoted 5 lines
Perhaps something like
Types that specify their own way of performing allocation and destruction. Typically, this trait is implemented on types from the C side.
Thanks, I'll use this.
Quoted 55 lines
?
Quoted 52 lines
rust/kernel/owned.rs new file +52
-0+/// +/// 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. +/// +/// 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::types::AlwaysRefCounted) should be implemented. +/// +/// # Safety +/// +/// Implementers must ensure that the [`release()`](Self::release) function frees the underlying +/// object in the correct way for a valid, owned object of this type. +/// +/// # Examples +/// +/// A minimal example implementation of [`Ownable`] and its usage with [`Owned`] looks like this: +/// +/// ``` +/// # #![expect(clippy::disallowed_names)] +/// # use core::cell::Cell; +/// # use core::ptr::NonNull; +/// # use kernel::sync::global_lock; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::types::{Owned, Ownable}; +/// +/// // Let's count the allocations to see if freeing works. +/// kernel::sync::global_lock! { +/// // SAFETY: we call `init()` right below, before doing anything else. +/// unsafe(uninit) static FOO_ALLOC_COUNT: Mutex<usize> = 0; +/// } +/// // SAFETY: We call `init()` only once, here. +/// unsafe { FOO_ALLOC_COUNT.init() }; +/// +/// struct Foo { +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo {}, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // Count new allocation +/// *FOO_ALLOC_COUNT.lock() += 1; +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and we won't
Quoted 8 lines
rust/kernel/owned.rs line 73
Quoted 6 lines
rust/kernel/owned.rs new file +6
-0+/// // use the raw pointer anymore. Thus we can transfer ownership to the `Owned`. +/// Ok(unsafe { Owned::from_raw(result) }) +/// } +/// } +/// +/// // SAFETY: What out `release()` function does is safe of any valid `Self`. I can't parse this sentence. Is "out" supposed to be a different word?
I think it should be "our".
Quoted 7 lines
rust/kernel/owned.rs line 76
Quoted 4 lines
rust/kernel/owned.rs new file +3
-0+/// unsafe impl Ownable for Foo { +/// unsafe fn release(this: NonNull<Self>) { +/// // The `Foo` will be dropped when `KBox` goes out of scope. I would just write
drop(unsafe { ... })to make drop explicit instead of commenting about the implicit drop.
Agree, that is easier to read.
Quoted 58 lines
Quoted 58 lines
rust/kernel/owned.rs new file +57
-0+/// // SAFETY: The [`KBox<Self>`] is still alive. 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()) }; +/// // Count released allocation +/// *FOO_ALLOC_COUNT.lock() -= 1; +/// } +/// } +/// +/// { +/// let foo = Foo::new().expect("Failed to allocate a Foo. This shouldn't happen"); +/// assert!(*FOO_ALLOC_COUNT.lock() == 1); +/// } +/// // `foo` is out of scope now, so we expect no live allocations. +/// assert!(*FOO_ALLOC_COUNT.lock() == 0); +/// ``` +pub unsafe trait Ownable { +/// Releases the object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `this` points to a valid `Self`. +/// - `*this` is no longer used after this call. +unsafe fn release (this:NonNull <Self >); +} + +/// An owned reference to an owned `T`. +/// +/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is +/// dropped. +/// +/// # Invariants +/// +/// - The [`Owned<T>`] has exclusive access to the instance of `T`. +/// - The instance of `T` will stay alive at least as long as the [`Owned<T>`] is alive. +pub struct Owned <T :Ownable > { + ptr:NonNull <T >, +} + +// SAFETY: It is safe to send an [`Owned<T>`] to another thread when the underlying `T` is [`Send`], +// because of the ownership invariant. Sending an [`Owned<T>`] is equivalent to sending the `T`. +unsafe impl <T :Ownable +Send >Send for Owned <T > {} + +// SAFETY: It is safe to send [`&Owned<T>`] to another thread when the underlying `T` is [`Sync`], +// because of the ownership invariant. Sending an [`&Owned<T>`] is equivalent to sending the `&T`. +unsafe impl <T :Ownable +Sync >Sync for Owned <T > {} + +impl <T :Ownable >Owned <T > { +/// Creates a new instance of [`Owned`]. +/// +/// It takes over ownership of the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`.
Quoted 8 lines
rust/kernel/owned.rs line 138
Quoted 5 lines
rust/kernel/owned.rs new file +5
-0+/// - Ownership of the underlying `T` can be transferred to the `Self<T>` (i.e. operations +/// which require ownership will be safe). +/// - No other Rust references to the underlying object exist. This implies that the underlying +/// object is not accessed through `ptr` anymore after the function call (at least until the +/// the `Self<T>` is dropped. Is this correct? If
Self<T>is dropped thenT::releaseis called so the pointer should also not be accessed further?
I can't follow you point here. Are you saying that the requirement is wrong because T::release will access the object by reference? If so, that is part of Owned<_>::drop, which is explicitly mentioned in the comment (until .. dropped).
Quoted 17 lines
rust/kernel/owned.rs line 141
Quoted 4 lines
rust/kernel/owned.rs new file +3
-0+/// - The C code follows the usual shared reference requirements. That is, the kernel will never +/// mutate or free the underlying object (excluding interior mutability that follows the usual +/// rules) while Rust owns it. The concept "interior mutability" doesn't really exist on the C side. Also, use of interior mutability (by UnsafeCell) would be incorrect if the type is implemented in the rust side (as this requires a UnsafePinned).
Interior mutability means things can be mutated behind a shared reference -- however in this case, we have a mutable reference (either
Pin<&mut Self>or&mut Self)!Perhaps together with the next line, they could be just phrased like this?
Quoted 8 lines
- The underlying object must not be accessed (read or mutated) through any pointer other than the created
Owned<T>.
Opt-out is still possbile similar to a mutable reference (e.g. by using pOpaque]).I think we should just tell the user "this is just a unique reference similar to &mut". They should be able to deduce that all the
!Unpinthat opts out from uniqueness of mutable reference applies here too.
I agree. I would suggest updating the struct documentation:
@@ -108,7 +108,7 @@ pub unsafe trait Ownable {
unsafe fn release(this: NonNull<Self>);
}
-/// An owned reference to an owned `T`.
+/// An mutable reference to an owned `T`.
///
/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is
/// dropped.And then the safety requirement as
An Owned<T> is a mutable reference to the underlying object. As such, the object must not be accessed (read or mutated) through any pointer other than the created Owned<T>. Opt-out is still possbile similar to a mutable reference (e.g. by using [Opaque]).
Quoted 6 lines
rust/kernel/owned.rs line 144
Quoted 3 lines
rust/kernel/owned.rs new file +3
-0+/// - In case `T` implements [`Unpin`] the previous requirement is extended from shared to +/// mutable reference requirements. That is, the kernel will not mutate or free the underlying +/// object and is okay with it being modified by Rust code. - If
Timplements [Unpin], the structure must not be mutated for the entire lifetime ofOwned<T>.
Would it be OK to just write "If T: Unpin, the ..."?
Again, opt out is possible, right?
Quoted 4 lines
rust/kernel/owned.rs line 145
Quoted 2 lines
rust/kernel/owned.rs new file +1
-0+pub unsafe fn from_raw (ptr:NonNull <T >) ->Self {This needs a (rather trivial) INVARIANT comment.
OK.
Quoted 10 lines
rust/kernel/owned.rs line 153
Quoted 9 lines
rust/kernel/owned.rs new file +8
-0+Self { + ptr, + } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not actually relinquish ownership of the object. After calling this
Quoted 3 lines
Perhaps "relinquish" isn't the best word here? In my mental model this function is pretty much relinquishing ownership as
Owned<T>no longer exists. It just doesn't release the object.
How about this:
/// Consumes the [`Owned`], returning a raw pointer.
///
/// This function does not drop the underlying `T`. When this function returns, ownership of the
/// underlying `T` is with the caller.Thanks for the comments!
Best regards,
Andreas Hindborg
Gary Guo
maintainerRe: [PATCH v13 1/4] rust: types: Add Ownable/Owned types
Quoted 226 lines · Andreas Hindborg
Quoted 73 lines · Gary Guo
Quoted 55 lines · On Mon, 17 Nov 2025 10:07:40 +0000 Oliver Mangold <[email protected]> wrote:
From: Asahi Lina <[email protected]>
By analogy to
AlwaysRefCountedandARef, anOwnabletype is a (typically C FFI) type that *may* be owned by Rust, but need not be. UnlikeAlwaysRefCounted, 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 theTinstead of using a generic allocator.[ om:
- Split code into separate file andpub useit fromtypes.rs.
- Makefrom_raw()andinto_raw()public.
- Remove OwnableMut, and make DerefMut dependent on Unpin instead.
- Usage example/doctest for Ownable/Owned.
- Fixes to documentation and commit message.
]Signed-off-by Asahi Lina <[email protected]>Co-developed-by Oliver Mangold <[email protected]>Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Boqun Feng <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/owned.rs | 195 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/aref.rs | 5 ++ rust/kernel/types.rs | 2 + 4 files changed, 203 insertions(+)rust/kernel/lib.rs +1
-0@@ -112,6 +112,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 +5
-0@@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Unique owned pointer types for objects with custom drop logic. +//! +//! These pointer types are useful for C-allocated objects which by API-contract rust/kernel/owned.rs line 15
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+//! are owned by Rust, but need to be freed through the C API. + +use core::{ + mem::ManuallyDrop , + ops::{Deref ,DerefMut }, + pin::Pin , + ptr::NonNull , +}; + +/// Type allocated and destroyed on the C side, but owned by Rust. The example given in the documentation below shows a valid way of defining a type that's handled on the Rust side, so I think this message is somewhat inaccurate.
Quoted 5 lines
Perhaps something like
Types that specify their own way of performing allocation and destruction. Typically, this trait is implemented on types from the C side.
Thanks, I'll use this.
Quoted 55 lines
?
Quoted 52 lines
rust/kernel/owned.rs new file +52
-0+/// +/// 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. +/// +/// 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::types::AlwaysRefCounted) should be implemented. +/// +/// # Safety +/// +/// Implementers must ensure that the [`release()`](Self::release) function frees the underlying +/// object in the correct way for a valid, owned object of this type. +/// +/// # Examples +/// +/// A minimal example implementation of [`Ownable`] and its usage with [`Owned`] looks like this: +/// +/// ``` +/// # #![expect(clippy::disallowed_names)] +/// # use core::cell::Cell; +/// # use core::ptr::NonNull; +/// # use kernel::sync::global_lock; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::types::{Owned, Ownable}; +/// +/// // Let's count the allocations to see if freeing works. +/// kernel::sync::global_lock! { +/// // SAFETY: we call `init()` right below, before doing anything else. +/// unsafe(uninit) static FOO_ALLOC_COUNT: Mutex<usize> = 0; +/// } +/// // SAFETY: We call `init()` only once, here. +/// unsafe { FOO_ALLOC_COUNT.init() }; +/// +/// struct Foo { +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo {}, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // Count new allocation +/// *FOO_ALLOC_COUNT.lock() += 1; +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and we won't Quoted 8 lines
rust/kernel/owned.rs line 73
Quoted 6 lines
rust/kernel/owned.rs new file +6
-0+/// // use the raw pointer anymore. Thus we can transfer ownership to the `Owned`. +/// Ok(unsafe { Owned::from_raw(result) }) +/// } +/// } +/// +/// // SAFETY: What out `release()` function does is safe of any valid `Self`. I can't parse this sentence. Is "out" supposed to be a different word?
I think it should be "our".
Quoted 7 lines
rust/kernel/owned.rs line 76
Quoted 4 lines
rust/kernel/owned.rs new file +3
-0+/// unsafe impl Ownable for Foo { +/// unsafe fn release(this: NonNull<Self>) { +/// // The `Foo` will be dropped when `KBox` goes out of scope. I would just write
drop(unsafe { ... })to make drop explicit instead of commenting about the implicit drop.Agree, that is easier to read.
Quoted 58 lines
Quoted 58 lines
rust/kernel/owned.rs new file +57
-0+/// // SAFETY: The [`KBox<Self>`] is still alive. 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()) }; +/// // Count released allocation +/// *FOO_ALLOC_COUNT.lock() -= 1; +/// } +/// } +/// +/// { +/// let foo = Foo::new().expect("Failed to allocate a Foo. This shouldn't happen"); +/// assert!(*FOO_ALLOC_COUNT.lock() == 1); +/// } +/// // `foo` is out of scope now, so we expect no live allocations. +/// assert!(*FOO_ALLOC_COUNT.lock() == 0); +/// ``` +pub unsafe trait Ownable { +/// Releases the object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `this` points to a valid `Self`. +/// - `*this` is no longer used after this call. +unsafe fn release (this:NonNull <Self >); +} + +/// An owned reference to an owned `T`. +/// +/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is +/// dropped. +/// +/// # Invariants +/// +/// - The [`Owned<T>`] has exclusive access to the instance of `T`. +/// - The instance of `T` will stay alive at least as long as the [`Owned<T>`] is alive. +pub struct Owned <T :Ownable > { + ptr:NonNull <T >, +} + +// SAFETY: It is safe to send an [`Owned<T>`] to another thread when the underlying `T` is [`Send`], +// because of the ownership invariant. Sending an [`Owned<T>`] is equivalent to sending the `T`. +unsafe impl <T :Ownable +Send >Send for Owned <T > {} + +// SAFETY: It is safe to send [`&Owned<T>`] to another thread when the underlying `T` is [`Sync`], +// because of the ownership invariant. Sending an [`&Owned<T>`] is equivalent to sending the `&T`. +unsafe impl <T :Ownable +Sync >Sync for Owned <T > {} + +impl <T :Ownable >Owned <T > { +/// Creates a new instance of [`Owned`]. +/// +/// It takes over ownership of the underlying object. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. Quoted 8 lines
rust/kernel/owned.rs line 138
Quoted 5 lines
rust/kernel/owned.rs new file +5
-0+/// - Ownership of the underlying `T` can be transferred to the `Self<T>` (i.e. operations +/// which require ownership will be safe). +/// - No other Rust references to the underlying object exist. This implies that the underlying +/// object is not accessed through `ptr` anymore after the function call (at least until the +/// the `Self<T>` is dropped. Is this correct? If
Self<T>is dropped thenT::releaseis called so the pointer should also not be accessed further?
Quoted 4 lines
I can't follow you point here. Are you saying that the requirement is wrong because
T::releasewill access the object by reference? If so, that is part ofOwned<_>::drop, which is explicitly mentioned in the comment (until .. dropped).
I meant that the Self<T> is dropped, the object is destroyed so it should also not be accessed further. Perhaps just remove the "(at least ...)" part from comment.
Quoted 39 lines
Quoted 18 lines
rust/kernel/owned.rs line 141
Quoted 5 lines
rust/kernel/owned.rs new file +3
-0+/// - The C code follows the usual shared reference requirements. That is, the kernel will never +/// mutate or free the underlying object (excluding interior mutability that follows the usual +/// rules) while Rust owns it. The concept "interior mutability" doesn't really exist on the C side. Also, use of interior mutability (by UnsafeCell) would be incorrect if the type is implemented in the rust side (as this requires a UnsafePinned).
Interior mutability means things can be mutated behind a shared reference -- however in this case, we have a mutable reference (either
Pin<&mut Self>or&mut Self)!Perhaps together with the next line, they could be just phrased like this?
Quoted 8 lines
- The underlying object must not be accessed (read or mutated) through any pointer other than the created
Owned<T>.
Opt-out is still possbile similar to a mutable reference (e.g. by using pOpaque]).I think we should just tell the user "this is just a unique reference similar to &mut". They should be able to deduce that all the
!Unpinthat opts out from uniqueness of mutable reference applies here too.I agree. I would suggest updating the struct documentation:
@@ -108,7 +108,7 @@ pub unsafe trait Ownable { unsafe fn release(this: NonNull<Self>); } -/// An owned reference to an owned `T`. +/// An mutable reference to an owned `T`. /// /// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is /// dropped.
Quoted 6 lines
And then the safety requirement as
An
Owned<T>is a mutable reference to the underlying object. As such, the object must not be accessed (read or mutated) through any pointer other than the createdOwned<T>. Opt-out is still possbile similar to a mutable reference (e.g. by using [Opaque]).
Sounds good to me.
Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
rust/kernel/owned.rs new file +3
-0+/// - In case `T` implements [`Unpin`] the previous requirement is extended from shared to +/// mutable reference requirements. That is, the kernel will not mutate or free the underlying +/// object and is okay with it being modified by Rust code.
Quoted 7 lines
Quoted 2 lines
- If
Timplements [Unpin], the structure must not be mutated for the entire lifetime ofOwned<T>.Would it be OK to just write "If
T: Unpin, the ..."?Again, opt out is possible, right?
When the "mutable reference" framing above I think you can just drop this part.
Quoted 21 lines
Quoted 4 lines
rust/kernel/owned.rs line 145
Quoted 2 lines
rust/kernel/owned.rs new file +1
-0+pub unsafe fn from_raw (ptr:NonNull <T >) ->Self {This needs a (rather trivial) INVARIANT comment.
OK.
Quoted 10 lines
rust/kernel/owned.rs line 153
Quoted 9 lines
rust/kernel/owned.rs new file +8
-0+Self { + ptr, + } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not actually relinquish ownership of the object. After calling this Quoted 3 lines
Perhaps "relinquish" isn't the best word here? In my mental model this function is pretty much relinquishing ownership as
Owned<T>no longer exists. It just doesn't release the object.
Quoted 7 lines
How about this:
/// Consumes the [`Owned`], returning a raw pointer. /// /// This function does not drop the underlying `T`. When this function returns, ownership of the /// underlying `T` is with the caller.
SGTM.
Quoted 3 lines
Thanks for the comments!
Best,
Gary
Quoted 4 lines
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerRe: [PATCH v13 1/4] rust: types: Add Ownable/Owned types
Quoted 7 lines · Gary Guo
Quoted 6 lines · Andreas Hindborg
Quoted 4 lines · Gary Guo
Quoted 1 line · On Mon, 17 Nov 2025 10:07:40 +0000 Oliver Mangold <[email protected]> wrote:
From: Asahi Lina <[email protected]>
<cut>
Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
Quoted 4 lines
rust/kernel/owned.rs new file +4
-0+impl <T :Ownable >Owned <T > { +/// Creates a new instance of [`Owned`]. +/// +/// It takes over ownership of the underlying object. rust/kernel/owned.rs line 138
Quoted 10 lines
rust/kernel/owned.rs new file +10
-0+/// +/// # Safety +/// +/// Callers must ensure that: +/// - `ptr` points to a valid instance of `T`. +/// - Ownership of the underlying `T` can be transferred to the `Self<T>` (i.e. operations +/// which require ownership will be safe). +/// - No other Rust references to the underlying object exist. This implies that the underlying +/// object is not accessed through `ptr` anymore after the function call (at least until the +/// the `Self<T>` is dropped. Is this correct? If
Self<T>is dropped thenT::releaseis called so the pointer should also not be accessed further?
Quoted 8 lines
Quoted 4 lines
I can't follow you point here. Are you saying that the requirement is wrong because
T::releasewill access the object by reference? If so, that is part ofOwned<_>::drop, which is explicitly mentioned in the comment (until .. dropped).I meant that the
Self<T>is dropped, the object is destroyed so it should also not be accessed further. Perhaps just remove the "(at least ...)" part from comment.
Right, got it. The "until.." is in place to allow reuse of the allocation. There is no requirement here to drop T via the release method when an Owned<T> is dropped. Implementers are free to implement schemes that reuse the object without drop and re-init. This can be used in object caches such as for the block request cache.
Quoted 40 lines
Quoted 40 lines
Quoted 19 lines
rust/kernel/owned.rs line 141
Quoted 6 lines
rust/kernel/owned.rs new file +3
-0+/// - The C code follows the usual shared reference requirements. That is, the kernel will never +/// mutate or free the underlying object (excluding interior mutability that follows the usual +/// rules) while Rust owns it. The concept "interior mutability" doesn't really exist on the C side. Also, use of interior mutability (by UnsafeCell) would be incorrect if the type is implemented in the rust side (as this requires a UnsafePinned).
Interior mutability means things can be mutated behind a shared reference -- however in this case, we have a mutable reference (either
Pin<&mut Self>or&mut Self)!Perhaps together with the next line, they could be just phrased like this?
Quoted 8 lines
- The underlying object must not be accessed (read or mutated) through any pointer other than the created
Owned<T>.
Opt-out is still possbile similar to a mutable reference (e.g. by using pOpaque]).I think we should just tell the user "this is just a unique reference similar to &mut". They should be able to deduce that all the
!Unpinthat opts out from uniqueness of mutable reference applies here too.I agree. I would suggest updating the struct documentation:
@@ -108,7 +108,7 @@ pub unsafe trait Ownable { unsafe fn release(this: NonNull<Self>); } -/// An owned reference to an owned `T`. +/// An mutable reference to an owned `T`. /// /// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is /// dropped.
Quoted 8 lines
Quoted 6 lines
And then the safety requirement as
An
Owned<T>is a mutable reference to the underlying object. As such, the object must not be accessed (read or mutated) through any pointer other than the createdOwned<T>. Opt-out is still possbile similar to a mutable reference (e.g. by using [Opaque]).Sounds good to me.
OK.
Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
rust/kernel/owned.rs line 144
Quoted 6 lines
rust/kernel/owned.rs new file +3
-0+/// - In case `T` implements [`Unpin`] the previous requirement is extended from shared to +/// mutable reference requirements. That is, the kernel will not mutate or free the underlying +/// object and is okay with it being modified by Rust code. - If
Timplements [Unpin], the structure must not be mutated for the entire lifetime ofOwned<T>.
Quoted 6 lines
Quoted 4 lines
Would it be OK to just write "If
T: Unpin, the ..."?Again, opt out is possible, right?
When the "mutable reference" framing above I think you can just drop this part.
Agreed.
Quoted 25 lines
Quoted 25 lines
Quoted 5 lines
Quoted 3 lines
+ pub unsafe fn
from_raw(ptr: NonNull<T>)-> Self {This needs a (rather trivial) INVARIANT comment.
OK.
Quoted 10 lines
rust/kernel/owned.rs line 153
Quoted 9 lines
rust/kernel/owned.rs new file +8
-0+Self { + ptr, + } + } + +/// Consumes the [`Owned`], returning a raw pointer. +/// +/// This function does not actually relinquish ownership of the object. After calling this Quoted 3 lines
Perhaps "relinquish" isn't the best word here? In my mental model this function is pretty much relinquishing ownership as
Owned<T>no longer exists. It just doesn't release the object.How about this:
Quoted 6 lines
Quoted 4 lines
/// Consumes the [`Owned`], returning a raw pointer. /// /// This function does not drop the underlying `T`. When this function returns, ownership of the /// underlying `T` is with the caller.SGTM.
OK.
Best regards,
Andreas Hindborg
PATCH v13 2/4 rust: `AlwaysRefCounted` is renamed to `RefCounted`.
In reply to Oliver MangoldAlwaysRefCounted will become a marker trait to indicate that it is allowed to obtain an ARef<T> from a &T, which cannot be allowed for types which are also Ownable.
--- rust/kernel/auxiliary.rs | 7 +++++- rust/kernel/block/mq/request.rs | 15 +++++++------ rust/kernel/cred.rs | 13 ++++++++++-- rust/kernel/device.rs | 13 ++++++++---- rust/kernel/device/property.rs | 7 +++++- rust/kernel/drm/device.rs | 10 ++++++--- rust/kernel/drm/gem/mod.rs | 10 ++++++--- rust/kernel/fs/file.rs | 16 ++++++++++---- rust/kernel/mm.rs | 15 +++++++++---- rust/kernel/mm/mmput_async.rs | 9 ++++++-- rust/kernel/opp.rs | 10 ++++++--- rust/kernel/owned.rs | 2 +- rust/kernel/pci.rs | 10 ++++++--- rust/kernel/pid_namespace.rs | 12 +++++++++-- rust/kernel/platform.rs | 7 +++++- rust/kernel/sync/aref.rs | 47 ++++++++++++++++++++++++++--------------- rust/kernel/task.rs | 10 ++++++--- rust/kernel/types.rs | 2 +- 18 files changed, 154 insertions(+), 61 deletions(-)
rust/kernel/auxiliary.rs +6 -1
@@ -10,6 +10,7 @@ driver, error::{from_result, to_result, Result}, prelude::*, + sync::aref::{AlwaysRefCounted, RefCounted}, types::Opaque, ThisModule, };
@@ -239,7 +240,7 @@ extern "C" fn release(dev: *mut bindings::device) { 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 ()) };
@@ -258,6 +259,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 +9 -6
@@ -8,7 +8,7 @@ bindings, block::mq::Operations, error::Result, - sync::{atomic::Relaxed, Refcount}, + sync::{aref::RefCounted, atomic::Relaxed, Refcount}, types::{ARef, AlwaysRefCounted, Opaque}, };use core::{marker::PhantomData , ptr::NonNull };
@@ -225,11 +225,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 (); }
@@ -251,3 +250,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 +11 -2
@@ -8,7 +8,12 @@//! //! 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 +81,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 +95,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 +9 -4
@@ -5,9 +5,10 @@//! C header: [`include/linux/device.h`](srctree/include/linux/device.h) use crate ::{ - bindings, fmt, - sync::aref::ARef , - types::{ForeignOwnable ,Opaque }, + bindings, + fmt, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted ,ForeignOwnable ,Opaque }, };use core::{marker::PhantomData , ptr};
@@ -407,7 +408,7 @@ pub fn fwnode(&self) -> Option<&property::FwNode> { 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 ()) };
@@ -419,6 +420,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 +6 -1
@@ -14,6 +14,7 @@ fmt, prelude::*, str::{CStr, CString}, + sync::aref::{AlwaysRefCounted, RefCounted}, types::{ARef, Opaque}, };
@@ -359,7 +360,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { }// SAFETY: Instances of `FwNode` are always reference-counted. -unsafe impl crate ::types::AlwaysRefCounted for FwNode { +unsafe impl RefCounted for FwNode {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the // refcount is non-zero.
@@ -373,6 +374,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 -3
@@ -11,8 +11,8 @@ error::from_err_ptr, error::Result, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, Opaque}, };use core::{alloc::Layout , mem, ops::Deref , ptr, ptr::NonNull };
@@ -198,7 +198,7 @@ fn deref(&self) -> &Self::Target {// SAFETY: DRM device objects are always reference counted and the get/put functions // satisfy the requirements. -unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > { +unsafe impl <T : drm::Driver >RefCounted for Device <T > {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_dev_get (self.as_raw ()) };
@@ -213,6 +213,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > {} +impl <T : drm::Driver >AsRef <device::Device >for Device <T > {fn as_ref (&self) -> &device::Device {// SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
rust/kernel/drm/gem/mod.rs +7 -3
@@ -10,8 +10,8 @@ drm::driver::{AllocImpl, AllocOps}, error::{to_result, Result}, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, Opaque}, };use core::{ops::Deref , ptr::NonNull };
@@ -56,7 +56,7 @@ pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted { }// SAFETY: All gem objects are refcounted. -unsafe impl <T :IntoGEMObject >AlwaysRefCounted for T { +unsafe impl <T :IntoGEMObject >RefCounted for T {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_gem_object_get (self.as_raw ()) };
@@ -75,6 +75,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<T>` from a +// `&T`. +unsafe impl <T :IntoGEMObject >crate ::types::AlwaysRefCounted for T {} +extern "C" fn open_callback <T :DriverObject >( raw_obj: *mut bindings::drm_gem_object , raw_file: *mut bindings::drm_file,
rust/kernel/fs/file.rs +12 -4
@@ -12,8 +12,8 @@ cred::Credential, error::{code::*, to_result, Error, Result}, fmt, - sync::aref::{ARef, AlwaysRefCounted}, - types::{NotThreadSafe, Opaque}, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, };use core::ptr;
@@ -192,7 +192,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.
@@ -207,6 +207,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.
@@ -228,7 +232,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.
@@ -244,6 +248,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/mm.rs +11 -4
@@ -13,8 +13,8 @@use crate ::{ bindings, - sync::aref::{ARef ,AlwaysRefCounted }, - types::{NotThreadSafe ,Opaque }, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted ,NotThreadSafe ,Opaque }, };use core::{ops::Deref , ptr::NonNull };
@@ -55,7 +55,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 +69,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 +94,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 +108,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 +7 -2
@@ -10,7 +10,8 @@use crate ::{ bindings, mm::MmWithUser , - sync::aref::{ARef ,AlwaysRefCounted }, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted }, };use core::{ops::Deref , ptr::NonNull };
@@ -34,7 +35,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 +49,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 +7 -3
@@ -16,8 +16,8 @@ ffi::c_ulong, prelude::*, str::CString, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, Opaque}, };#[cfg( CONFIG_CPU_FREQ )]
@@ -1037,7 +1037,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 {fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero. unsafe { bindings::dev_pm_opp_get (self.0 .get ()) };
@@ -1049,6 +1049,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
@@ -21,7 +21,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::types::AlwaysRefCounted) should be implemented. +/// [`RefCounted`](crate::types::RefCounted) should be implemented. /// /// # Safety ///
rust/kernel/pci.rs +7 -3
@@ -13,8 +13,8 @@ io::{Io, IoRaw}, irq::{self, IrqRequest}, str::CStr, - sync::aref::ARef, - types::Opaque, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, Opaque}, ThisModule, };use core::{
@@ -601,7 +601,7 @@ pub fn set_master(&self) {impl crate ::dma::Device for Device <device::Core > {}// 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 ()) };
@@ -613,6 +613,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 +10 -2
@@ -7,7 +7,11 @@//! 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 +45,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 +59,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 +6 -1
@@ -13,6 +13,7 @@ irq::{self, IrqRequest}, of, prelude::*, + sync::aref::{AlwaysRefCounted, RefCounted}, types::Opaque, ThisModule, };
@@ -468,7 +469,7 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {impl crate ::dma::Device for Device <device::Core > {}// 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 ()) };
@@ -480,6 +481,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/sync/aref.rs +30 -17
117 lines not on this page · raw message
rust/kernel/task.rs +7 -3
@@ -9,8 +9,8 @@ ffi::{c_int, c_long, c_uint}, mm::MmWithUser, pid_namespace::PidNamespace, - sync::aref::ARef, - types::{NotThreadSafe, Opaque}, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, NotThreadSafe, Opaque}, };use core::{ cmp::{Eq ,PartialEq },
@@ -348,7 +348,7 @@ pub fn active_pid_ns(&self) -> Option<&PidNamespace> { }// 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.
@@ -362,6 +362,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 Kuid {/// Get the current euid. #[inline]
rust/kernel/types.rs +1 -1
@@ -13,7 +13,7 @@pub use crate ::owned::{Ownable ,Owned }; -pub use crate ::sync::aref::{ARef ,AlwaysRefCounted }; +pub use crate ::sync::aref::{ARef ,AlwaysRefCounted ,RefCounted };/// Used to transfer ownership to and from foreign (non-Rust) languages. ///
Signature · 1 line
2.51.2
Re: [PATCH v13 2/4] rust: `AlwaysRefCounted` is renamed to `RefCounted`.
Quoted 756 lines · Oliver Mangold
AlwaysRefCountedwill become a marker trait to indicate that it is allowed to obtain anARef<T>from a&T, which cannot be allowed for types which are also Ownable.Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Suggested-by Alice Ryhl <[email protected]>---
rust/kernel/auxiliary.rs | 7 +++++- rust/kernel/block/mq/request.rs | 15 +++++++------ rust/kernel/cred.rs | 13 ++++++++++-- rust/kernel/device.rs | 13 ++++++++---- rust/kernel/device/property.rs | 7 +++++- rust/kernel/drm/device.rs | 10 ++++++--- rust/kernel/drm/gem/mod.rs | 10 ++++++--- rust/kernel/fs/file.rs | 16 ++++++++++---- rust/kernel/mm.rs | 15 +++++++++---- rust/kernel/mm/mmput_async.rs | 9 ++++++-- rust/kernel/opp.rs | 10 ++++++--- rust/kernel/owned.rs | 2 +- rust/kernel/pci.rs | 10 ++++++--- rust/kernel/pid_namespace.rs | 12 +++++++++-- rust/kernel/platform.rs | 7 +++++- rust/kernel/sync/aref.rs | 47 ++++++++++++++++++++++++++--------------- rust/kernel/task.rs | 10 ++++++--- rust/kernel/types.rs | 2 +- 18 files changed, 154 insertions(+), 61 deletions(-)rust/kernel/auxiliary.rs +6
-1@@ -10,6 +10,7 @@ driver, error::{from_result, to_result, Result}, prelude::*, + sync::aref::{AlwaysRefCounted, RefCounted}, types::Opaque, ThisModule, };@@ -239,7 +240,7 @@ extern "C" fn release(dev: *mut bindings::device) { 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 ()) };@@ -258,6 +259,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 +9
-6@@ -8,7 +8,7 @@ bindings, block::mq::Operations, error::Result, - sync::{atomic::Relaxed, Refcount}, + sync::{aref::RefCounted, atomic::Relaxed, Refcount}, types::{ARef, AlwaysRefCounted, Opaque}, };use core::{marker::PhantomData , ptr::NonNull };@@ -225,11 +225,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 (); }@@ -251,3 +250,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 +11
-2@@ -8,7 +8,12 @@//! //! 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 +81,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 +95,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 +9
-4@@ -5,9 +5,10 @@//! C header: [`include/linux/device.h`](srctree/include/linux/device.h) use crate ::{ - bindings, fmt, - sync::aref::ARef , - types::{ForeignOwnable ,Opaque }, + bindings, + fmt, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted ,ForeignOwnable ,Opaque }, };use core::{marker::PhantomData , ptr};@@ -407,7 +408,7 @@ pub fn fwnode(&self) -> Option<&property::FwNode> { 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 ()) };@@ -419,6 +420,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 +6
-1@@ -14,6 +14,7 @@ fmt, prelude::*, str::{CStr, CString}, + sync::aref::{AlwaysRefCounted, RefCounted}, types::{ARef, Opaque}, };@@ -359,7 +360,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { }// SAFETY: Instances of `FwNode` are always reference-counted. -unsafe impl crate ::types::AlwaysRefCounted for FwNode { +unsafe impl RefCounted for FwNode {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the // refcount is non-zero. @@ -373,6 +374,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
-3@@ -11,8 +11,8 @@ error::from_err_ptr, error::Result, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, Opaque}, };use core::{alloc::Layout , mem, ops::Deref , ptr, ptr::NonNull };@@ -198,7 +198,7 @@ fn deref(&self) -> &Self::Target {// SAFETY: DRM device objects are always reference counted and the get/put functions // satisfy the requirements. -unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > { +unsafe impl <T : drm::Driver >RefCounted for Device <T > {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_dev_get (self.as_raw ()) };@@ -213,6 +213,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > {} +impl <T : drm::Driver >AsRef <device::Device >for Device <T > {fn as_ref (&self) -> &device::Device {// SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid, rust/kernel/drm/gem/mod.rs +7
-3@@ -10,8 +10,8 @@ drm::driver::{AllocImpl, AllocOps}, error::{to_result, Result}, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, Opaque}, };use core::{ops::Deref , ptr::NonNull };@@ -56,7 +56,7 @@ pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted { }// SAFETY: All gem objects are refcounted. -unsafe impl <T :IntoGEMObject >AlwaysRefCounted for T { +unsafe impl <T :IntoGEMObject >RefCounted for T {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_gem_object_get (self.as_raw ()) };@@ -75,6 +75,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<T>` from a +// `&T`. +unsafe impl <T :IntoGEMObject >crate ::types::AlwaysRefCounted for T {} +extern "C" fn open_callback<T: DriverObject>(
raw_obj: *mutbindings::drm_gem_object,
raw_file: *mutbindings::drm_file,rust/kernel/fs/file.rs +12
-4@@ -12,8 +12,8 @@ cred::Credential, error::{code::*, to_result, Error, Result}, fmt, - sync::aref::{ARef, AlwaysRefCounted}, - types::{NotThreadSafe, Opaque}, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, };use core::ptr;@@ -192,7 +192,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. @@ -207,6 +207,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. @@ -228,7 +232,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. @@ -244,6 +248,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/mm.rs +11
-4@@ -13,8 +13,8 @@use crate ::{ bindings, - sync::aref::{ARef ,AlwaysRefCounted }, - types::{NotThreadSafe ,Opaque }, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted ,NotThreadSafe ,Opaque }, };use core::{ops::Deref , ptr::NonNull };@@ -55,7 +55,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 +69,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 +94,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 +108,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 +7
-2@@ -10,7 +10,8 @@use crate ::{ bindings, mm::MmWithUser , - sync::aref::{ARef ,AlwaysRefCounted }, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted }, };use core::{ops::Deref , ptr::NonNull };@@ -34,7 +35,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 +49,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 +7
-3@@ -16,8 +16,8 @@ ffi::c_ulong, prelude::*, str::CString, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, Opaque}, };#[cfg( CONFIG_CPU_FREQ )] @@ -1037,7 +1037,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 {fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero. unsafe { bindings::dev_pm_opp_get (self.0 .get ()) };@@ -1049,6 +1049,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@@ -21,7 +21,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::types::AlwaysRefCounted) should be implemented. +/// [`RefCounted`](crate::types::RefCounted) should be implemented. /// /// # Safety /// rust/kernel/pci.rs +7
-3@@ -13,8 +13,8 @@ io::{Io, IoRaw}, irq::{self, IrqRequest}, str::CStr, - sync::aref::ARef, - types::Opaque, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, Opaque}, ThisModule, };use core::{@@ -601,7 +601,7 @@ pub fn set_master(&self) {impl crate ::dma::Device for Device <device::Core > {}// 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 ()) };@@ -613,6 +613,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 +10
-2@@ -7,7 +7,11 @@//! 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 +45,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 +59,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 +6
-1@@ -13,6 +13,7 @@ irq::{self, IrqRequest}, of, prelude::*, + sync::aref::{AlwaysRefCounted, RefCounted}, types::Opaque, ThisModule, };@@ -468,7 +469,7 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {impl crate ::dma::Device for Device <device::Core > {}// 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 ()) };@@ -480,6 +481,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/sync/aref.rs +30
-17@@ -19,11 +19,9 @@use core::{marker::PhantomData , mem::ManuallyDrop , ops::Deref , ptr::NonNull }; -/// Types that are _always_ reference counted. +/// Types that are internally reference counted. /// /// It allows such types to define their own custom ref increment and decrement functions. -/// Additionally, it allows users to convert from a shared reference `&T` to an owned reference -/// [`ARef<T>`]. /// /// This is usually implemented by wrappers to existing structures on the C side of the code. For /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted @@ -40,9 +38,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);@@ -55,11 +52,27 @@ pub unsafe trait AlwaysRefCounted {/// Callers must ensure that there was a previous matching increment to the reference count, /// and that the object is no longer used after its reference count is decremented (as it may /// result in the object being freed), unless the caller owns another increment on the refcount -/// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls -/// [`AlwaysRefCounted::dec_ref`] once). +/// (e.g., it calls [`RefCounted::inc_ref`] twice, then calls [`RefCounted::dec_ref`] once). unsafe fn dec_ref (obj:NonNull <Self >); } +/// Always reference-counted type. +/// +/// It allows to derive a counted reference [`ARef<T>`] from a `&T`. +/// +/// This provides some convenience, but it allows "escaping" borrow checks on `&T`. As it +/// complicates attempts to ensure that a reference to T is unique, it is optional to provide for +/// [`RefCounted`] types. See *Safety* below. +/// +/// # Safety +/// +/// Implementers must ensure that no safety invariants are violated by upgrading an `&T` to an +/// [`ARef<T>`]. In particular that implies [`AlwaysRefCounted`] and [`crate::types::Ownable`] +/// cannot be implemented for the same type, as this would allow to violate the uniqueness guarantee +/// of [`crate::types::Owned<T>`] by derefencing it into an `&T` and obtaining an [`ARef`] from +/// that. +pub unsafe trait AlwaysRefCounted :RefCounted {} +/// An owned reference to an always-reference-counted object. /// /// The object's reference count is automatically decremented when an instance of [`ARef`] is @@ -70,7 +83,7 @@ pub unsafe trait AlwaysRefCounted {/// /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count. -pub struct ARef <T :AlwaysRefCounted > { +pub struct ARef <T :RefCounted > { ptr:NonNull <T >, _p:PhantomData <T >, }@@ -79,16 +92,16 @@ pub struct ARef<T: AlwaysRefCounted> {// it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a // mutable reference, for example, when the reference count reaches zero and `T` is dropped. -unsafe impl <T :AlwaysRefCounted +Sync +Send >Send for ARef <T > {} +unsafe impl <T :RefCounted +Sync +Send >Send for ARef <T > {}// SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync` // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for // example, when the reference count reaches zero and `T` is dropped. -unsafe impl <T :AlwaysRefCounted +Sync +Send >Sync for ARef <T > {} +unsafe impl <T :RefCounted +Sync +Send >Sync for ARef <T > {} -impl <T :AlwaysRefCounted >ARef <T > { +impl <T :RefCounted >ARef <T > {/// Creates a new instance of [`ARef`]. /// /// It takes over an increment of the reference count on the underlying object. @@ -117,12 +130,12 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// ``` /// use core::ptr::NonNull; -/// use kernel::sync::aref::{ARef, AlwaysRefCounted}; +/// use kernel::sync::aref::{ARef, RefCounted}; /// /// struct Empty {} /// /// # // SAFETY: TODO. -/// unsafe impl AlwaysRefCounted for Empty { +/// unsafe impl RefCounted for Empty { /// fn inc_ref(&self) {} /// unsafe fn dec_ref(_obj: NonNull<Self>) {} /// } @@ -140,7 +153,7 @@ pub fn into_raw(me: Self) -> NonNull<T> { } } -impl <T :AlwaysRefCounted >Clone for ARef <T > { +impl <T :RefCounted >Clone for ARef <T > {fn clone (&self) ->Self { self.inc_ref ();// SAFETY: We just incremented the refcount above. @@ -148,7 +161,7 @@ fn clone(&self) -> Self { } } -impl <T :AlwaysRefCounted >Deref for ARef <T > { +impl <T :RefCounted >Deref for ARef <T > {type Target =T ;fn deref (&self) -> &Self ::Target {@@ -165,7 +178,7 @@ fn from(b: &T) -> Self { } } -impl <T :AlwaysRefCounted >Drop for ARef <T > { +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 // decrement. rust/kernel/task.rs +7
-3@@ -9,8 +9,8 @@ ffi::{c_int, c_long, c_uint}, mm::MmWithUser, pid_namespace::PidNamespace, - sync::aref::ARef, - types::{NotThreadSafe, Opaque}, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, NotThreadSafe, Opaque}, };use core::{ cmp::{Eq ,PartialEq },@@ -348,7 +348,7 @@ pub fn active_pid_ns(&self) -> Option<&PidNamespace> { }// 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. @@ -362,6 +362,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 Kuid {/// Get the current euid. #[inline] rust/kernel/types.rs +1
-1@@ -13,7 +13,7 @@pub use crate ::owned::{Ownable ,Owned }; -pub use crate ::sync::aref::{ARef ,AlwaysRefCounted }; +pub use crate ::sync::aref::{ARef ,AlwaysRefCounted ,RefCounted };/// Used to transfer ownership to and from foreign (non-Rust) languages. /// Signature · 2 lines
-- 2.51.2
Can you use imperative voice in the title? i.e.:
rust: rename AlwaysRefCounted to `RefCounted
…or something similar?
Andreas Hindborg
maintainerRe: [PATCH v13 2/4] rust: `AlwaysRefCounted` is renamed to `RefCounted`.
Quoted 757 lines · Daniel Almeida
Quoted 754 lines · Oliver Mangold
AlwaysRefCountedwill become a marker trait to indicate that it is allowed to obtain anARef<T>from a&T, which cannot be allowed for types which are also Ownable.Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Suggested-by Alice Ryhl <[email protected]>---
rust/kernel/auxiliary.rs | 7 +++++- rust/kernel/block/mq/request.rs | 15 +++++++------ rust/kernel/cred.rs | 13 ++++++++++-- rust/kernel/device.rs | 13 ++++++++---- rust/kernel/device/property.rs | 7 +++++- rust/kernel/drm/device.rs | 10 ++++++--- rust/kernel/drm/gem/mod.rs | 10 ++++++--- rust/kernel/fs/file.rs | 16 ++++++++++---- rust/kernel/mm.rs | 15 +++++++++---- rust/kernel/mm/mmput_async.rs | 9 ++++++-- rust/kernel/opp.rs | 10 ++++++--- rust/kernel/owned.rs | 2 +- rust/kernel/pci.rs | 10 ++++++--- rust/kernel/pid_namespace.rs | 12 +++++++++-- rust/kernel/platform.rs | 7 +++++- rust/kernel/sync/aref.rs | 47 ++++++++++++++++++++++++++--------------- rust/kernel/task.rs | 10 ++++++--- rust/kernel/types.rs | 2 +- 18 files changed, 154 insertions(+), 61 deletions(-)rust/kernel/auxiliary.rs +6
-1@@ -10,6 +10,7 @@ driver, error::{from_result, to_result, Result}, prelude::*, + sync::aref::{AlwaysRefCounted, RefCounted}, types::Opaque, ThisModule, };@@ -239,7 +240,7 @@ extern "C" fn release(dev: *mut bindings::device) { 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 ()) };@@ -258,6 +259,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 +9
-6@@ -8,7 +8,7 @@ bindings, block::mq::Operations, error::Result, - sync::{atomic::Relaxed, Refcount}, + sync::{aref::RefCounted, atomic::Relaxed, Refcount}, types::{ARef, AlwaysRefCounted, Opaque}, };use core::{marker::PhantomData , ptr::NonNull };@@ -225,11 +225,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 (); }@@ -251,3 +250,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 +11
-2@@ -8,7 +8,12 @@//! //! 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 +81,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 +95,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 +9
-4@@ -5,9 +5,10 @@//! C header: [`include/linux/device.h`](srctree/include/linux/device.h) use crate ::{ - bindings, fmt, - sync::aref::ARef , - types::{ForeignOwnable ,Opaque }, + bindings, + fmt, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted ,ForeignOwnable ,Opaque }, };use core::{marker::PhantomData , ptr};@@ -407,7 +408,7 @@ pub fn fwnode(&self) -> Option<&property::FwNode> { 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 ()) };@@ -419,6 +420,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 +6
-1@@ -14,6 +14,7 @@ fmt, prelude::*, str::{CStr, CString}, + sync::aref::{AlwaysRefCounted, RefCounted}, types::{ARef, Opaque}, };@@ -359,7 +360,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { }// SAFETY: Instances of `FwNode` are always reference-counted. -unsafe impl crate ::types::AlwaysRefCounted for FwNode { +unsafe impl RefCounted for FwNode {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the // refcount is non-zero. @@ -373,6 +374,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
-3@@ -11,8 +11,8 @@ error::from_err_ptr, error::Result, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, Opaque}, };use core::{alloc::Layout , mem, ops::Deref , ptr, ptr::NonNull };@@ -198,7 +198,7 @@ fn deref(&self) -> &Self::Target {// SAFETY: DRM device objects are always reference counted and the get/put functions // satisfy the requirements. -unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > { +unsafe impl <T : drm::Driver >RefCounted for Device <T > {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_dev_get (self.as_raw ()) };@@ -213,6 +213,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a +// `&Device`. +unsafe impl <T : drm::Driver >AlwaysRefCounted for Device <T > {} +impl <T : drm::Driver >AsRef <device::Device >for Device <T > {fn as_ref (&self) -> &device::Device {// SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid, rust/kernel/drm/gem/mod.rs +7
-3@@ -10,8 +10,8 @@ drm::driver::{AllocImpl, AllocOps}, error::{to_result, Result}, prelude::*, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, Opaque}, };use core::{ops::Deref , ptr::NonNull };@@ -56,7 +56,7 @@ pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted { }// SAFETY: All gem objects are refcounted. -unsafe impl <T :IntoGEMObject >AlwaysRefCounted for T { +unsafe impl <T :IntoGEMObject >RefCounted for T {fn inc_ref (&self) {// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. unsafe { bindings::drm_gem_object_get (self.as_raw ()) };@@ -75,6 +75,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) { } } +// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<T>` from a +// `&T`. +unsafe impl <T :IntoGEMObject >crate ::types::AlwaysRefCounted for T {} +extern "C" fn open_callback<T: DriverObject>(
raw_obj: *mutbindings::drm_gem_object,
raw_file: *mutbindings::drm_file,rust/kernel/fs/file.rs +12
-4@@ -12,8 +12,8 @@ cred::Credential, error::{code::*, to_result, Error, Result}, fmt, - sync::aref::{ARef, AlwaysRefCounted}, - types::{NotThreadSafe, Opaque}, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, };use core::ptr;@@ -192,7 +192,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. @@ -207,6 +207,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. @@ -228,7 +232,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. @@ -244,6 +248,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/mm.rs +11
-4@@ -13,8 +13,8 @@use crate ::{ bindings, - sync::aref::{ARef ,AlwaysRefCounted }, - types::{NotThreadSafe ,Opaque }, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted ,NotThreadSafe ,Opaque }, };use core::{ops::Deref , ptr::NonNull };@@ -55,7 +55,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 +69,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 +94,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 +108,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 +7
-2@@ -10,7 +10,8 @@use crate ::{ bindings, mm::MmWithUser , - sync::aref::{ARef ,AlwaysRefCounted }, + sync::aref::RefCounted , + types::{ARef ,AlwaysRefCounted }, };use core::{ops::Deref , ptr::NonNull };@@ -34,7 +35,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 +49,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 +7
-3@@ -16,8 +16,8 @@ ffi::c_ulong, prelude::*, str::CString, - sync::aref::{ARef, AlwaysRefCounted}, - types::Opaque, + sync::aref::RefCounted, + types::{ARef, AlwaysRefCounted, Opaque}, };#[cfg( CONFIG_CPU_FREQ )] @@ -1037,7 +1037,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 {fn inc_ref (&self) {// SAFETY: The existence of a shared reference means that the refcount is nonzero. unsafe { bindings::dev_pm_opp_get (self.0 .get ()) };@@ -1049,6 +1049,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@@ -21,7 +21,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::types::AlwaysRefCounted) should be implemented. +/// [`RefCounted`](crate::types::RefCounted) should be implemented. /// /// # Safety /// rust/kernel/pci.rs +7
-3@@ -13,8 +13,8 @@ io::{Io, IoRaw}, irq::{self, IrqRequest}, str::CStr, - sync::aref::ARef, - types::Opaque, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, Opaque}, ThisModule, };use core::{@@ -601,7 +601,7 @@ pub fn set_master(&self) {impl crate ::dma::Device for Device <device::Core > {}// 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 ()) };@@ -613,6 +613,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 +10
-2@@ -7,7 +7,11 @@//! 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 +45,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 +59,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 +6
-1@@ -13,6 +13,7 @@ irq::{self, IrqRequest}, of, prelude::*, + sync::aref::{AlwaysRefCounted, RefCounted}, types::Opaque, ThisModule, };@@ -468,7 +469,7 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {impl crate ::dma::Device for Device <device::Core > {}// 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 ()) };@@ -480,6 +481,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/sync/aref.rs +30
-17@@ -19,11 +19,9 @@use core::{marker::PhantomData , mem::ManuallyDrop , ops::Deref , ptr::NonNull }; -/// Types that are _always_ reference counted. +/// Types that are internally reference counted. /// /// It allows such types to define their own custom ref increment and decrement functions. -/// Additionally, it allows users to convert from a shared reference `&T` to an owned reference -/// [`ARef<T>`]. /// /// This is usually implemented by wrappers to existing structures on the C side of the code. For /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted @@ -40,9 +38,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);@@ -55,11 +52,27 @@ pub unsafe trait AlwaysRefCounted {/// Callers must ensure that there was a previous matching increment to the reference count, /// and that the object is no longer used after its reference count is decremented (as it may /// result in the object being freed), unless the caller owns another increment on the refcount -/// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls -/// [`AlwaysRefCounted::dec_ref`] once). +/// (e.g., it calls [`RefCounted::inc_ref`] twice, then calls [`RefCounted::dec_ref`] once). unsafe fn dec_ref (obj:NonNull <Self >); } +/// Always reference-counted type. +/// +/// It allows to derive a counted reference [`ARef<T>`] from a `&T`. +/// +/// This provides some convenience, but it allows "escaping" borrow checks on `&T`. As it +/// complicates attempts to ensure that a reference to T is unique, it is optional to provide for +/// [`RefCounted`] types. See *Safety* below. +/// +/// # Safety +/// +/// Implementers must ensure that no safety invariants are violated by upgrading an `&T` to an +/// [`ARef<T>`]. In particular that implies [`AlwaysRefCounted`] and [`crate::types::Ownable`] +/// cannot be implemented for the same type, as this would allow to violate the uniqueness guarantee +/// of [`crate::types::Owned<T>`] by derefencing it into an `&T` and obtaining an [`ARef`] from +/// that. +pub unsafe trait AlwaysRefCounted :RefCounted {} +/// An owned reference to an always-reference-counted object. /// /// The object's reference count is automatically decremented when an instance of [`ARef`] is @@ -70,7 +83,7 @@ pub unsafe trait AlwaysRefCounted {/// /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count. -pub struct ARef <T :AlwaysRefCounted > { +pub struct ARef <T :RefCounted > { ptr:NonNull <T >, _p:PhantomData <T >, }@@ -79,16 +92,16 @@ pub struct ARef<T: AlwaysRefCounted> {// it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a // mutable reference, for example, when the reference count reaches zero and `T` is dropped. -unsafe impl <T :AlwaysRefCounted +Sync +Send >Send for ARef <T > {} +unsafe impl <T :RefCounted +Sync +Send >Send for ARef <T > {}// SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync` // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for // example, when the reference count reaches zero and `T` is dropped. -unsafe impl <T :AlwaysRefCounted +Sync +Send >Sync for ARef <T > {} +unsafe impl <T :RefCounted +Sync +Send >Sync for ARef <T > {} -impl <T :AlwaysRefCounted >ARef <T > { +impl <T :RefCounted >ARef <T > {/// Creates a new instance of [`ARef`]. /// /// It takes over an increment of the reference count on the underlying object. @@ -117,12 +130,12 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// ``` /// use core::ptr::NonNull; -/// use kernel::sync::aref::{ARef, AlwaysRefCounted}; +/// use kernel::sync::aref::{ARef, RefCounted}; /// /// struct Empty {} /// /// # // SAFETY: TODO. -/// unsafe impl AlwaysRefCounted for Empty { +/// unsafe impl RefCounted for Empty { /// fn inc_ref(&self) {} /// unsafe fn dec_ref(_obj: NonNull<Self>) {} /// } @@ -140,7 +153,7 @@ pub fn into_raw(me: Self) -> NonNull<T> { } } -impl <T :AlwaysRefCounted >Clone for ARef <T > { +impl <T :RefCounted >Clone for ARef <T > {fn clone (&self) ->Self { self.inc_ref ();// SAFETY: We just incremented the refcount above. @@ -148,7 +161,7 @@ fn clone(&self) -> Self { } } -impl <T :AlwaysRefCounted >Deref for ARef <T > { +impl <T :RefCounted >Deref for ARef <T > {type Target =T ;fn deref (&self) -> &Self ::Target {@@ -165,7 +178,7 @@ fn from(b: &T) -> Self { } } -impl <T :AlwaysRefCounted >Drop for ARef <T > { +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 // decrement. rust/kernel/task.rs +7
-3@@ -9,8 +9,8 @@ ffi::{c_int, c_long, c_uint}, mm::MmWithUser, pid_namespace::PidNamespace, - sync::aref::ARef, - types::{NotThreadSafe, Opaque}, + sync::aref::{AlwaysRefCounted, RefCounted}, + types::{ARef, NotThreadSafe, Opaque}, };use core::{ cmp::{Eq ,PartialEq },@@ -348,7 +348,7 @@ pub fn active_pid_ns(&self) -> Option<&PidNamespace> { }// 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. @@ -362,6 +362,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 Kuid {/// Get the current euid. #[inline] rust/kernel/types.rs +1
-1@@ -13,7 +13,7 @@pub use crate ::owned::{Ownable ,Owned }; -pub use crate ::sync::aref::{ARef ,AlwaysRefCounted }; +pub use crate ::sync::aref::{ARef ,AlwaysRefCounted ,RefCounted };/// Used to transfer ownership to and from foreign (non-Rust) languages. /// Signature · 2 lines
-- 2.51.2Can you use imperative voice in the title? i.e.:
Quoted 5 lines
rust: rename
AlwaysRefCountedto `RefCounted…or something similar?
Reviewed-by Daniel Almeida <[email protected]>
How about this:
rust: rename AlwaysRefCounted to RefCounted.
Change AlwaysRefCounted to be a marker trait that indicate that obtaining an ARef<T> from a &T 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.
Best regards,
Andreas Hindborg
Gary Guo
maintainerRe: [PATCH v13 2/4] rust: `AlwaysRefCounted` is renamed to `RefCounted`.
In reply to Oliver MangoldQuoted 3 lines · On Mon, 17 Nov 2025 10:07:57 +0000 Oliver Mangold <[email protected]> wrote:
AlwaysRefCountedwill become a marker trait to indicate that it is allowed to obtain anARef<T>from a&T, which cannot be allowed for types which are also Ownable.
The message needs a rationale for making the change rather than relying on the reader to deduce so.
For example:
There are types where it may both be referenced counted in some cases and owned in other. 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.
Best,
Gary
Quoted 25 lines
Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Suggested-by Alice Ryhl <[email protected]>--- rust/kernel/auxiliary.rs | 7 +++++- rust/kernel/block/mq/request.rs | 15 +++++++------ rust/kernel/cred.rs | 13 ++++++++++-- rust/kernel/device.rs | 13 ++++++++---- rust/kernel/device/property.rs | 7 +++++- rust/kernel/drm/device.rs | 10 ++++++--- rust/kernel/drm/gem/mod.rs | 10 ++++++--- rust/kernel/fs/file.rs | 16 ++++++++++---- rust/kernel/mm.rs | 15 +++++++++---- rust/kernel/mm/mmput_async.rs | 9 ++++++-- rust/kernel/opp.rs | 10 ++++++--- rust/kernel/owned.rs | 2 +- rust/kernel/pci.rs | 10 ++++++--- rust/kernel/pid_namespace.rs | 12 +++++++++-- rust/kernel/platform.rs | 7 +++++- rust/kernel/sync/aref.rs | 47 ++++++++++++++++++++++++++--------------- rust/kernel/task.rs | 10 ++++++--- rust/kernel/types.rs | 2 +- 18 files changed, 154 insertions(+), 61 deletions(-)
Andreas Hindborg
maintainerRe: [PATCH v13 2/4] rust: `AlwaysRefCounted` is renamed to `RefCounted`.
Quoted 17 lines · Gary Guo
Quoted 3 lines · On Mon, 17 Nov 2025 10:07:57 +0000 Oliver Mangold <[email protected]> wrote:
AlwaysRefCountedwill become a marker trait to indicate that it is allowed to obtain anARef<T>from a&T, which cannot be allowed for types which are also Ownable.The message needs a rationale for making the change rather than relying on the reader to deduce so.
For example:
There are types where it may both be referenced counted in some cases and owned in other. In such cases, obtaining
ARef<T>from&Twould be unsound as it allows creation ofARef<T>copy from&Owned<T>.
Quoted 4 lines
Therefore, we split
AlwaysRefCountedintoRefCounted(whichARef<T>would require) and a marker trait to indicate that the type is always reference counted (and notOwnable) so the&T->ARef<T>conversion is possible.
Thanks, I'll mix this in with the one I sent to Daniel.
Best regards,
Andreas Hindborg
PATCH v13 3/4 rust: Add missing SAFETY documentation for `ARef` example
In reply to Oliver MangoldSAFETY comment in rustdoc example was just 'TODO'. Fixed.
--- rust/kernel/sync/aref.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
rust/kernel/sync/aref.rs +6 -4
@@ -129,12 +129,14 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// # Examples /// /// ``` -/// use core::ptr::NonNull; -/// use kernel::sync::aref::{ARef, RefCounted}; +/// # use core::ptr::NonNull; +/// # use kernel::sync::aref::{ARef, RefCounted}; /// /// 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 having a refcount on 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>) {}
@@ -142,7 +144,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
Re: [PATCH v13 3/4] rust: Add missing SAFETY documentation for `ARef` example
Quoted 21 lines · Oliver Mangold
SAFETY comment in rustdoc example was just 'TODO'. Fixed.
Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>---
rust/kernel/sync/aref.rs| 10 ++++++----1 file changed, 6 insertions(+), 4 deletions(-)rust/kernel/sync/aref.rs +0
-0@@ -129,12 +129,14 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// # Examples /// /// ```
rust/kernel/sync/aref.rs pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { · line 138
Quoted 10 lines
rust/kernel/sync/aref.rs +4
-3-/// use core::ptr::NonNull; -/// use kernel::sync::aref::{ARef, RefCounted}; +/// # use core::ptr::NonNull; +/// # use kernel::sync::aref::{ARef, RefCounted}; /// /// 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 having a refcount on the object
nit: perhaps saying “an increment on the refcount” is clearer?
Quoted 19 lines
rust/kernel/sync/aref.rs +2
-1+/// // that we pass to the newly created `ARef`. /// unsafe impl RefCounted for Empty { /// fn inc_ref(&self) {} /// unsafe fn dec_ref(_obj: NonNull<Self>) {} @@ -142,7 +144,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 · 2 lines
-- 2.51.2
Andreas Hindborg
maintainerRe: [PATCH v13 3/4] rust: Add missing SAFETY documentation for `ARef` example
Quoted 23 lines · Daniel Almeida
Quoted 23 lines · Oliver Mangold
SAFETY comment in rustdoc example was just 'TODO'. Fixed.
Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>---
rust/kernel/sync/aref.rs| 10 ++++++----1 file changed, 6 insertions(+), 4 deletions(-)rust/kernel/sync/aref.rs +2
-2@@ -129,12 +129,14 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// # Examples /// /// ``` -/// use core::ptr::NonNull; -/// use kernel::sync::aref::{ARef, RefCounted}; +/// # use core::ptr::NonNull; +/// # use kernel::sync::aref::{ARef, RefCounted};
Quoted 8 lines
rust/kernel/sync/aref.rs pub unsafe fn from_raw(ptr: NonNull<T>) -> Self { · line 138
Quoted 6 lines
rust/kernel/sync/aref.rs +2
-1/// /// 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 having a refcount on the object nit: perhaps saying “an increment on the refcount” is clearer?
OK
/// // 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`.Quoted 15 lines
Quoted 15 lines
rust/kernel/sync/aref.rs +2
-1+/// // that we pass to the newly created `ARef`. /// unsafe impl RefCounted for Empty { /// fn inc_ref(&self) {} /// unsafe fn dec_ref(_obj: NonNull<Self>) {} @@ -142,7 +144,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); ///
Quoted 7 lines
Quoted 5 lines
Signature · 1 line
2.51.2Reviewed-by Daniel Almeida <[email protected]>
Thanks.
Best regards,
Andreas Hindborg
PATCH v13 4/4 rust: Add `OwnableRefCounted`
In reply to Oliver MangoldTypes 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().
--- rust/kernel/owned.rs | 138 ++++++++++++++++++++++++++++++++++++++++++++--- rust/kernel/sync/aref.rs | 11 +++- rust/kernel/types.rs | 2 +- 3 files changed, 141 insertions(+), 10 deletions(-)
rust/kernel/owned.rs +130 -8
@@ -5,6 +5,7 @@//! These pointer types are useful for C-allocated objects which by API-contract //! are owned by Rust, but need to be freed through the C API. +use crate ::sync::aref::{ARef ,RefCounted };use core::{ mem::ManuallyDrop , ops::{Deref ,DerefMut },
@@ -14,14 +15,16 @@/// Type allocated and destroyed on the C side, but owned by Rust. /// -/// 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. /// /// # Safety ///
@@ -143,9 +146,7 @@ impl<T: Ownable> Owned<T> {/// mutable reference requirements. That is, the kernel will not mutate or free the underlying /// object and is okay with it being modified by Rust code. pub unsafe fn from_raw (ptr:NonNull <T >) ->Self { -Self { - ptr, - } +Self { ptr } }/// Consumes the [`Owned`], returning a raw pointer.
@@ -193,3 +194,124 @@ fn drop(&mut self) {unsafe {T ::release (self.ptr) }; } } + +/// 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}; +/// +/// // Example internally refcounted struct. +/// // +/// // # Invariants +/// // +/// // - `refcount` is always non-zero for a valid object. +/// // - `refcount` is >1 if there are more than 1 Rust reference to it. +/// // +/// struct Foo { +/// refcount: Cell<usize>, +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo { +/// refcount: Cell::new(1), +/// }, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and +/// // we won't use the raw pointer anymore, thus we can transfer ownership to the `Owned`. +/// 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) +/// } +/// } +/// } +/// +/// // SAFETY: This implementation of `release()` is safe for any valid `Self`. +/// unsafe 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().expect("Failed to allocate a Foo. This shouldn't happen"); +/// let mut foo = ARef::from(foo); +/// { +/// let bar = foo.clone(); +/// assert!(Owned::try_from(bar).is_err()); +/// } +/// assert!(Owned::try_from(foo).is_ok()); +/// ``` +pub trait OwnableRefCounted :RefCounted +Ownable +Sized { +/// Checks if the [`ARef`] is unique and convert it to an [`Owned`] it that is that 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 > { +// SAFETY: Safe by the requirements on implementing the trait. +unsafe {ARef ::from_raw (Owned ::into_raw (this)) } + } +} + +impl <T :OwnableRefCounted >TryFrom <ARef <T >>for Owned <T > { +type Error =ARef <T >; +/// Tries to convert the [`ARef`] to an [`Owned`] by calling +/// [`try_from_shared()`](OwnableRefCounted::try_from_shared). In case the [`ARef`] is not +/// unique, it returns again an [`ARef`] to the same underlying object. +fn try_from (b:ARef <T >) ->Result <Owned <T >,Self ::Error > { +T ::try_from_shared (b) + } +}
rust/kernel/sync/aref.rs +10 -1
@@ -30,7 +30,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`](crate::types::OwnableRefCounted) allows to convert between unique and +/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and +/// [`ARef<Self>`](crate::types::Owned)). /// /// # Safety ///
@@ -180,6 +183,12 @@ fn from(b: &T) -> Self { } } +impl <T :crate ::types::OwnableRefCounted >From <crate ::types::Owned <T >>for ARef <T > { +fn from (b:crate ::types::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 -1
@@ -11,7 +11,7 @@ };use pin_init::{PinInit ,Wrapper ,Zeroable }; -pub use crate ::owned::{Ownable ,Owned }; +pub use crate ::owned::{Ownable ,OwnableRefCounted ,Owned };pub use crate ::sync::aref::{ARef ,AlwaysRefCounted ,RefCounted };
Signature · 1 line
2.51.2
Daniel Almeida
reviewerRe: [PATCH v13 4/4] rust: Add `OwnableRefCounted`
Hi Oliver,
Quoted 54 lines · Oliver Mangold
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().Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Andreas Hindborg <[email protected]>---
rust/kernel/owned.rs | 138 ++++++++++++++++++++++++++++++++++++++++++++--- rust/kernel/sync/aref.rs | 11 +++- rust/kernel/types.rs | 2 +- 3 files changed, 141 insertions(+), 10 deletions(-)rust/kernel/owned.rs +8
-5@@ -5,6 +5,7 @@//! These pointer types are useful for C-allocated objects which by API-contract //! are owned by Rust, but need to be freed through the C API. +use crate ::sync::aref::{ARef ,RefCounted };use core::{ mem::ManuallyDrop , ops::{Deref ,DerefMut },@@ -14,14 +15,16 @@/// Type allocated and destroyed on the C side, but owned by Rust. /// -/// 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. /// /// # Safety ///
rust/kernel/owned.rs impl<T: Ownable> Owned<T> { · line 150
Quoted 8 lines
rust/kernel/owned.rs +1
-3@@ -143,9 +146,7 @@ impl<T: Ownable> Owned<T> {/// mutable reference requirements. That is, the kernel will not mutate or free the underlying /// object and is okay with it being modified by Rust code. pub unsafe fn from_raw (ptr:NonNull <T >) ->Self { -Self { - ptr, - } +Self { ptr } }
Unrelated change?
Quoted 14 lines
rust/kernel/owned.rs +8
-0/// Consumes the [`Owned`], returning a raw pointer. @@ -193,3 +194,124 @@ fn drop(&mut self) {unsafe {T ::release (self.ptr) }; } } + +/// 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:
rust/kernel/owned.rs fn drop(&mut self) { · line 214
Quoted 10 lines
rust/kernel/owned.rs +10
-0+/// +/// ``` +/// # #![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}; +/// +/// // Example internally refcounted struct.
nit: IMHO the wording could improve ^
Quoted 55 lines
rust/kernel/owned.rs +55
-0+/// // +/// // # Invariants +/// // +/// // - `refcount` is always non-zero for a valid object. +/// // - `refcount` is >1 if there are more than 1 Rust reference to it. +/// // +/// struct Foo { +/// refcount: Cell<usize>, +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo { +/// refcount: Cell::new(1), +/// }, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and +/// // we won't use the raw pointer anymore, thus we can transfer ownership to the `Owned`. +/// 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>> {
rust/kernel/owned.rs fn drop(&mut self) { · line 279
Quoted 10 lines
rust/kernel/owned.rs +10
-0+/// 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) +/// } +/// } +/// } +///
We wouldn’t need this implementation if we added a “refcount()” member to this trait. This lets you abstract away this logic for all implementors, which has the massive upside of making sure we hardcode (and thus enforce) the refcount == 1 check.
rust/kernel/owned.rs fn drop(&mut self) { · line 289
Quoted 10 lines
rust/kernel/owned.rs +10
-0+/// // SAFETY: This implementation of `release()` is safe for any valid `Self`. +/// unsafe 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().expect("Failed to allocate a Foo. This shouldn't happen");
All these “expects()” and custom error strings would go away if you place this behind a fictional function that returns Result.
rust/kernel/owned.rs fn drop(&mut self) { · line 300
Quoted 11 lines
rust/kernel/owned.rs +11
-0+/// let mut foo = ARef::from(foo); +/// { +/// let bar = foo.clone(); +/// assert!(Owned::try_from(bar).is_err()); +/// } +/// assert!(Owned::try_from(foo).is_ok()); +/// ``` +pub trait OwnableRefCounted :RefCounted +Ownable +Sized { +/// Checks if the [`ARef`] is unique and convert it to an [`Owned`] it that is that case. +/// Otherwise it returns again an [`ARef`] to the same underlying object. +fn try_from_shared (this:ARef <Self >) ->Result <Owned <Self >,ARef <Self >>;
Again, this method can go way if we add a method to expose the refcount.
Quoted 34 lines
rust/kernel/owned.rs +17
-0+ +/// Converts the [`Owned`] into an [`ARef`]. +fn into_shared (this:Owned <Self >) ->ARef <Self > { +// SAFETY: Safe by the requirements on implementing the trait. +unsafe {ARef ::from_raw (Owned ::into_raw (this)) } + } +} + +impl <T :OwnableRefCounted >TryFrom <ARef <T >>for Owned <T > { +type Error =ARef <T >; +/// Tries to convert the [`ARef`] to an [`Owned`] by calling +/// [`try_from_shared()`](OwnableRefCounted::try_from_shared). In case the [`ARef`] is not +/// unique, it returns again an [`ARef`] to the same underlying object. +fn try_from (b:ARef <T >) ->Result <Owned <T >,Self ::Error > { +T ::try_from_shared (b) + } +}rust/kernel/sync/aref.rs +4
-1@@ -30,7 +30,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`](crate::types::OwnableRefCounted) allows to convert between unique and +/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and +/// [`ARef<Self>`](crate::types::Owned)). /// /// # Safety ///
rust/kernel/sync/aref.rs fn from(b: &T) -> Self { · line 191
Quoted 9 lines
rust/kernel/sync/aref.rs +6
-0@@ -180,6 +183,12 @@ fn from(b: &T) -> Self { } } +impl <T :crate ::types::OwnableRefCounted >From <crate ::types::Owned <T >>for ARef <T > { +fn from (b:crate ::types::Owned <T >) ->Self { +T ::into_shared (b) + } +} +
Not sure why we’re using fully-qualified names here if we can import them, but your call.
Quoted 22 lines
rust/kernel/sync/aref.rs +0
-0impl <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
-1@@ -11,7 +11,7 @@ };use pin_init::{PinInit ,Wrapper ,Zeroable }; -pub use crate ::owned::{Ownable ,Owned }; +pub use crate ::owned::{Ownable ,OwnableRefCounted ,Owned };pub use crate ::sync::aref::{ARef ,AlwaysRefCounted ,RefCounted };Signature · 2 lines
-- 2.51.2
— Daniel
Re: [PATCH v13 4/4] rust: Add `OwnableRefCounted`
Quoted 23 lines · Daniel Almeida
Quoted 23 lines
/// Type allocated and destroyed on the C side, but owned by Rust. ///
rust/kernel/owned.rs +5
-4-/// 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,rust/kernel/owned.rs +2
-1-/// [`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. ///
/// # Safety
///rust/kernel/owned.rs +0
-0@@ -143,9 +146,7 @@ impl<T: Ownable> Owned<T> {/// mutable reference requirements. That is, the kernel will not mutate or free the underlying /// object and is okay with it being modified by Rust code.
Quoted 8 lines
rust/kernel/owned.rs impl<T: Ownable> Owned<T> { · line 150
Quoted 6 lines
rust/kernel/owned.rs +1
-3pub unsafe fn from_raw (ptr:NonNull <T >) ->Self { -Self { - ptr, - } +Self { ptr } }Unrelated change?
Ah, yes, rustfmt must I done that, and I missed it. Will fix.
Quoted 10 lines
Quoted 10 lines
rust/kernel/owned.rs +10
-0+/// +/// 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) +/// }
Quoted 8 lines
rust/kernel/owned.rs fn drop(&mut self) { · line 243
Quoted 3 lines
rust/kernel/owned.rs +3
-0+/// } +/// } +/// We wouldn’t need this implementation if we added a “refcount()” member to this trait. This lets you abstract away this logic for all implementors, which has the massive upside of making sure we hardcode (and thus enforce) the refcount == 1 check.
This wouldn't work for the block Request use case. There a reference can be acquired "out of thin air" using a TagSet. Thus "check for unique refcount" + "create an owned reference" needs to be one atomic operation.
Also I think it might be generally problematic to require a refcount() function. The API of the underlying kernel object we want to wrap might not offer that, so we would need to access internal data.
Quoted 5 lines
Quoted 5 lines
rust/kernel/owned.rs +5
-0+/// // SAFETY: This implementation of `release()` is safe for any valid `Self`. +/// unsafe 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>`].
Quoted 8 lines
rust/kernel/owned.rs fn drop(&mut self) { · line 289
Quoted 5 lines
rust/kernel/owned.rs +5
-0+/// unsafe{ Foo::dec_ref(this) }; +/// } +/// } +/// +/// let foo = Foo::new().expect("Failed to allocate a Foo. This shouldn't happen"); All these “expects()” and custom error strings would go away if you place this behind a fictional function that returns Result.
Not sure what you mean by fictional function. Do you mean a non-existent function? We want to compile this code as a unit test.
The rest of your suggested changes make sense, I guess. I will implement them.
Thanks,
Oliver
Re: [PATCH v13 4/4] rust: Add `OwnableRefCounted`
Quoted 2 lines · Oliver Mangold
Ah, yes, rustfmt must I done that, and I missed it. Will fix.
Strange -- if you noticed a case where rustfmt wasn't idempotent, please let us (and upstream) know about it.
Quoted 2 lines
Not sure what you mean by fictional function. Do you mean a non-existent function? We want to compile this code as a unit test.
Typically that means either using a (hidden on rendering) function that wraps the code and returns a Result or directly a doctest that returns one (better, when applicable). Please check other tests for lines like
/// # Ok::<(), Error>(())
I hope that helps!
Cheers,
Miguel
Andreas Hindborg
maintainerRe: [PATCH v13 4/4] rust: Add `OwnableRefCounted`
In reply to Daniel AlmeidaQuoted 58 lines · Daniel Almeida
Hi Oliver,
Quoted 56 lines · Oliver Mangold
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().Signed-off-by Oliver Mangold <[email protected]>Co-developed-by Andreas Hindborg <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>Reviewed-by Andreas Hindborg <[email protected]>---
rust/kernel/owned.rs | 138 ++++++++++++++++++++++++++++++++++++++++++++--- rust/kernel/sync/aref.rs | 11 +++- rust/kernel/types.rs | 2 +- 3 files changed, 141 insertions(+), 10 deletions(-)rust/kernel/owned.rs +8
-5@@ -5,6 +5,7 @@//! These pointer types are useful for C-allocated objects which by API-contract //! are owned by Rust, but need to be freed through the C API. +use crate ::sync::aref::{ARef ,RefCounted };use core::{ mem::ManuallyDrop , ops::{Deref ,DerefMut },@@ -14,14 +15,16 @@/// Type allocated and destroyed on the C side, but owned by Rust. /// -/// 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. /// /// # Safety /// @@ -143,9 +146,7 @@ impl<T: Ownable> Owned<T> {/// mutable reference requirements. That is, the kernel will not mutate or free the underlying /// object and is okay with it being modified by Rust code.
Quoted 8 lines
rust/kernel/owned.rs impl<T: Ownable> Owned<T> { · line 150
Quoted 6 lines
rust/kernel/owned.rs +1
-3pub unsafe fn from_raw (ptr:NonNull <T >) ->Self { -Self { - ptr, - } +Self { ptr } }Unrelated change?
Looks like a rustfmt thing. I'll split it out or remove it.
Quoted 19 lines
Quoted 19 lines
rust/kernel/owned.rs +12
-0/// Consumes the [`Owned`], returning a raw pointer. @@ -193,3 +194,124 @@ fn drop(&mut self) {unsafe {T ::release (self.ptr) }; } } + +/// 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;
Quoted 8 lines
rust/kernel/owned.rs fn drop(&mut self) { · line 214
Quoted 6 lines
rust/kernel/owned.rs +6
-0+/// # use core::ptr::NonNull; +/// # use kernel::alloc::{flags, kbox::KBox, AllocError}; +/// # use kernel::sync::aref::{ARef, RefCounted}; +/// # use kernel::types::{Owned, Ownable, OwnableRefCounted}; +/// +/// // Example internally refcounted struct. nit: IMHO the wording could improve ^
/// // An internally refcounted struct for demonstration purposes.
Quoted 63 lines
Quoted 63 lines
rust/kernel/owned.rs +62
-0+/// // +/// // # Invariants +/// // +/// // - `refcount` is always non-zero for a valid object. +/// // - `refcount` is >1 if there are more than 1 Rust reference to it. +/// // +/// struct Foo { +/// refcount: Cell<usize>, +/// } +/// +/// impl Foo { +/// fn new() -> Result<Owned<Self>, AllocError> { +/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is +/// // not actually a C-allocated object. +/// let result = KBox::new( +/// Foo { +/// refcount: Cell::new(1), +/// }, +/// flags::GFP_KERNEL, +/// )?; +/// let result = NonNull::new(KBox::into_raw(result)) +/// .expect("Raw pointer to newly allocation KBox is null, this should never happen."); +/// // SAFETY: We just allocated the `Self`, thus it is valid and there cannot be any other +/// // Rust references. Calling `into_raw()` makes us responsible for ownership and +/// // we won't use the raw pointer anymore, thus we can transfer ownership to the `Owned`. +/// 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) +/// }
Quoted 8 lines
rust/kernel/owned.rs fn drop(&mut self) { · line 243
Quoted 3 lines
rust/kernel/owned.rs +3
-0+/// } +/// } +/// We wouldn’t need this implementation if we added a “refcount()” member to this trait. This lets you abstract away this logic for all implementors, which has the massive upside of making sure we hardcode (and thus enforce) the refcount == 1 check.
This exist to allow reference counting schemes that are different from the general implementation. See [1] for an example.
Quoted 15 lines
rust/kernel/owned.rs fn drop(&mut self) { · line 289
Quoted 12 lines
rust/kernel/owned.rs +10
-0+/// // SAFETY: This implementation of `release()` is safe for any valid `Self`. +/// unsafe 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().expect("Failed to allocate a Foo. This shouldn't happen"); All these “expects()” and custom error strings would go away if you place this behind a fictional function that returns Result.
I'll do that.
Quoted 52 lines
rust/kernel/owned.rs fn drop(&mut self) { · line 300
Quoted 12 lines
rust/kernel/owned.rs +11
-0+/// let mut foo = ARef::from(foo); +/// { +/// let bar = foo.clone(); +/// assert!(Owned::try_from(bar).is_err()); +/// } +/// assert!(Owned::try_from(foo).is_ok()); +/// ``` +pub trait OwnableRefCounted :RefCounted +Ownable +Sized { +/// Checks if the [`ARef`] is unique and convert it to an [`Owned`] it that is that case. +/// Otherwise it returns again an [`ARef`] to the same underlying object. +fn try_from_shared (this:ARef <Self >) ->Result <Owned <Self >,ARef <Self >>;Again, this method can go way if we add a method to expose the refcount.
Quoted 37 lines
rust/kernel/owned.rs +17
-0+ +/// Converts the [`Owned`] into an [`ARef`]. +fn into_shared (this:Owned <Self >) ->ARef <Self > { +// SAFETY: Safe by the requirements on implementing the trait. +unsafe {ARef ::from_raw (Owned ::into_raw (this)) } + } +} + +impl <T :OwnableRefCounted >TryFrom <ARef <T >>for Owned <T > { +type Error =ARef <T >; +/// Tries to convert the [`ARef`] to an [`Owned`] by calling +/// [`try_from_shared()`](OwnableRefCounted::try_from_shared). In case the [`ARef`] is not +/// unique, it returns again an [`ARef`] to the same underlying object. +fn try_from (b:ARef <T >) ->Result <Owned <T >,Self ::Error > { +T ::try_from_shared (b) + } +}rust/kernel/sync/aref.rs +4
-1@@ -30,7 +30,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`](crate::types::OwnableRefCounted) allows to convert between unique and +/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and +/// [`ARef<Self>`](crate::types::Owned)). /// /// # Safety /// @@ -180,6 +183,12 @@ fn from(b: &T) -> Self { } }
Quoted 8 lines
rust/kernel/sync/aref.rs fn from(b: &T) -> Self { · line 191
Quoted 6 lines
rust/kernel/sync/aref.rs +6
-0+impl <T :crate ::types::OwnableRefCounted >From <crate ::types::Owned <T >>for ARef <T > { +fn from (b:crate ::types::Owned <T >) ->Self { +T ::into_shared (b) + } +} +Not sure why we’re using fully-qualified names here if we can import them, but your call.
I'll import them.
Best regards,
Andreas Hindborg