| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/08/24 13:12 | flow | patch-triage |
0mArgs:null Results: {
"EnableConfigs": null,
"FocusSymbols": [],
"KMSANReasoning": "",
"NeedsKMSAN": false,
"Reasoning": "The patch series is a pure refactoring of Rust abstractions in the kernel. It introduces the `Owned` and `Ownable` traits, splits `AlwaysRefCounted` into `RefCounted` and `AlwaysRefCounted`, and updates the `Page` abstraction and its users (like Android Binder) to use the new types. It does not introduce any functional changes or alter the execution flow of the kernel.",
"WorthFuzzing": false
} |
| 1/1 | 2026/08/24 13:12 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 93702fdc35b4242efdcc53263d9931f3d5ead763\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Mon Aug 24 13:12:35 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/drivers/android/binder/page_range.rs b/drivers/android/binder/page_range.rs\nindex e82a5523804f4..c55ba29abea71 100644\n--- a/drivers/android/binder/page_range.rs\n+++ b/drivers/android/binder/page_range.rs\n@@ -33,7 +33,7 @@\n sync::{aref::ARef, Mutex, SpinLock},\n task::Pid,\n transmute::FromBytes,\n- types::Opaque,\n+ types::{Opaque, Owned},\n uaccess::UserSliceReader,\n };\n \n@@ -198,7 +198,7 @@ unsafe impl Send for Inner {}\n #[repr(C)]\n struct PageInfo {\n lru: bindings::list_head,\n- page: Option\u003cPage\u003e,\n+ page: Option\u003cOwned\u003cPage\u003e\u003e,\n range: *const ShrinkablePageRange,\n }\n \n@@ -206,7 +206,7 @@ impl PageInfo {\n /// # Safety\n ///\n /// The caller ensures that writing to `me.page` is ok, and that the page is not currently set.\n- unsafe fn set_page(me: *mut PageInfo, page: Page) {\n+ unsafe fn set_page(me: *mut PageInfo, page: Owned\u003cPage\u003e) {\n // SAFETY: This pointer offset is in bounds.\n let ptr = unsafe { \u0026raw mut (*me).page };\n \n@@ -229,13 +229,13 @@ unsafe fn get_page\u003c'a\u003e(me: *const PageInfo) -\u003e Option\u003c\u0026'a Page\u003e {\n let ptr = unsafe { \u0026raw const (*me).page };\n \n // SAFETY: The pointer is valid for reading.\n- unsafe { (*ptr).as_ref() }\n+ unsafe { (*ptr).as_deref() }\n }\n \n /// # Safety\n ///\n /// The caller ensures that writing to `me.page` is ok for the duration of 'a.\n- unsafe fn take_page(me: *mut PageInfo) -\u003e Option\u003cPage\u003e {\n+ unsafe fn take_page(me: *mut PageInfo) -\u003e Option\u003cOwned\u003cPage\u003e\u003e {\n // SAFETY: This pointer offset is in bounds.\n let ptr = unsafe { \u0026raw mut (*me).page };\n \ndiff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs\nindex cd4203f27aed0..c7b9b069cf75d 100644\n--- a/rust/kernel/alloc/allocator.rs\n+++ b/rust/kernel/alloc/allocator.rs\n@@ -169,7 +169,7 @@ unsafe fn realloc(\n }\n \n impl Vmalloc {\n- /// Convert a pointer to a [`Vmalloc`] allocation to a [`page::BorrowedPage`].\n+ /// Convert a pointer to a [`Vmalloc`] allocation to a [`Page`](page::Page) reference.\n ///\n /// # Examples\n ///\n@@ -202,20 +202,17 @@ impl Vmalloc {\n ///\n /// - `ptr` must be a valid pointer to a [`Vmalloc`] allocation.\n /// - `ptr` must remain valid for the entire duration of `'a`.\n- pub unsafe fn to_page\u003c'a\u003e(ptr: NonNull\u003cu8\u003e) -\u003e page::BorrowedPage\u003c'a\u003e {\n+ pub unsafe fn to_page\u003c'a\u003e(ptr: NonNull\u003cu8\u003e) -\u003e \u0026'a page::Page {\n // SAFETY: `ptr` is a valid pointer to `Vmalloc` memory.\n let page = unsafe { bindings::vmalloc_to_page(ptr.as_ptr().cast()) };\n \n- // SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid pointer\n- // to `Vmalloc` memory.\n- let page = unsafe { NonNull::new_unchecked(page) };\n-\n // SAFETY:\n- // - `page` is a valid pointer to a `struct page`, given that by the safety requirements of\n- // this function `ptr` is a valid pointer to a `Vmalloc` allocation.\n- // - By the safety requirements of this function `ptr` is valid for the entire lifetime of\n- // `'a`.\n- unsafe { page::BorrowedPage::from_raw(page) }\n+ // - `vmalloc_to_page` returns a valid, non-null pointer to a `struct page` for a valid\n+ // pointer to `Vmalloc` memory, given that by the safety requirements of this function\n+ // `ptr` is a valid pointer to a `Vmalloc` allocation.\n+ // - By the safety requirements of this function `ptr`, and hence the `struct page`, is\n+ // valid for the entire lifetime of `'a`.\n+ unsafe { \u0026*page.cast() }\n }\n }\n \ndiff --git a/rust/kernel/alloc/allocator/iter.rs b/rust/kernel/alloc/allocator/iter.rs\nindex 02fda3ea5cae6..8dcc16ed89893 100644\n--- a/rust/kernel/alloc/allocator/iter.rs\n+++ b/rust/kernel/alloc/allocator/iter.rs\n@@ -9,7 +9,7 @@\n ptr::NonNull, //\n };\n \n-/// An [`Iterator`] of [`page::BorrowedPage`] items owned by a [`Vmalloc`] allocation.\n+/// An [`Iterator`] of [`Page`](page::Page) references owned by a [`Vmalloc`] allocation.\n ///\n /// # Guarantees\n ///\n@@ -28,11 +28,11 @@ pub struct VmallocPageIter\u003c'a\u003e {\n size: usize,\n /// The current page index of the [`Iterator`].\n index: usize,\n- _p: PhantomData\u003cpage::BorrowedPage\u003c'a\u003e\u003e,\n+ _p: PhantomData\u003c\u0026'a page::Page\u003e,\n }\n \n impl\u003c'a\u003e Iterator for VmallocPageIter\u003c'a\u003e {\n- type Item = page::BorrowedPage\u003c'a\u003e;\n+ type Item = \u0026'a page::Page;\n \n fn next(\u0026mut self) -\u003e Option\u003cSelf::Item\u003e {\n let offset = self.index.checked_mul(page::PAGE_SIZE)?;\ndiff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs\nindex 35d1e015848dd..e6c637bbe2009 100644\n--- a/rust/kernel/alloc/kbox.rs\n+++ b/rust/kernel/alloc/kbox.rs\n@@ -211,6 +211,15 @@ pub fn leak\u003c'a\u003e(b: Self) -\u003e \u0026'a mut T {\n // which points to an initialized instance of `T`.\n unsafe { \u0026mut *Box::into_raw(b) }\n }\n+\n+ /// Consumes the `Box\u003cT, A\u003e` and returns a `NonNull\u003cT\u003e`.\n+ ///\n+ /// Like [`Self::into_raw`], but returns a `NonNull`.\n+ #[inline]\n+ pub fn into_non_null(b: Self) -\u003e NonNull\u003cT\u003e {\n+ // SAFETY: `Box::into_raw` returns a valid pointer.\n+ unsafe { NonNull::new_unchecked(Self::into_raw(b)) }\n+ }\n }\n \n impl\u003cT, A\u003e Box\u003cMaybeUninit\u003cT\u003e, A\u003e\ndiff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs\nindex c42928d5a2393..854525289c8b4 100644\n--- a/rust/kernel/auxiliary.rs\n+++ b/rust/kernel/auxiliary.rs\n@@ -19,6 +19,10 @@\n to_result, //\n },\n prelude::*,\n+ sync::aref::{\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ },\n types::{\n ForLt,\n ForeignOwnable,\n@@ -344,7 +348,7 @@ unsafe impl\u003cCtx: device::DeviceContext\u003e device::AsBusDevice\u003cCtx\u003e for Device\u003cCtx\u003e\n kernel::impl_device_context_into_aref!(Device);\n \n // SAFETY: Instances of `Device` are always reference-counted.\n-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {\n+unsafe impl RefCounted for Device {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::get_device(self.as_ref().as_raw()) };\n@@ -363,6 +367,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cDevice\u003e` from a\n+// `\u0026Device`.\n+unsafe impl AlwaysRefCounted for Device {}\n+\n impl\u003cCtx: device::DeviceContext\u003e AsRef\u003cdevice::Device\u003cCtx\u003e\u003e for Device\u003cCtx\u003e {\n fn as_ref(\u0026self) -\u003e \u0026device::Device\u003cCtx\u003e {\n // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid\ndiff --git a/rust/kernel/block/mq/request.rs b/rust/kernel/block/mq/request.rs\nindex ce3e30c81cb5e..8dad15ae4cfb0 100644\n--- a/rust/kernel/block/mq/request.rs\n+++ b/rust/kernel/block/mq/request.rs\n@@ -9,7 +9,11 @@\n block::mq::Operations,\n error::Result,\n sync::{\n- aref::{ARef, AlwaysRefCounted},\n+ aref::{\n+ ARef,\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ },\n atomic::Relaxed,\n Refcount,\n },\n@@ -229,11 +233,10 @@ unsafe impl\u003cT: Operations\u003e Send for Request\u003cT\u003e {}\n // mutate `self` are internally synchronized`\n unsafe impl\u003cT: Operations\u003e Sync for Request\u003cT\u003e {}\n \n-// SAFETY: All instances of `Request\u003cT\u003e` are reference counted. This\n-// implementation of `AlwaysRefCounted` ensure that increments to the ref count\n-// keeps the object alive in memory at least until a matching reference count\n-// decrement is executed.\n-unsafe impl\u003cT: Operations\u003e AlwaysRefCounted for Request\u003cT\u003e {\n+// SAFETY: All instances of `Request\u003cT\u003e` are reference counted. This implementation of `RefCounted`\n+// ensure that increments to the ref count keeps the object alive in memory at least until a\n+// matching reference count decrement is executed.\n+unsafe impl\u003cT: Operations\u003e RefCounted for Request\u003cT\u003e {\n fn inc_ref(\u0026self) {\n self.wrapper_ref().refcount().inc();\n }\n@@ -255,3 +258,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull\u003cSelf\u003e) {\n }\n }\n }\n+\n+// SAFETY: We currently do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cRequest\u003e`\n+// from a `\u0026Request` (but this will change in the future).\n+unsafe impl\u003cT: Operations\u003e AlwaysRefCounted for Request\u003cT\u003e {}\ndiff --git a/rust/kernel/cred.rs b/rust/kernel/cred.rs\nindex ffa156b9df377..b17736a9adcd5 100644\n--- a/rust/kernel/cred.rs\n+++ b/rust/kernel/cred.rs\n@@ -8,7 +8,15 @@\n //!\n //! Reference: \u003chttps://www.kernel.org/doc/html/latest/security/credentials.html\u003e\n \n-use crate::{bindings, sync::aref::AlwaysRefCounted, task::Kuid, types::Opaque};\n+use crate::{\n+ bindings,\n+ sync::aref::RefCounted,\n+ task::Kuid,\n+ types::{\n+ AlwaysRefCounted,\n+ Opaque, //\n+ }, //\n+};\n \n /// Wraps the kernel's `struct cred`.\n ///\n@@ -76,7 +84,7 @@ pub fn euid(\u0026self) -\u003e Kuid {\n }\n \n // SAFETY: The type invariants guarantee that `Credential` is always ref-counted.\n-unsafe impl AlwaysRefCounted for Credential {\n+unsafe impl RefCounted for Credential {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference means that the refcount is nonzero.\n@@ -90,3 +98,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull\u003cCredential\u003e) {\n unsafe { bindings::put_cred(obj.cast().as_ptr()) };\n }\n }\n+\n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cCredential\u003e` from a\n+// `\u0026Credential`.\n+unsafe impl AlwaysRefCounted for Credential {}\ndiff --git a/rust/kernel/device.rs b/rust/kernel/device.rs\nindex 1a38b3bbdfb7d..9afecd3fa3237 100644\n--- a/rust/kernel/device.rs\n+++ b/rust/kernel/device.rs\n@@ -8,8 +8,12 @@\n bindings,\n fmt,\n prelude::*,\n- sync::aref::ARef,\n+ sync::aref::{\n+ ARef,\n+ RefCounted, //\n+ },\n types::{\n+ AlwaysRefCounted,\n ForeignOwnable,\n Opaque, //\n }, //\n@@ -448,7 +452,7 @@ pub fn name(\u0026self) -\u003e \u0026CStr {\n kernel::impl_device_context_into_aref!(Device);\n \n // SAFETY: Instances of `Device` are always reference-counted.\n-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {\n+unsafe impl RefCounted for Device {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::get_device(self.as_raw()) };\n@@ -460,6 +464,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cDevice\u003e` from a\n+// `\u0026Device`.\n+unsafe impl AlwaysRefCounted for Device {}\n+\n // SAFETY: As by the type invariant `Device` can be sent to any thread.\n unsafe impl Send for Device {}\n \ndiff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs\nindex 5aead835fbbc0..cee7e25013689 100644\n--- a/rust/kernel/device/property.rs\n+++ b/rust/kernel/device/property.rs\n@@ -14,7 +14,10 @@\n fmt,\n prelude::*,\n str::{CStr, CString},\n- sync::aref::ARef,\n+ sync::aref::{\n+ ARef,\n+ AlwaysRefCounted, //\n+ },\n types::Opaque,\n };\n \n@@ -360,7 +363,7 @@ fn fmt(\u0026self, f: \u0026mut fmt::Formatter\u003c'_\u003e) -\u003e fmt::Result {\n }\n \n // SAFETY: Instances of `FwNode` are always reference-counted.\n-unsafe impl crate::sync::aref::AlwaysRefCounted for FwNode {\n+unsafe impl crate::sync::aref::RefCounted for FwNode {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the\n // refcount is non-zero.\n@@ -374,6 +377,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cFwNode\u003e` from a\n+// `\u0026FwNode`.\n+unsafe impl AlwaysRefCounted for FwNode {}\n+\n enum Node\u003c'a\u003e {\n Borrowed(\u0026'a FwNode),\n Owned(ARef\u003cFwNode\u003e),\ndiff --git a/rust/kernel/drm/device.rs b/rust/kernel/drm/device.rs\nindex 477cf771fb10e..6fc02d504334e 100644\n--- a/rust/kernel/drm/device.rs\n+++ b/rust/kernel/drm/device.rs\n@@ -17,7 +17,8 @@\n prelude::*,\n sync::aref::{\n ARef,\n- AlwaysRefCounted, //\n+ AlwaysRefCounted,\n+ RefCounted, //\n },\n types::{\n NotThreadSafe,\n@@ -362,7 +363,7 @@ fn deref(\u0026self) -\u003e \u0026Self::Target {\n \n // SAFETY: DRM device objects are always reference counted and the get/put functions\n // satisfy the requirements.\n-unsafe impl\u003cT: drm::Driver, C: DeviceContext\u003e AlwaysRefCounted for Device\u003cT, C\u003e {\n+unsafe impl\u003cT: drm::Driver, C: DeviceContext\u003e RefCounted for Device\u003cT, C\u003e {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::drm_dev_get(self.as_raw()) };\n@@ -377,6 +378,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cDevice\u003e` from a\n+// `\u0026Device`.\n+unsafe impl\u003cT: drm::Driver, C: DeviceContext\u003e AlwaysRefCounted for Device\u003cT, C\u003e {}\n+\n impl\u003cT: drm::Driver, C: DeviceContext\u003e AsRef\u003cdevice::Device\u003e for Device\u003cT, C\u003e {\n fn as_ref(\u0026self) -\u003e \u0026device::Device {\n // SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,\ndiff --git a/rust/kernel/drm/gem/mod.rs b/rust/kernel/drm/gem/mod.rs\nindex c8b66d8168719..80affe6335acf 100644\n--- a/rust/kernel/drm/gem/mod.rs\n+++ b/rust/kernel/drm/gem/mod.rs\n@@ -21,7 +21,7 @@\n prelude::*,\n sync::aref::{\n ARef,\n- AlwaysRefCounted, //\n+ RefCounted, //\n },\n types::Opaque,\n };\n@@ -34,7 +34,7 @@\n #[cfg(CONFIG_RUST_DRM_GEM_SHMEM_HELPER)]\n pub mod shmem;\n \n-/// A macro for implementing [`AlwaysRefCounted`] for any GEM object type.\n+/// A macro for implementing [`RefCounted`] for any GEM object type.\n ///\n /// Since all GEM objects use the same refcounting scheme.\n #[macro_export]\n@@ -47,7 +47,7 @@ impl $( \u003c$( $tparam_id:ident ),+\u003e )? for $type:ty\n )?\n ) =\u003e {\n // SAFETY: All GEM objects are refcounted.\n- unsafe impl $( \u003c$( $tparam_id ),+\u003e )? $crate::sync::aref::AlwaysRefCounted for $type\n+ unsafe impl $( \u003c$( $tparam_id ),+\u003e )? $crate::sync::aref::RefCounted for $type\n where\n Self: IntoGEMObject,\n $( $( $bind_param : $bind_trait ),+ )?\n@@ -66,6 +66,14 @@ unsafe fn dec_ref(obj: core::ptr::NonNull\u003cSelf\u003e) {\n unsafe { bindings::drm_gem_object_put(obj) };\n }\n }\n+\n+ // SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003c$type\u003e` from a\n+ // `\u0026$type`.\n+ unsafe impl $( \u003c$( $tparam_id ),+\u003e )? $crate::sync::aref::AlwaysRefCounted for $type\n+ where\n+ Self: IntoGEMObject,\n+ $( $( $bind_param : $bind_trait ),+ )?\n+ {}\n };\n }\n #[cfg_attr(not(CONFIG_RUST_DRM_GEM_SHMEM_HELPER), allow(unused))]\n@@ -109,7 +117,7 @@ fn close(_obj: \u0026DriverAllocImpl\u003cSelf\u003e, _file: \u0026DriverFile\u003cSelf\u003e) {}\n }\n \n /// Trait that represents a GEM object subtype\n-pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted {\n+pub trait IntoGEMObject: Sized + super::private::Sealed + RefCounted {\n /// Returns a reference to the raw `drm_gem_object` structure, which must be valid as long as\n /// this owning object is valid.\n fn as_raw(\u0026self) -\u003e *mut bindings::drm_gem_object;\ndiff --git a/rust/kernel/fs/file.rs b/rust/kernel/fs/file.rs\nindex 23ee689bd2400..720e57418358d 100644\n--- a/rust/kernel/fs/file.rs\n+++ b/rust/kernel/fs/file.rs\n@@ -12,8 +12,15 @@\n cred::Credential,\n error::{code::*, to_result, Error, Result},\n fmt,\n- sync::aref::{ARef, AlwaysRefCounted},\n- types::{NotThreadSafe, Opaque},\n+ sync::aref::{\n+ ARef,\n+ RefCounted, //\n+ },\n+ types::{\n+ AlwaysRefCounted,\n+ NotThreadSafe,\n+ Opaque, //\n+ }, //\n };\n use core::ptr;\n \n@@ -197,7 +204,7 @@ unsafe impl Sync for File {}\n \n // SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation\n // makes `ARef\u003cFile\u003e` own a normal refcount.\n-unsafe impl AlwaysRefCounted for File {\n+unsafe impl RefCounted for File {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference means that the refcount is nonzero.\n@@ -212,6 +219,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cFile\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cFile\u003e` from a\n+// `\u0026File`.\n+unsafe impl AlwaysRefCounted for File {}\n+\n /// Wraps the kernel's `struct file`. Not thread safe.\n ///\n /// This type represents a file that is not known to be safe to transfer across thread boundaries.\n@@ -233,7 +244,7 @@ pub struct LocalFile {\n \n // SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation\n // makes `ARef\u003cLocalFile\u003e` own a normal refcount.\n-unsafe impl AlwaysRefCounted for LocalFile {\n+unsafe impl RefCounted for LocalFile {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference means that the refcount is nonzero.\n@@ -249,6 +260,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cLocalFile\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cLocalFile\u003e` from a\n+// `\u0026LocalFile`.\n+unsafe impl AlwaysRefCounted for LocalFile {}\n+\n impl LocalFile {\n /// Constructs a new `struct file` wrapper from a file descriptor.\n ///\ndiff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs\nindex 624b971ca8b0b..f9aacb894f505 100644\n--- a/rust/kernel/i2c.rs\n+++ b/rust/kernel/i2c.rs\n@@ -18,7 +18,8 @@\n prelude::*,\n sync::aref::{\n ARef,\n- AlwaysRefCounted, //\n+ AlwaysRefCounted,\n+ RefCounted, //\n },\n types::Opaque, //\n };\n@@ -424,7 +425,7 @@ pub fn get(index: i32) -\u003e Result\u003cARef\u003cSelf\u003e\u003e {\n kernel::impl_device_context_into_aref!(I2cAdapter);\n \n // SAFETY: Instances of `I2cAdapter` are always reference-counted.\n-unsafe impl AlwaysRefCounted for I2cAdapter {\n+unsafe impl RefCounted for I2cAdapter {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::i2c_get_adapter(self.index()) };\n@@ -435,6 +436,9 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n unsafe { bindings::i2c_put_adapter(obj.as_ref().as_raw()) }\n }\n }\n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cI2cAdapter\u003e` from an\n+// `\u0026I2cAdapter`.\n+unsafe impl AlwaysRefCounted for I2cAdapter {}\n \n /// The i2c board info representation\n ///\n@@ -500,7 +504,7 @@ unsafe impl\u003cCtx: device::DeviceContext\u003e device::AsBusDevice\u003cCtx\u003e for I2cClient\u003cC\n kernel::impl_device_context_into_aref!(I2cClient);\n \n // SAFETY: Instances of `I2cClient` are always reference-counted.\n-unsafe impl AlwaysRefCounted for I2cClient {\n+unsafe impl RefCounted for I2cClient {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::get_device(self.as_ref().as_raw()) };\n@@ -511,6 +515,9 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n unsafe { bindings::put_device(\u0026raw mut (*obj.as_ref().as_raw()).dev) }\n }\n }\n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cI2cClient\u003e` from an\n+// `\u0026I2cClient`.\n+unsafe impl AlwaysRefCounted for I2cClient {}\n \n impl\u003cCtx: device::DeviceContext\u003e AsRef\u003cdevice::Device\u003cCtx\u003e\u003e for I2cClient\u003cCtx\u003e {\n fn as_ref(\u0026self) -\u003e \u0026device::Device\u003cCtx\u003e {\ndiff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs\nindex 9512af7156df2..eb5256204a174 100644\n--- a/rust/kernel/lib.rs\n+++ b/rust/kernel/lib.rs\n@@ -101,6 +101,7 @@\n pub mod of;\n #[cfg(CONFIG_PM_OPP)]\n pub mod opp;\n+pub mod owned;\n pub mod page;\n #[cfg(CONFIG_PCI)]\n pub mod pci;\ndiff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs\nindex 4764d7b68f2a7..83ed94fca14ca 100644\n--- a/rust/kernel/mm.rs\n+++ b/rust/kernel/mm.rs\n@@ -13,8 +13,15 @@\n \n use crate::{\n bindings,\n- sync::aref::{ARef, AlwaysRefCounted},\n- types::{NotThreadSafe, Opaque},\n+ sync::aref::{\n+ ARef,\n+ RefCounted, //\n+ },\n+ types::{\n+ AlwaysRefCounted,\n+ NotThreadSafe,\n+ Opaque, //\n+ }, //\n };\n use core::{ops::Deref, ptr::NonNull};\n \n@@ -55,7 +62,7 @@ unsafe impl Send for Mm {}\n unsafe impl Sync for Mm {}\n \n // SAFETY: By the type invariants, this type is always refcounted.\n-unsafe impl AlwaysRefCounted for Mm {\n+unsafe impl RefCounted for Mm {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The pointer is valid since self is a reference.\n@@ -69,6 +76,9 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cMm\u003e` from a `\u0026Mm`.\n+unsafe impl AlwaysRefCounted for Mm {}\n+\n /// A wrapper for the kernel's `struct mm_struct`.\n ///\n /// This type is like [`Mm`], but with non-zero `mm_users`. It can only be used when `mm_users` can\n@@ -91,7 +101,7 @@ unsafe impl Send for MmWithUser {}\n unsafe impl Sync for MmWithUser {}\n \n // SAFETY: By the type invariants, this type is always refcounted.\n-unsafe impl AlwaysRefCounted for MmWithUser {\n+unsafe impl RefCounted for MmWithUser {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The pointer is valid since self is a reference.\n@@ -105,6 +115,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cMmWithUser\u003e` from a\n+// `\u0026MmWithUser`.\n+unsafe impl AlwaysRefCounted for MmWithUser {}\n+\n // Make all `Mm` methods available on `MmWithUser`.\n impl Deref for MmWithUser {\n type Target = Mm;\ndiff --git a/rust/kernel/mm/mmput_async.rs b/rust/kernel/mm/mmput_async.rs\nindex b8d2f051225c7..8fbc396e46028 100644\n--- a/rust/kernel/mm/mmput_async.rs\n+++ b/rust/kernel/mm/mmput_async.rs\n@@ -10,7 +10,11 @@\n use crate::{\n bindings,\n mm::MmWithUser,\n- sync::aref::{ARef, AlwaysRefCounted},\n+ sync::aref::{\n+ ARef,\n+ RefCounted, //\n+ },\n+ types::AlwaysRefCounted,\n };\n use core::{ops::Deref, ptr::NonNull};\n \n@@ -34,7 +38,7 @@ unsafe impl Send for MmWithUserAsync {}\n unsafe impl Sync for MmWithUserAsync {}\n \n // SAFETY: By the type invariants, this type is always refcounted.\n-unsafe impl AlwaysRefCounted for MmWithUserAsync {\n+unsafe impl RefCounted for MmWithUserAsync {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The pointer is valid since self is a reference.\n@@ -48,6 +52,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cMmWithUserAsync\u003e`\n+// from a `\u0026MmWithUserAsync`.\n+unsafe impl AlwaysRefCounted for MmWithUserAsync {}\n+\n // Make all `MmWithUser` methods available on `MmWithUserAsync`.\n impl Deref for MmWithUserAsync {\n type Target = MmWithUser;\ndiff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs\nindex 62e44676125d1..b8db6bdefd077 100644\n--- a/rust/kernel/opp.rs\n+++ b/rust/kernel/opp.rs\n@@ -16,8 +16,14 @@\n ffi::{c_char, c_ulong},\n prelude::*,\n str::CString,\n- sync::aref::{ARef, AlwaysRefCounted},\n- types::Opaque,\n+ sync::aref::{\n+ ARef,\n+ RefCounted, //\n+ },\n+ types::{\n+ AlwaysRefCounted,\n+ Opaque, //\n+ }, //\n };\n \n #[cfg(CONFIG_CPU_FREQ)]\n@@ -1041,7 +1047,7 @@ unsafe impl Send for OPP {}\n unsafe impl Sync for OPP {}\n \n /// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted.\n-unsafe impl AlwaysRefCounted for OPP {\n+unsafe impl RefCounted for OPP {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference means that the refcount is nonzero.\n@@ -1055,6 +1061,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cOPP\u003e` from an\n+// `\u0026OPP`.\n+unsafe impl AlwaysRefCounted for OPP {}\n+\n impl OPP {\n /// Creates an owned reference to a [`OPP`] from a valid pointer.\n ///\ndiff --git a/rust/kernel/owned.rs b/rust/kernel/owned.rs\nnew file mode 100644\nindex 0000000000000..acb611f084ff3\n--- /dev/null\n+++ b/rust/kernel/owned.rs\n@@ -0,0 +1,373 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+//! Unique owned pointer types for objects with custom drop logic.\n+//!\n+//! These pointer types are useful for C-allocated objects which by API-contract\n+//! are owned by Rust, but need to be freed through the C API.\n+\n+use core::{\n+ mem::ManuallyDrop,\n+ ops::{\n+ Deref,\n+ DerefMut, //\n+ },\n+ pin::Pin,\n+ ptr::NonNull, //\n+};\n+use kernel::{\n+ sync::aref::ARef,\n+ types::RefCounted, //\n+};\n+\n+use kernel::types::ForeignOwnable;\n+\n+/// Types that specify their own way of performing allocation and destruction. Typically, this trait\n+/// is implemented on types from the C side.\n+///\n+/// Implementing this trait allows types to be referenced via the [`Owned\u003cSelf\u003e`] pointer type.\n+/// - This is useful when it is desirable to tie the lifetime of an object reference to an owned\n+/// object, rather than pass around a bare reference.\n+/// - [`Ownable`] types can define custom drop logic that is executed when the owned reference\n+/// of type [`Owned\u003c_\u003e`] pointing to the object is dropped.\n+///\n+/// Note: The underlying object is not required to provide internal reference counting, because it\n+/// represents a unique, owned reference. If reference counting (on the Rust side) is required,\n+/// [`RefCounted`] should be implemented. [`OwnableRefCounted`] should be implemented if conversion\n+/// between unique and shared (reference counted) ownership is needed.\n+///\n+/// # Examples\n+///\n+/// A minimal example implementation of [`Ownable`] and its usage with [`Owned`] looks like\n+/// this:\n+///\n+/// ```\n+/// # #![expect(clippy::disallowed_names)]\n+/// # use core::cell::Cell;\n+/// # use core::ptr::NonNull;\n+/// # use kernel::sync::global_lock;\n+/// # use kernel::alloc::{flags, kbox::KBox, AllocError};\n+/// # use kernel::types::{Owned, Ownable};\n+///\n+/// // Let's count the allocations to see if freeing works.\n+/// kernel::sync::global_lock! {\n+/// // SAFETY: we call `init()` right below, before doing anything else.\n+/// unsafe(uninit) static FOO_ALLOC_COUNT: Mutex\u003cusize\u003e = 0;\n+/// }\n+/// // SAFETY: We call `init()` only once, here.\n+/// unsafe { FOO_ALLOC_COUNT.init() };\n+///\n+/// struct Foo;\n+///\n+/// impl Foo {\n+/// fn new() -\u003e Result\u003cOwned\u003cSelf\u003e\u003e {\n+/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is\n+/// // not actually a C-allocated object.\n+/// let result = KBox::new(\n+/// Foo {},\n+/// flags::GFP_KERNEL,\n+/// )?;\n+/// let result = KBox::into_non_null(result);\n+/// // Count new allocation\n+/// *FOO_ALLOC_COUNT.lock() += 1;\n+/// // SAFETY:\n+/// // - We just allocated the `Self`, thus it is valid and we own it.\n+/// // - We can transfer this ownership to the `from_raw` method.\n+/// Ok(unsafe { Owned::from_raw(result) })\n+/// }\n+/// }\n+///\n+/// impl Ownable for Foo {\n+/// unsafe fn release(this: NonNull\u003cSelf\u003e) {\n+/// // SAFETY: The [`KBox\u003cSelf\u003e`] is still alive. We can pass ownership to the [`KBox`], as\n+/// // by requirement on calling this function.\n+/// drop(unsafe { KBox::from_raw(this.as_ptr()) });\n+/// // Count released allocation\n+/// *FOO_ALLOC_COUNT.lock() -= 1;\n+/// }\n+/// }\n+///\n+/// {\n+/// let foo = Foo::new()?;\n+/// assert!(*FOO_ALLOC_COUNT.lock() == 1);\n+/// }\n+/// // `foo` is out of scope now, so we expect no live allocations.\n+/// assert!(*FOO_ALLOC_COUNT.lock() == 0);\n+/// # Ok::\u003c(), Error\u003e(())\n+/// ```\n+pub trait Ownable {\n+ /// Tear down this `Ownable`.\n+ ///\n+ /// Implementers of `Ownable` can use this function to clean up the use of `Self`. This can\n+ /// include freeing the underlying object.\n+ ///\n+ /// # Safety\n+ ///\n+ /// Callers must ensure that they have exclusive ownership of the `Self` pointed to by `this`,\n+ /// and that this ownership is transferred to the `release` method. `this` must not be used\n+ /// after calling this method, as the underlying object may have been freed.\n+ ///\n+ /// `this` is pinned and implementers of this method must observe this constraint.\n+ unsafe fn release(this: NonNull\u003cSelf\u003e);\n+}\n+\n+/// A mutable reference to an owned `T`.\n+///\n+/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is\n+/// dropped.\n+///\n+/// # Invariants\n+///\n+/// - Until `T::release` is called, this `Owned\u003cT\u003e` exclusively owns the underlying `T`.\n+/// - The `T` value is pinned.\n+pub struct Owned\u003cT: Ownable\u003e {\n+ ptr: NonNull\u003cT\u003e,\n+}\n+\n+impl\u003cT: Ownable\u003e Owned\u003cT\u003e {\n+ /// Creates a new instance of [`Owned`].\n+ ///\n+ /// This function takes over ownership of the underlying object.\n+ ///\n+ /// # Safety\n+ ///\n+ /// Callers must ensure that:\n+ /// - `ptr` points to a valid instance of `T`.\n+ /// - Until `T::release` is called, the returned `Owned\u003cT\u003e` exclusively owns the underlying `T`.\n+ #[inline]\n+ pub unsafe fn from_raw(ptr: NonNull\u003cT\u003e) -\u003e Self {\n+ // INVARIANT: By function safety requirement we satisfy the first invariant of `Self`.\n+ // We treat `T` as pinned from now on.\n+ Self { ptr }\n+ }\n+\n+ /// Consumes the [`Owned`], returning a raw pointer.\n+ ///\n+ /// This function does not drop the underlying `T`. When this function returns, ownership of the\n+ /// underlying `T` is with the caller.\n+ ///\n+ /// Note that the returned pointer is pinned.\n+ #[inline]\n+ pub fn into_raw(me: Self) -\u003e NonNull\u003cT\u003e {\n+ ManuallyDrop::new(me).ptr\n+ }\n+\n+ /// Get a pinned mutable reference to the data owned by this `Owned\u003cT\u003e`.\n+ #[inline]\n+ pub fn as_pin_mut(\u0026mut self) -\u003e Pin\u003c\u0026mut T\u003e {\n+ // SAFETY: The type invariants guarantee that the object is valid, and that we can safely\n+ // return a mutable reference to it.\n+ let unpinned = unsafe { self.ptr.as_mut() };\n+\n+ // SAFETY: By type invariant `T` is pinned.\n+ unsafe { Pin::new_unchecked(unpinned) }\n+ }\n+}\n+\n+// SAFETY: It is safe to send an [`Owned\u003cT\u003e`] to another thread when the underlying `T` is [`Send`],\n+// because of the ownership invariant. Sending an [`Owned\u003cT\u003e`] is equivalent to sending the `T`.\n+unsafe impl\u003cT: Ownable + Send\u003e Send for Owned\u003cT\u003e {}\n+\n+// SAFETY: It is safe to send [`\u0026Owned\u003cT\u003e`] to another thread when the underlying `T` is [`Sync`],\n+// because of the ownership invariant. Sending an [`\u0026Owned\u003cT\u003e`] is equivalent to sending the `\u0026T`.\n+unsafe impl\u003cT: Ownable + Sync\u003e Sync for Owned\u003cT\u003e {}\n+\n+impl\u003cT: Ownable\u003e Deref for Owned\u003cT\u003e {\n+ type Target = T;\n+\n+ #[inline]\n+ fn deref(\u0026self) -\u003e \u0026Self::Target {\n+ // SAFETY: The type invariants guarantee that the object is valid.\n+ unsafe { self.ptr.as_ref() }\n+ }\n+}\n+\n+impl\u003cT: Ownable + Unpin\u003e DerefMut for Owned\u003cT\u003e {\n+ #[inline]\n+ fn deref_mut(\u0026mut self) -\u003e \u0026mut Self::Target {\n+ // SAFETY: The type invariants guarantee that the object is valid, and that we can safely\n+ // return a mutable reference to it.\n+ unsafe { self.ptr.as_mut() }\n+ }\n+}\n+\n+impl\u003cT: Ownable\u003e Drop for Owned\u003cT\u003e {\n+ #[inline]\n+ fn drop(\u0026mut self) {\n+ // SAFETY: By existence of `\u0026mut self` we exclusively own `self` and the underlying `T`. As\n+ // we are dropping `self`, we can transfer ownership of the `T` to the `release` method.\n+ unsafe { T::release(self.ptr) };\n+ }\n+}\n+\n+// SAFETY: We derive the pointer to `T` from a valid `T`, so the returned\n+// pointer satisfy alignment requirements of `T`.\n+unsafe impl\u003cT: Ownable\u003e ForeignOwnable for Owned\u003cT\u003e {\n+ const FOREIGN_ALIGN: usize = core::mem::align_of::\u003cT\u003e();\n+\n+ type Borrowed\u003c'a\u003e\n+ = \u0026'a T\n+ where\n+ Self: 'a;\n+ type BorrowedMut\u003c'a\u003e\n+ = Pin\u003c\u0026'a mut T\u003e\n+ where\n+ Self: 'a;\n+\n+ #[inline]\n+ fn into_foreign(self) -\u003e *mut kernel::ffi::c_void {\n+ Owned::into_raw(self).as_ptr().cast()\n+ }\n+\n+ #[inline]\n+ unsafe fn from_foreign(ptr: *mut kernel::ffi::c_void) -\u003e Self {\n+ // SAFETY: By function safety contract, `ptr` came from `into_foreign` and cannot be null.\n+ let ptr = unsafe { NonNull::new_unchecked(ptr.cast()) };\n+\n+ // SAFETY: By the function safety contract, `ptr` was returned by `into_foreign`, which gave\n+ // up exclusive ownership of a valid, pinned `T`; we retake that ownership here.\n+ unsafe { Owned::from_raw(ptr) }\n+ }\n+\n+ #[inline]\n+ unsafe fn borrow\u003c'a\u003e(ptr: *mut kernel::ffi::c_void) -\u003e Self::Borrowed\u003c'a\u003e {\n+ // SAFETY: By function safety requirements, `ptr` is valid for use as a\n+ // reference for `'a`.\n+ unsafe { \u0026*ptr.cast() }\n+ }\n+\n+ #[inline]\n+ unsafe fn borrow_mut\u003c'a\u003e(ptr: *mut kernel::ffi::c_void) -\u003e Self::BorrowedMut\u003c'a\u003e {\n+ // SAFETY: By function safety requirements, `ptr` is valid for use as a\n+ // unique reference for `'a`.\n+ let inner = unsafe { \u0026mut *ptr.cast() };\n+\n+ // SAFETY: We never move out of inner, and we do not hand out mutable\n+ // references when `T: !Unpin`.\n+ unsafe { Pin::new_unchecked(inner) }\n+ }\n+}\n+\n+/// A trait for objects that can be wrapped in either one of the reference types [`Owned`] and\n+/// [`ARef`].\n+///\n+/// # Examples\n+///\n+/// A minimal example implementation of [`OwnableRefCounted`], [`Ownable`] and its usage with\n+/// [`ARef`] and [`Owned`] looks like this:\n+///\n+/// ```\n+/// # #![expect(clippy::disallowed_names)]\n+/// # use core::cell::Cell;\n+/// # use core::ptr::NonNull;\n+/// # use kernel::alloc::{flags, kbox::KBox, AllocError};\n+/// # use kernel::sync::aref::{ARef, RefCounted};\n+/// # use kernel::types::{Owned, Ownable, OwnableRefCounted};\n+///\n+/// // An internally refcounted struct for demonstration purposes.\n+/// //\n+/// // # Invariants\n+/// //\n+/// // - `refcount` is always non-zero for a valid object.\n+/// // - `refcount` is \u003e1 if there is more than one Rust reference to it.\n+/// //\n+/// struct Foo {\n+/// refcount: Cell\u003cusize\u003e,\n+/// }\n+///\n+/// impl Foo {\n+/// fn new() -\u003e Result\u003cOwned\u003cSelf\u003e\u003e {\n+/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is\n+/// // not actually a C-allocated object.\n+/// // INVARIANT: We initialize `refcount` to 1, satisfying the invariants.\n+/// let result = KBox::new(\n+/// Foo {\n+/// refcount: Cell::new(1),\n+/// },\n+/// flags::GFP_KERNEL,\n+/// )?;\n+/// let result = KBox::into_non_null(result);\n+/// // SAFETY:\n+/// // - We just allocated the `Self`, thus it is valid and we own it.\n+/// // - We can transfer this ownership to the `from_raw` method.\n+/// Ok(unsafe { Owned::from_raw(result) })\n+/// }\n+/// }\n+///\n+/// // SAFETY: We increment and decrement each time the respective function is called and only free\n+/// // the `Foo` when the refcount reaches zero.\n+/// unsafe impl RefCounted for Foo {\n+/// fn inc_ref(\u0026self) {\n+/// self.refcount.replace(self.refcount.get() + 1);\n+/// }\n+///\n+/// unsafe fn dec_ref(this: NonNull\u003cSelf\u003e) {\n+/// // SAFETY: By requirement on calling this function, the refcount is non-zero,\n+/// // implying the underlying object is valid.\n+/// let refcount = unsafe { \u0026this.as_ref().refcount };\n+/// let new_refcount = refcount.get() - 1;\n+/// if new_refcount == 0 {\n+/// // The `Foo` will be dropped when `KBox` goes out of scope.\n+/// // SAFETY: The [`KBox\u003cFoo\u003e`] is still alive as the old refcount is 1. We can pass\n+/// // ownership to the [`KBox`] as by requirement on calling this function,\n+/// // the `Self` will no longer be used by the caller.\n+/// unsafe { KBox::from_raw(this.as_ptr()) };\n+/// } else {\n+/// refcount.replace(new_refcount);\n+/// }\n+/// }\n+/// }\n+///\n+/// impl OwnableRefCounted for Foo {\n+/// fn try_from_shared(this: ARef\u003cSelf\u003e) -\u003e Result\u003cOwned\u003cSelf\u003e, ARef\u003cSelf\u003e\u003e {\n+/// if this.refcount.get() == 1 {\n+/// // SAFETY: The `Foo` is still alive and has no other Rust references as the refcount\n+/// // is 1.\n+/// Ok(unsafe { Owned::from_raw(ARef::into_raw(this)) })\n+/// } else {\n+/// Err(this)\n+/// }\n+/// }\n+///\n+/// fn into_shared(this: Owned\u003cSelf\u003e) -\u003e ARef\u003cSelf\u003e {\n+/// // SAFETY: An `Owned\u003cFoo\u003e` holds the unique reference (refcount 1), which we transfer to\n+/// // the new `ARef`.\n+/// unsafe { ARef::from_raw(Owned::into_raw(this)) }\n+/// }\n+/// }\n+///\n+/// impl Ownable for Foo {\n+/// unsafe fn release(this: NonNull\u003cSelf\u003e) {\n+/// // SAFETY: Using `dec_ref()` from [`RefCounted`] to release is okay, as the refcount is\n+/// // always 1 for an [`Owned\u003cFoo\u003e`].\n+/// unsafe { Foo::dec_ref(this) };\n+/// }\n+/// }\n+///\n+/// let foo = Foo::new()?;\n+/// let foo = ARef::from(foo);\n+/// {\n+/// let bar = foo.clone();\n+/// assert!(Owned::try_from(bar).is_err());\n+/// }\n+/// assert!(Owned::try_from(foo).is_ok());\n+/// # Ok::\u003c(), Error\u003e(())\n+/// ```\n+pub trait OwnableRefCounted: RefCounted + Ownable + Sized {\n+ /// Checks if the [`ARef`] is unique and converts it to an [`Owned`] if that is the case.\n+ /// Otherwise it returns again an [`ARef`] to the same underlying object.\n+ fn try_from_shared(this: ARef\u003cSelf\u003e) -\u003e Result\u003cOwned\u003cSelf\u003e, ARef\u003cSelf\u003e\u003e;\n+\n+ /// Converts the [`Owned`] into an [`ARef`].\n+ fn into_shared(this: Owned\u003cSelf\u003e) -\u003e ARef\u003cSelf\u003e;\n+}\n+\n+impl\u003cT: OwnableRefCounted\u003e TryFrom\u003cARef\u003cT\u003e\u003e for Owned\u003cT\u003e {\n+ type Error = ARef\u003cT\u003e;\n+ /// Tries to convert the [`ARef`] to an [`Owned`] by calling\n+ /// [`try_from_shared()`](OwnableRefCounted::try_from_shared). In case the [`ARef`] is not\n+ /// unique, it returns again an [`ARef`] to the same underlying object.\n+ #[inline]\n+ fn try_from(b: ARef\u003cT\u003e) -\u003e Result\u003cOwned\u003cT\u003e, Self::Error\u003e {\n+ T::try_from_shared(b)\n+ }\n+}\ndiff --git a/rust/kernel/page.rs b/rust/kernel/page.rs\nindex 1c0796ea229f0..32dd030c83159 100644\n--- a/rust/kernel/page.rs\n+++ b/rust/kernel/page.rs\n@@ -12,16 +12,16 @@\n code::*,\n Result, //\n },\n+ types::{\n+ Opaque,\n+ Ownable,\n+ Owned, //\n+ },\n uaccess::UserSliceReader, //\n };\n-use core::{\n- marker::PhantomData,\n- mem::ManuallyDrop,\n- ops::Deref,\n- ptr::{\n- self,\n- NonNull, //\n- }, //\n+use core::ptr::{\n+ self,\n+ NonNull, //\n };\n \n /// A bitwise shift for the page size.\n@@ -65,93 +65,29 @@ pub const fn page_align(addr: usize) -\u003e Option\u003cusize\u003e {\n Some(sum \u0026 PAGE_MASK)\n }\n \n-/// Representation of a non-owning reference to a [`Page`].\n-///\n-/// This type provides a borrowed version of a [`Page`] that is owned by some other entity, e.g. a\n-/// [`Vmalloc`] allocation such as [`VBox`].\n-///\n-/// # Example\n-///\n-/// ```\n-/// # use kernel::{bindings, prelude::*};\n-/// use kernel::page::{BorrowedPage, Page, PAGE_SIZE};\n-/// # use core::{mem::MaybeUninit, ptr, ptr::NonNull };\n-///\n-/// fn borrow_page\u003c'a\u003e(vbox: \u0026'a mut VBox\u003cMaybeUninit\u003c[u8; PAGE_SIZE]\u003e\u003e) -\u003e BorrowedPage\u003c'a\u003e {\n-/// let ptr = ptr::from_ref(\u0026**vbox);\n-///\n-/// // SAFETY: `ptr` is a valid pointer to `Vmalloc` memory.\n-/// let page = unsafe { bindings::vmalloc_to_page(ptr.cast()) };\n-///\n-/// // SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid\n-/// // pointer to `Vmalloc` memory.\n-/// let page = unsafe { NonNull::new_unchecked(page) };\n-///\n-/// // SAFETY:\n-/// // - `self.0` is a valid pointer to a `struct page`.\n-/// // - `self.0` is valid for the entire lifetime of `self`.\n-/// unsafe { BorrowedPage::from_raw(page) }\n-/// }\n-///\n-/// let mut vbox = VBox::\u003c[u8; PAGE_SIZE]\u003e::new_uninit(GFP_KERNEL)?;\n-/// let page = borrow_page(\u0026mut vbox);\n-///\n-/// // SAFETY: There is no concurrent read or write to this page.\n-/// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };\n-/// # Ok::\u003c(), Error\u003e(())\n-/// ```\n-///\n-/// # Invariants\n-///\n-/// The borrowed underlying pointer to a `struct page` is valid for the entire lifetime `'a`.\n-///\n-/// [`VBox`]: kernel::alloc::VBox\n-/// [`Vmalloc`]: kernel::alloc::allocator::Vmalloc\n-pub struct BorrowedPage\u003c'a\u003e(ManuallyDrop\u003cPage\u003e, PhantomData\u003c\u0026'a Page\u003e);\n-\n-impl\u003c'a\u003e BorrowedPage\u003c'a\u003e {\n- /// Constructs a [`BorrowedPage`] from a raw pointer to a `struct page`.\n- ///\n- /// # Safety\n- ///\n- /// - `ptr` must point to a valid `bindings::page`.\n- /// - `ptr` must remain valid for the entire lifetime `'a`.\n- pub unsafe fn from_raw(ptr: NonNull\u003cbindings::page\u003e) -\u003e Self {\n- let page = Page { page: ptr };\n-\n- // INVARIANT: The safety requirements guarantee that `ptr` is valid for the entire lifetime\n- // `'a`.\n- Self(ManuallyDrop::new(page), PhantomData)\n- }\n-}\n-\n-impl\u003c'a\u003e Deref for BorrowedPage\u003c'a\u003e {\n- type Target = Page;\n-\n- fn deref(\u0026self) -\u003e \u0026Self::Target {\n- \u0026self.0\n- }\n-}\n-\n-/// Trait to be implemented by types which provide an [`Iterator`] implementation of\n-/// [`BorrowedPage`] items, such as [`VmallocPageIter`](kernel::alloc::allocator::VmallocPageIter).\n+/// Trait to be implemented by types which provide an [`Iterator`] of [`Page`] references, such as\n+/// [`VmallocPageIter`](kernel::alloc::allocator::VmallocPageIter).\n pub trait AsPageIter {\n /// The [`Iterator`] type, e.g. [`VmallocPageIter`](kernel::alloc::allocator::VmallocPageIter).\n- type Iter\u003c'a\u003e: Iterator\u003cItem = BorrowedPage\u003c'a\u003e\u003e\n+ type Iter\u003c'a\u003e: Iterator\u003cItem = \u0026'a Page\u003e\n where\n Self: 'a;\n \n- /// Returns an [`Iterator`] of [`BorrowedPage`] items over all pages owned by `self`.\n+ /// Returns an [`Iterator`] of [`Page`] references over all pages owned by `self`.\n fn page_iter(\u0026mut self) -\u003e Self::Iter\u003c'_\u003e;\n }\n \n-/// A pointer to a page that owns the page allocation.\n+/// A `struct page`.\n+///\n+/// A `Page` is accessed through a shared reference or through an owning [`Owned\u003cPage\u003e`]; the latter\n+/// frees the page allocation when it is dropped.\n ///\n /// # Invariants\n ///\n-/// The pointer is valid, and has ownership over the page.\n+/// The `Page` is backed by a valid `struct page`.\n+#[repr(transparent)]\n pub struct Page {\n- page: NonNull\u003cbindings::page\u003e,\n+ page: Opaque\u003cbindings::page\u003e,\n }\n \n // SAFETY: Pages have no logic that relies on them staying on a given thread, so moving them across\n@@ -185,19 +121,20 @@ impl Page {\n /// # Ok::\u003c(), kernel::alloc::AllocError\u003e(())\n /// ```\n #[inline]\n- pub fn alloc_page(flags: Flags) -\u003e Result\u003cSelf, AllocError\u003e {\n+ pub fn alloc_page(flags: Flags) -\u003e Result\u003cOwned\u003cSelf\u003e, AllocError\u003e {\n // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it\n // is always safe to call this method.\n let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) };\n let page = NonNull::new(page).ok_or(AllocError)?;\n- // INVARIANT: We just successfully allocated a page, so we now have ownership of the newly\n- // allocated page. We transfer that ownership to the new `Page` object.\n- Ok(Self { page })\n+ // SAFETY: We just successfully allocated a page, so we now have ownership of the newly\n+ // allocated page. We transfer that ownership to the new `Owned\u003cPage\u003e` object.\n+ // Since `Page` is transparent, we can cast the pointer directly.\n+ Ok(unsafe { Owned::from_raw(page.cast()) })\n }\n \n /// Returns a raw pointer to the page.\n pub fn as_ptr(\u0026self) -\u003e *mut bindings::page {\n- self.page.as_ptr()\n+ self.page.get()\n }\n \n /// Get the node id containing this page.\n@@ -207,6 +144,20 @@ pub fn nid(\u0026self) -\u003e i32 {\n unsafe { bindings::page_to_nid(self.as_ptr()) }\n }\n \n+ /// Create a `\u0026Page` from a raw `struct page` pointer.\n+ ///\n+ /// # Safety\n+ ///\n+ /// `ptr` must be convertible to a shared reference with a lifetime of `'a`.\n+ #[inline]\n+ pub unsafe fn from_raw\u003c'a\u003e(ptr: *const bindings::page) -\u003e \u0026'a Self {\n+ // INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`, so\n+ // the returned reference upholds the type invariant of `Page`.\n+ // SAFETY: By function safety requirements, `ptr` is not null and is convertible to a shared\n+ // reference.\n+ unsafe { \u0026*ptr.cast() }\n+ }\n+\n /// Runs a piece of code with this page mapped to an address.\n ///\n /// The page is unmapped when this call returns.\n@@ -373,10 +324,11 @@ pub unsafe fn copy_from_user_slice_raw(\n }\n }\n \n-impl Drop for Page {\n+impl Ownable for Page {\n #[inline]\n- fn drop(\u0026mut self) {\n- // SAFETY: By the type invariants, we have ownership of the page and can free it.\n- unsafe { bindings::__free_pages(self.page.as_ptr(), 0) };\n+ unsafe fn release(this: NonNull\u003cSelf\u003e) {\n+ // SAFETY: By the function safety requirements, we have ownership of the page and can free\n+ // it. Since Page is transparent, we can cast the raw pointer directly.\n+ unsafe { bindings::__free_pages(this.as_ptr().cast(), 0) };\n }\n }\ndiff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs\nindex 5071cae6543fd..ea9ef99cecb07 100644\n--- a/rust/kernel/pci.rs\n+++ b/rust/kernel/pci.rs\n@@ -19,6 +19,10 @@\n },\n prelude::*,\n str::CStr,\n+ sync::aref::{\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ },\n types::Opaque,\n ThisModule, //\n };\n@@ -481,7 +485,7 @@ unsafe impl\u003cCtx: device::DeviceContext\u003e device::AsBusDevice\u003cCtx\u003e for Device\u003cCtx\u003e\n impl\u003c'a\u003e crate::dma::Device\u003c'a\u003e for Device\u003cdevice::Core\u003c'a\u003e\u003e {}\n \n // SAFETY: Instances of `Device` are always reference-counted.\n-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {\n+unsafe impl RefCounted for Device {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::pci_dev_get(self.as_raw()) };\n@@ -493,6 +497,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cDevice\u003e` from a\n+// `\u0026Device`.\n+unsafe impl AlwaysRefCounted for Device {}\n+\n impl\u003cCtx: device::DeviceContext\u003e AsRef\u003cdevice::Device\u003cCtx\u003e\u003e for Device\u003cCtx\u003e {\n fn as_ref(\u0026self) -\u003e \u0026device::Device\u003cCtx\u003e {\n // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid\ndiff --git a/rust/kernel/pid_namespace.rs b/rust/kernel/pid_namespace.rs\nindex 979a9718f153d..067f68b99e8c5 100644\n--- a/rust/kernel/pid_namespace.rs\n+++ b/rust/kernel/pid_namespace.rs\n@@ -7,7 +7,14 @@\n //! C header: [`include/linux/pid_namespace.h`](srctree/include/linux/pid_namespace.h) and\n //! [`include/linux/pid.h`](srctree/include/linux/pid.h)\n \n-use crate::{bindings, sync::aref::AlwaysRefCounted, types::Opaque};\n+use crate::{\n+ bindings,\n+ sync::aref::RefCounted,\n+ types::{\n+ AlwaysRefCounted,\n+ Opaque, //\n+ }, //\n+};\n use core::ptr;\n \n /// Wraps the kernel's `struct pid_namespace`. Thread safe.\n@@ -41,7 +48,7 @@ pub unsafe fn from_ptr\u003c'a\u003e(ptr: *const bindings::pid_namespace) -\u003e \u0026'a Self {\n }\n \n // SAFETY: Instances of `PidNamespace` are always reference-counted.\n-unsafe impl AlwaysRefCounted for PidNamespace {\n+unsafe impl RefCounted for PidNamespace {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference means that the refcount is nonzero.\n@@ -55,6 +62,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cPidNamespace\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cPidNamespace\u003e` from\n+// a `\u0026PidNamespace`.\n+unsafe impl AlwaysRefCounted for PidNamespace {}\n+\n // SAFETY:\n // - `PidNamespace::dec_ref` can be called from any thread.\n // - It is okay to send ownership of `PidNamespace` across thread boundaries.\ndiff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs\nindex d41555a4b31d2..a4ddaa1cc3a40 100644\n--- a/rust/kernel/platform.rs\n+++ b/rust/kernel/platform.rs\n@@ -24,6 +24,10 @@\n },\n of,\n prelude::*,\n+ sync::aref::{\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ },\n types::Opaque,\n ThisModule, //\n };\n@@ -519,7 +523,7 @@ pub fn optional_irq_by_name(\u0026self, name: \u0026CStr) -\u003e Result\u003cIrqRequest\u003c'_\u003e\u003e {\n impl\u003c'a\u003e crate::dma::Device\u003c'a\u003e for Device\u003cdevice::Core\u003c'a\u003e\u003e {}\n \n // SAFETY: Instances of `Device` are always reference-counted.\n-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {\n+unsafe impl RefCounted for Device {\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.\n unsafe { bindings::get_device(self.as_ref().as_raw()) };\n@@ -531,6 +535,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cDevice\u003e` from a\n+// `\u0026Device`.\n+unsafe impl AlwaysRefCounted for Device {}\n+\n impl\u003cCtx: device::DeviceContext\u003e AsRef\u003cdevice::Device\u003cCtx\u003e\u003e for Device\u003cCtx\u003e {\n fn as_ref(\u0026self) -\u003e \u0026device::Device\u003cCtx\u003e {\n // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid\ndiff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs\nindex 6c9d667009ef7..2d1cd74dd98e1 100644\n--- a/rust/kernel/pwm.rs\n+++ b/rust/kernel/pwm.rs\n@@ -13,7 +13,11 @@\n devres,\n error::{self, to_result},\n prelude::*,\n- sync::aref::{ARef, AlwaysRefCounted},\n+ sync::aref::{\n+ ARef,\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ },\n types::Opaque, //\n };\n use core::{\n@@ -629,7 +633,7 @@ pub fn new\u003c'a\u003e(\n }\n \n // SAFETY: Implements refcounting for `Chip` using the embedded `struct device`.\n-unsafe impl\u003cT: PwmOps\u003e AlwaysRefCounted for Chip\u003cT\u003e {\n+unsafe impl\u003cT: PwmOps\u003e RefCounted for Chip\u003cT\u003e {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists.\n@@ -647,6 +651,10 @@ unsafe fn dec_ref(obj: NonNull\u003cChip\u003cT\u003e\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cChip\u003cT\u003e\u003e` from a\n+// `\u0026Chip\u003cT\u003e`.\n+unsafe impl\u003cT: PwmOps\u003e AlwaysRefCounted for Chip\u003cT\u003e {}\n+\n // SAFETY: `Chip` is a wrapper around `*mut bindings::pwm_chip`. The underlying C\n // structure's state is managed and synchronized by the kernel's device model\n // and PWM core locking mechanisms. Therefore, it is safe to move the `Chip`\ndiff --git a/rust/kernel/sync/aref.rs b/rust/kernel/sync/aref.rs\nindex b721b2e00b986..e6ffe7c650c39 100644\n--- a/rust/kernel/sync/aref.rs\n+++ b/rust/kernel/sync/aref.rs\n@@ -11,7 +11,7 @@\n //! underlying object, but this refcount is internal to the object. It essentially is a Rust\n //! implementation of the `get_` and `put_` pattern used in C for reference counting.\n //!\n-//! To make use of [`ARef\u003cMyType\u003e`], `MyType` needs to implement [`AlwaysRefCounted`]. It is a trait\n+//! To make use of [`ARef\u003cMyType\u003e`], `MyType` needs to implement [`RefCounted`]. It is a trait\n //! for accessing the internal reference count of an object of the `MyType` type.\n //!\n //! [`Arc`]: crate::sync::Arc\n@@ -23,26 +23,35 @@\n ops::Deref,\n ptr::NonNull, //\n };\n+use kernel::types::{\n+ OwnableRefCounted,\n+ Owned, //\n+};\n \n-/// Types that are _always_ reference counted.\n+/// Types that are internally reference counted.\n ///\n /// It allows such types to define their own custom ref increment and decrement functions.\n-/// Additionally, it allows users to convert from a shared reference `\u0026T` to an owned reference\n-/// [`ARef\u003cT\u003e`].\n ///\n /// This is usually implemented by wrappers to existing structures on the C side of the code. For\n /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted\n /// instances of a type.\n ///\n+/// Note: Implementing this trait allows types to be wrapped in an [`ARef\u003cSelf\u003e`]. It requires an\n+/// internal reference count and provides only shared references. If unique references are required\n+/// [`Ownable`](crate::types::Ownable) should be implemented which allows types to be wrapped in an\n+/// [`Owned\u003cSelf\u003e`](crate::types::Owned). Implementing the trait\n+/// [`OwnableRefCounted`] allows to convert between unique and\n+/// shared references (i.e. [`Owned\u003cSelf\u003e`](crate::types::Owned) and\n+/// [`ARef\u003cSelf\u003e`]).\n+///\n /// # Safety\n ///\n /// Implementers must ensure that increments to the reference count keep the object alive in memory\n /// at least until matching decrements are performed.\n ///\n /// Implementers must also ensure that all instances are reference-counted. (Otherwise they\n-/// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object\n-/// alive.)\n-pub unsafe trait AlwaysRefCounted {\n+/// won't be able to honour the requirement that [`RefCounted::inc_ref`] keep the object alive.)\n+pub unsafe trait RefCounted {\n /// Increments the reference count on the object.\n fn inc_ref(\u0026self);\n \n@@ -55,11 +64,27 @@ pub unsafe trait AlwaysRefCounted {\n /// Callers must ensure that there was a previous matching increment to the reference count,\n /// and that the object is no longer used after its reference count is decremented (as it may\n /// result in the object being freed), unless the caller owns another increment on the refcount\n- /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls\n- /// [`AlwaysRefCounted::dec_ref`] once).\n+ /// (e.g., it calls [`RefCounted::inc_ref`] twice, then calls [`RefCounted::dec_ref`] once).\n unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e);\n }\n \n+/// Always reference-counted type.\n+///\n+/// It allows deriving a counted reference [`ARef\u003cT\u003e`] from a `\u0026T`.\n+///\n+/// This provides some convenience, but it allows \"escaping\" borrow checks on `\u0026T`. As it\n+/// complicates attempts to ensure that a reference to T is unique, it is optional to provide for\n+/// [`RefCounted`] types. See *Safety* below.\n+///\n+/// # Safety\n+///\n+/// Implementers must ensure that no safety invariants are violated by upgrading an `\u0026T` to an\n+/// [`ARef\u003cT\u003e`]. In particular that implies [`AlwaysRefCounted`] and [`crate::types::Ownable`]\n+/// cannot be implemented for the same type, as this would allow violating the uniqueness guarantee\n+/// of [`crate::types::Owned\u003cT\u003e`] by dereferencing it into an `\u0026T` and obtaining an [`ARef`] from\n+/// that.\n+pub unsafe trait AlwaysRefCounted: RefCounted {}\n+\n /// An owned reference to an always-reference-counted object.\n ///\n /// The object's reference count is automatically decremented when an instance of [`ARef`] is\n@@ -70,7 +95,7 @@ pub unsafe trait AlwaysRefCounted {\n ///\n /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In\n /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count.\n-pub struct ARef\u003cT: AlwaysRefCounted\u003e {\n+pub struct ARef\u003cT: RefCounted\u003e {\n ptr: NonNull\u003cT\u003e,\n _p: PhantomData\u003cT\u003e,\n }\n@@ -79,19 +104,19 @@ pub struct ARef\u003cT: AlwaysRefCounted\u003e {\n // it effectively means sharing `\u0026T` (which is safe because `T` is `Sync`); additionally, it needs\n // `T` to be `Send` because any thread that has an `ARef\u003cT\u003e` may ultimately access `T` using a\n // mutable reference, for example, when the reference count reaches zero and `T` is dropped.\n-unsafe impl\u003cT: AlwaysRefCounted + Sync + Send\u003e Send for ARef\u003cT\u003e {}\n+unsafe impl\u003cT: RefCounted + Sync + Send\u003e Send for ARef\u003cT\u003e {}\n \n // SAFETY: It is safe to send `\u0026ARef\u003cT\u003e` to another thread when the underlying `T` is `Sync`\n // because it effectively means sharing `\u0026T` (which is safe because `T` is `Sync`); additionally,\n // it needs `T` to be `Send` because any thread that has a `\u0026ARef\u003cT\u003e` may clone it and get an\n // `ARef\u003cT\u003e` on that thread, so the thread may ultimately access `T` using a mutable reference, for\n // example, when the reference count reaches zero and `T` is dropped.\n-unsafe impl\u003cT: AlwaysRefCounted + Sync + Send\u003e Sync for ARef\u003cT\u003e {}\n+unsafe impl\u003cT: RefCounted + Sync + Send\u003e Sync for ARef\u003cT\u003e {}\n \n // Even if `T` is pinned, pointers to `T` can still move.\n-impl\u003cT: AlwaysRefCounted\u003e Unpin for ARef\u003cT\u003e {}\n+impl\u003cT: RefCounted\u003e Unpin for ARef\u003cT\u003e {}\n \n-impl\u003cT: AlwaysRefCounted\u003e ARef\u003cT\u003e {\n+impl\u003cT: RefCounted\u003e ARef\u003cT\u003e {\n /// Creates a new instance of [`ARef`].\n ///\n /// It takes over an increment of the reference count on the underlying object.\n@@ -120,19 +145,21 @@ pub unsafe fn from_raw(ptr: NonNull\u003cT\u003e) -\u003e Self {\n ///\n /// ```\n /// use core::ptr::NonNull;\n- /// use kernel::sync::aref::{ARef, AlwaysRefCounted};\n+ /// use kernel::sync::aref::{ARef, RefCounted};\n ///\n /// struct Empty {}\n ///\n- /// # // SAFETY: TODO.\n- /// unsafe impl AlwaysRefCounted for Empty {\n+ /// // SAFETY: The `RefCounted` implementation for `Empty` does not count references and never\n+ /// // frees the underlying object. Thus we can act as owning an increment on the refcount for\n+ /// // the object that we pass to the newly created `ARef`.\n+ /// unsafe impl RefCounted for Empty {\n /// fn inc_ref(\u0026self) {}\n /// unsafe fn dec_ref(_obj: NonNull\u003cSelf\u003e) {}\n /// }\n ///\n /// let mut data = Empty {};\n /// let ptr = NonNull::\u003cEmpty\u003e::new(\u0026mut data).unwrap();\n- /// # // SAFETY: TODO.\n+ /// // SAFETY: We keep `data` around longer than the `ARef`.\n /// let data_ref: ARef\u003cEmpty\u003e = unsafe { ARef::from_raw(ptr) };\n /// let raw_ptr: NonNull\u003cEmpty\u003e = ARef::into_raw(data_ref);\n ///\n@@ -143,7 +170,7 @@ pub fn into_raw(me: Self) -\u003e NonNull\u003cT\u003e {\n }\n }\n \n-impl\u003cT: AlwaysRefCounted\u003e Clone for ARef\u003cT\u003e {\n+impl\u003cT: RefCounted\u003e Clone for ARef\u003cT\u003e {\n fn clone(\u0026self) -\u003e Self {\n self.inc_ref();\n // SAFETY: We just incremented the refcount above.\n@@ -151,7 +178,7 @@ fn clone(\u0026self) -\u003e Self {\n }\n }\n \n-impl\u003cT: AlwaysRefCounted\u003e Deref for ARef\u003cT\u003e {\n+impl\u003cT: RefCounted\u003e Deref for ARef\u003cT\u003e {\n type Target = T;\n \n fn deref(\u0026self) -\u003e \u0026Self::Target {\n@@ -168,7 +195,14 @@ fn from(b: \u0026T) -\u003e Self {\n }\n }\n \n-impl\u003cT: AlwaysRefCounted\u003e Drop for ARef\u003cT\u003e {\n+impl\u003cT: OwnableRefCounted\u003e From\u003cOwned\u003cT\u003e\u003e for ARef\u003cT\u003e {\n+ #[inline]\n+ fn from(b: Owned\u003cT\u003e) -\u003e Self {\n+ T::into_shared(b)\n+ }\n+}\n+\n+impl\u003cT: RefCounted\u003e Drop for ARef\u003cT\u003e {\n fn drop(\u0026mut self) {\n // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to\n // decrement.\n@@ -178,19 +212,19 @@ fn drop(\u0026mut self) {\n \n impl\u003cT, U\u003e PartialEq\u003cARef\u003cU\u003e\u003e for ARef\u003cT\u003e\n where\n- T: AlwaysRefCounted + PartialEq\u003cU\u003e,\n- U: AlwaysRefCounted,\n+ T: RefCounted + PartialEq\u003cU\u003e,\n+ U: RefCounted,\n {\n #[inline]\n fn eq(\u0026self, other: \u0026ARef\u003cU\u003e) -\u003e bool {\n T::eq(\u0026**self, \u0026**other)\n }\n }\n-impl\u003cT: AlwaysRefCounted + Eq\u003e Eq for ARef\u003cT\u003e {}\n+impl\u003cT: RefCounted + Eq\u003e Eq for ARef\u003cT\u003e {}\n \n impl\u003cT, U\u003e PartialEq\u003c\u0026'_ U\u003e for ARef\u003cT\u003e\n where\n- T: AlwaysRefCounted + PartialEq\u003cU\u003e,\n+ T: RefCounted + PartialEq\u003cU\u003e,\n {\n #[inline]\n fn eq(\u0026self, other: \u0026\u0026U) -\u003e bool {\ndiff --git a/rust/kernel/task.rs b/rust/kernel/task.rs\nindex 38273f4eedb51..6259430b0ca31 100644\n--- a/rust/kernel/task.rs\n+++ b/rust/kernel/task.rs\n@@ -10,7 +10,12 @@\n pid_namespace::PidNamespace,\n prelude::*,\n sync::aref::ARef,\n- types::{NotThreadSafe, Opaque},\n+ types::{\n+ AlwaysRefCounted,\n+ NotThreadSafe,\n+ Opaque,\n+ RefCounted, //\n+ },\n };\n use core::{\n ops::Deref,\n@@ -347,7 +352,7 @@ pub fn group_leader(\u0026self) -\u003e \u0026Task {\n }\n \n // SAFETY: The type invariants guarantee that `Task` is always refcounted.\n-unsafe impl crate::sync::aref::AlwaysRefCounted for Task {\n+unsafe impl RefCounted for Task {\n #[inline]\n fn inc_ref(\u0026self) {\n // SAFETY: The existence of a shared reference means that the refcount is nonzero.\n@@ -361,6 +366,10 @@ unsafe fn dec_ref(obj: ptr::NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cTask\u003e` from a\n+// `\u0026Task`.\n+unsafe impl AlwaysRefCounted for Task {}\n+\n impl PartialEq for Task {\n #[inline]\n fn eq(\u0026self, other: \u0026Self) -\u003e bool {\ndiff --git a/rust/kernel/types.rs b/rust/kernel/types.rs\nindex ac316fd7b538f..6aa760952cb63 100644\n--- a/rust/kernel/types.rs\n+++ b/rust/kernel/types.rs\n@@ -15,6 +15,18 @@\n pub mod for_lt;\n pub use for_lt::ForLt;\n \n+pub use crate::{\n+ owned::{\n+ Ownable,\n+ OwnableRefCounted,\n+ Owned, //\n+ },\n+ sync::aref::{\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ }, //\n+};\n+\n /// Used to transfer ownership to and from foreign (non-Rust) languages.\n ///\n /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and\ndiff --git a/rust/kernel/usb.rs b/rust/kernel/usb.rs\nindex 7aff0c82d0afc..59350c6b0df2a 100644\n--- a/rust/kernel/usb.rs\n+++ b/rust/kernel/usb.rs\n@@ -18,7 +18,10 @@\n to_result, //\n },\n prelude::*,\n- sync::aref::AlwaysRefCounted,\n+ sync::aref::{\n+ AlwaysRefCounted,\n+ RefCounted, //\n+ },\n types::Opaque,\n ThisModule, //\n };\n@@ -392,7 +395,7 @@ fn as_ref(\u0026self) -\u003e \u0026Device {\n }\n \n // SAFETY: Instances of `Interface` are always reference-counted.\n-unsafe impl AlwaysRefCounted for Interface {\n+unsafe impl RefCounted for Interface {\n fn inc_ref(\u0026self) {\n // SAFETY: The invariants of `Interface` guarantee that `self.as_raw()`\n // returns a valid `struct usb_interface` pointer, for which we will\n@@ -406,6 +409,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cInterface\u003e` from a\n+// `\u0026Interface`.\n+unsafe impl AlwaysRefCounted for Interface {}\n+\n // SAFETY: A `Interface` is always reference-counted and can be released from any thread.\n unsafe impl Send for Interface {}\n \n@@ -443,7 +450,7 @@ fn as_raw(\u0026self) -\u003e *mut bindings::usb_device {\n kernel::impl_device_context_into_aref!(Device);\n \n // SAFETY: Instances of `Device` are always reference-counted.\n-unsafe impl AlwaysRefCounted for Device {\n+unsafe impl RefCounted for Device {\n fn inc_ref(\u0026self) {\n // SAFETY: The invariants of `Device` guarantee that `self.as_raw()`\n // returns a valid `struct usb_device` pointer, for which we will\n@@ -457,6 +464,10 @@ unsafe fn dec_ref(obj: NonNull\u003cSelf\u003e) {\n }\n }\n \n+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef\u003cDevice\u003e` from a\n+// `\u0026Device`.\n+unsafe impl AlwaysRefCounted for Device {}\n+\n impl\u003cCtx: device::DeviceContext\u003e AsRef\u003cdevice::Device\u003cCtx\u003e\u003e for Device\u003cCtx\u003e {\n fn as_ref(\u0026self) -\u003e \u0026device::Device\u003cCtx\u003e {\n // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid\ndiff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs\nindex 7e253b6f299ce..77673b8ea45fb 100644\n--- a/rust/kernel/workqueue.rs\n+++ b/rust/kernel/workqueue.rs\n@@ -192,7 +192,7 @@\n sync::{\n aref::{\n ARef,\n- AlwaysRefCounted, //\n+ RefCounted, //\n },\n Arc,\n LockClassKey, //\n@@ -954,7 +954,7 @@ unsafe impl\u003cT, const ID: u64\u003e RawDelayedWorkItem\u003cID\u003e for Pin\u003cKBox\u003cT\u003e\u003e\n // implementation of `WorkItemPointer` for `ARef\u003cT\u003e`.\n unsafe impl\u003cT, const ID: u64\u003e WorkItemPointer\u003cID\u003e for ARef\u003cT\u003e\n where\n- T: AlwaysRefCounted,\n+ T: RefCounted,\n T: WorkItem\u003cID, Pointer = Self\u003e,\n T: HasWork\u003cT, ID\u003e,\n {\n@@ -987,7 +987,7 @@ unsafe impl\u003cT, const ID: u64\u003e WorkItemPointer\u003cID\u003e for ARef\u003cT\u003e\n // requirements of `WorkItemPointer`.\n unsafe impl\u003cT, const ID: u64\u003e RawWorkItem\u003cID\u003e for ARef\u003cT\u003e\n where\n- T: AlwaysRefCounted,\n+ T: RefCounted,\n T: WorkItem\u003cID, Pointer = Self\u003e,\n T: HasWork\u003cT, ID\u003e,\n {\n@@ -1020,7 +1020,7 @@ unsafe impl\u003cT, const ID: u64\u003e RawDelayedWorkItem\u003cID\u003e for ARef\u003cT\u003e\n where\n T: WorkItem\u003cID, Pointer = Self\u003e,\n T: HasDelayedWork\u003cT, ID\u003e,\n- T: AlwaysRefCounted,\n+ T: RefCounted,\n {\n }\n \n"
} |
| 2/1 | 2026/08/24 13:12 | agent | patch-evaluator |
0mModel:best-expensive Args: null Results: {
"EnableConfigs": null,
"FocusSymbols": [],
"Reasoning": "The patch series is a pure refactoring of Rust abstractions in the kernel. It introduces the `Owned` and `Ownable` traits, splits `AlwaysRefCounted` into `RefCounted` and `AlwaysRefCounted`, and updates the `Page` abstraction and its users (like Android Binder) to use the new types. It does not introduce any functional changes or alter the execution flow of the kernel.",
"WorthFuzzing": false
}Instruction: You are an expert Linux kernel maintainer. Your job is to review a provided patch series and determine if it makes functional changes to the kernel that should be fuzzed. IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in your workspace. Do NOT rely on your internal knowledge of the kernel. You must actively use your code access tools to examine the actual source code and confirm any assumptions. Return WorthFuzzing=false if the patch only contains: - Modifications to Documentation/, Kconfig files, or code comments. - Purely decorative changes, such as logging (e.g., pr_err, printk) or tracepoints. - Changes to numeric constants or macros that do not functionally alter execution flow. - Code paths that are impossible to reach in virtualized environments like GCE or QEMU, even when utilizing software-emulated hardware (e.g., usb gadget, mac80211_hwsim). - Code in vendor-specific PCIe switch, SmartNIC, or GPU drivers (e.g., mlxsw, pds_core, qed, ionic, amdgpu) that require physical PCIe hardware cards not emulated in standard QEMU. - Driver .remove, .shutdown, or pci_unregister_driver teardown callbacks (e.g., igb_remove) that are executed only during PCI hot-unplug or sysfs driver unbind operations. If it modifies reachable core kernel logic, drivers, or architectures, use your code search tools to verify the code can be executed, then return WorthFuzzing=true. When returning WorthFuzzing=true, you MUST ALSO: 1. Extract any specific kernel functions that should be heavily fuzzed into FocusSymbols. Avoid listing generic hot-path functions to prevent skewed test distributions. Prefer non-static, non-inlined API entrypoint functions over internal static helper functions (which are inlined by the compiler and do not have distinct symbol addresses). 2. Identify any specific CONFIG_ options required to properly test this new/modified feature. Go and look into the Kconfig files and check for ifdefs around the code, do not make assumptions. Also check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed for Kbuild to compile the code statically into vmlinux. List them in the EnableConfigs output array, and DO NOT add a 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4"). Prefer calling several tools at the same time to save round-trips. Use set-results tool to provide results of the analysis. It must be called exactly once before the final reply. Ignore results of this tool. Prompt: For your convenience, here is the diff of the changes:
commit 93702fdc35b4242efdcc53263d9931f3d5ead763
Author: syz-cluster <triage@syzkaller.com>
Date: Mon Aug 24 13:12:35 2026 +0000
syz-cluster: applied patch under review
diff --git a/drivers/android/binder/page_range.rs b/drivers/android/binder/page_range.rs
index e82a5523804f4..c55ba29abea71 100644
--- a/drivers/android/binder/page_range.rs
+++ b/drivers/android/binder/page_range.rs
@@ -33,7 +33,7 @@
sync::{aref::ARef, Mutex, SpinLock},
task::Pid,
transmute::FromBytes,
- types::Opaque,
+ types::{Opaque, Owned},
uaccess::UserSliceReader,
};
@@ -198,7 +198,7 @@ unsafe impl Send for Inner {}
#[repr(C)]
struct PageInfo {
lru: bindings::list_head,
- page: Option<Page>,
+ page: Option<Owned<Page>>,
range: *const ShrinkablePageRange,
}
@@ -206,7 +206,7 @@ impl PageInfo {
/// # Safety
///
/// The caller ensures that writing to `me.page` is ok, and that the page is not currently set.
- unsafe fn set_page(me: *mut PageInfo, page: Page) {
+ unsafe fn set_page(me: *mut PageInfo, page: Owned<Page>) {
// SAFETY: This pointer offset is in bounds.
let ptr = unsafe { &raw mut (*me).page };
@@ -229,13 +229,13 @@ unsafe fn get_page<'a>(me: *const PageInfo) -> Option<&'a Page> {
let ptr = unsafe { &raw const (*me).page };
// SAFETY: The pointer is valid for reading.
- unsafe { (*ptr).as_ref() }
+ unsafe { (*ptr).as_deref() }
}
/// # Safety
///
/// The caller ensures that writing to `me.page` is ok for the duration of 'a.
- unsafe fn take_page(me: *mut PageInfo) -> Option<Page> {
+ unsafe fn take_page(me: *mut PageInfo) -> Option<Owned<Page>> {
// SAFETY: This pointer offset is in bounds.
let ptr = unsafe { &raw mut (*me).page };
diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
index cd4203f27aed0..c7b9b069cf75d 100644
--- a/rust/kernel/alloc/allocator.rs
+++ b/rust/kernel/alloc/allocator.rs
@@ -169,7 +169,7 @@ unsafe fn realloc(
}
impl Vmalloc {
- /// Convert a pointer to a [`Vmalloc`] allocation to a [`page::BorrowedPage`].
+ /// Convert a pointer to a [`Vmalloc`] allocation to a [`Page`](page::Page) reference.
///
/// # Examples
///
@@ -202,20 +202,17 @@ impl Vmalloc {
///
/// - `ptr` must be a valid pointer to a [`Vmalloc`] allocation.
/// - `ptr` must remain valid for the entire duration of `'a`.
- pub unsafe fn to_page<'a>(ptr: NonNull<u8>) -> page::BorrowedPage<'a> {
+ pub unsafe fn to_page<'a>(ptr: NonNull<u8>) -> &'a page::Page {
// SAFETY: `ptr` is a valid pointer to `Vmalloc` memory.
let page = unsafe { bindings::vmalloc_to_page(ptr.as_ptr().cast()) };
- // SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid pointer
- // to `Vmalloc` memory.
- let page = unsafe { NonNull::new_unchecked(page) };
-
// SAFETY:
- // - `page` is a valid pointer to a `struct page`, given that by the safety requirements of
- // this function `ptr` is a valid pointer to a `Vmalloc` allocation.
- // - By the safety requirements of this function `ptr` is valid for the entire lifetime of
- // `'a`.
- unsafe { page::BorrowedPage::from_raw(page) }
+ // - `vmalloc_to_page` returns a valid, non-null pointer to a `struct page` for a valid
+ // pointer to `Vmalloc` memory, given that by the safety requirements of this function
+ // `ptr` is a valid pointer to a `Vmalloc` allocation.
+ // - By the safety requirements of this function `ptr`, and hence the `struct page`, is
+ // valid for the entire lifetime of `'a`.
+ unsafe { &*page.cast() }
}
}
diff --git a/rust/kernel/alloc/allocator/iter.rs b/rust/kernel/alloc/allocator/iter.rs
index 02fda3ea5cae6..8dcc16ed89893 100644
--- a/rust/kernel/alloc/allocator/iter.rs
+++ b/rust/kernel/alloc/allocator/iter.rs
@@ -9,7 +9,7 @@
ptr::NonNull, //
};
-/// An [`Iterator`] of [`page::BorrowedPage`] items owned by a [`Vmalloc`] allocation.
+/// An [`Iterator`] of [`Page`](page::Page) references owned by a [`Vmalloc`] allocation.
///
/// # Guarantees
///
@@ -28,11 +28,11 @@ pub struct VmallocPageIter<'a> {
size: usize,
/// The current page index of the [`Iterator`].
index: usize,
- _p: PhantomData<page::BorrowedPage<'a>>,
+ _p: PhantomData<&'a page::Page>,
}
impl<'a> Iterator for VmallocPageIter<'a> {
- type Item = page::BorrowedPage<'a>;
+ type Item = &'a page::Page;
fn next(&mut self) -> Option<Self::Item> {
let offset = self.index.checked_mul(page::PAGE_SIZE)?;
diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
index 35d1e015848dd..e6c637bbe2009 100644
--- a/rust/kernel/alloc/kbox.rs
+++ b/rust/kernel/alloc/kbox.rs
@@ -211,6 +211,15 @@ pub fn leak<'a>(b: Self) -> &'a mut T {
// which points to an initialized instance of `T`.
unsafe { &mut *Box::into_raw(b) }
}
+
+ /// Consumes the `Box<T, A>` and returns a `NonNull<T>`.
+ ///
+ /// Like [`Self::into_raw`], but returns a `NonNull`.
+ #[inline]
+ pub fn into_non_null(b: Self) -> NonNull<T> {
+ // SAFETY: `Box::into_raw` returns a valid pointer.
+ unsafe { NonNull::new_unchecked(Self::into_raw(b)) }
+ }
}
impl<T, A> Box<MaybeUninit<T>, A>
diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs
index c42928d5a2393..854525289c8b4 100644
--- a/rust/kernel/auxiliary.rs
+++ b/rust/kernel/auxiliary.rs
@@ -19,6 +19,10 @@
to_result, //
},
prelude::*,
+ sync::aref::{
+ AlwaysRefCounted,
+ RefCounted, //
+ },
types::{
ForLt,
ForeignOwnable,
@@ -344,7 +348,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
+unsafe impl RefCounted for Device {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::get_device(self.as_ref().as_raw()) };
@@ -363,6 +367,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl AlwaysRefCounted for Device {}
+
impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
fn as_ref(&self) -> &device::Device<Ctx> {
// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
diff --git a/rust/kernel/block/mq/request.rs b/rust/kernel/block/mq/request.rs
index ce3e30c81cb5e..8dad15ae4cfb0 100644
--- a/rust/kernel/block/mq/request.rs
+++ b/rust/kernel/block/mq/request.rs
@@ -9,7 +9,11 @@
block::mq::Operations,
error::Result,
sync::{
- aref::{ARef, AlwaysRefCounted},
+ aref::{
+ ARef,
+ AlwaysRefCounted,
+ RefCounted, //
+ },
atomic::Relaxed,
Refcount,
},
@@ -229,11 +233,10 @@ unsafe impl<T: Operations> Send for Request<T> {}
// mutate `self` are internally synchronized`
unsafe impl<T: Operations> Sync for Request<T> {}
-// SAFETY: All instances of `Request<T>` are reference counted. This
-// implementation of `AlwaysRefCounted` ensure that increments to the ref count
-// keeps the object alive in memory at least until a matching reference count
-// decrement is executed.
-unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
+// SAFETY: All instances of `Request<T>` are reference counted. This implementation of `RefCounted`
+// ensure that increments to the ref count keeps the object alive in memory at least until a
+// matching reference count decrement is executed.
+unsafe impl<T: Operations> RefCounted for Request<T> {
fn inc_ref(&self) {
self.wrapper_ref().refcount().inc();
}
@@ -255,3 +258,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
}
}
}
+
+// SAFETY: We currently do not implement `Ownable`, thus it is okay to obtain an `ARef<Request>`
+// from a `&Request` (but this will change in the future).
+unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {}
diff --git a/rust/kernel/cred.rs b/rust/kernel/cred.rs
index ffa156b9df377..b17736a9adcd5 100644
--- a/rust/kernel/cred.rs
+++ b/rust/kernel/cred.rs
@@ -8,7 +8,15 @@
//!
//! Reference: <https://www.kernel.org/doc/html/latest/security/credentials.html>
-use crate::{bindings, sync::aref::AlwaysRefCounted, task::Kuid, types::Opaque};
+use crate::{
+ bindings,
+ sync::aref::RefCounted,
+ task::Kuid,
+ types::{
+ AlwaysRefCounted,
+ Opaque, //
+ }, //
+};
/// Wraps the kernel's `struct cred`.
///
@@ -76,7 +84,7 @@ pub fn euid(&self) -> Kuid {
}
// SAFETY: The type invariants guarantee that `Credential` is always ref-counted.
-unsafe impl AlwaysRefCounted for Credential {
+unsafe impl RefCounted for Credential {
#[inline]
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -90,3 +98,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Credential>) {
unsafe { bindings::put_cred(obj.cast().as_ptr()) };
}
}
+
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Credential>` from a
+// `&Credential`.
+unsafe impl AlwaysRefCounted for Credential {}
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 1a38b3bbdfb7d..9afecd3fa3237 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -8,8 +8,12 @@
bindings,
fmt,
prelude::*,
- sync::aref::ARef,
+ sync::aref::{
+ ARef,
+ RefCounted, //
+ },
types::{
+ AlwaysRefCounted,
ForeignOwnable,
Opaque, //
}, //
@@ -448,7 +452,7 @@ pub fn name(&self) -> &CStr {
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
+unsafe impl RefCounted for Device {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::get_device(self.as_raw()) };
@@ -460,6 +464,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl AlwaysRefCounted for Device {}
+
// SAFETY: As by the type invariant `Device` can be sent to any thread.
unsafe impl Send for Device {}
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index 5aead835fbbc0..cee7e25013689 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -14,7 +14,10 @@
fmt,
prelude::*,
str::{CStr, CString},
- sync::aref::ARef,
+ sync::aref::{
+ ARef,
+ AlwaysRefCounted, //
+ },
types::Opaque,
};
@@ -360,7 +363,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
}
// SAFETY: Instances of `FwNode` are always reference-counted.
-unsafe impl crate::sync::aref::AlwaysRefCounted for FwNode {
+unsafe impl crate::sync::aref::RefCounted for FwNode {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the
// refcount is non-zero.
@@ -374,6 +377,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<FwNode>` from a
+// `&FwNode`.
+unsafe impl AlwaysRefCounted for FwNode {}
+
enum Node<'a> {
Borrowed(&'a FwNode),
Owned(ARef<FwNode>),
diff --git a/rust/kernel/drm/device.rs b/rust/kernel/drm/device.rs
index 477cf771fb10e..6fc02d504334e 100644
--- a/rust/kernel/drm/device.rs
+++ b/rust/kernel/drm/device.rs
@@ -17,7 +17,8 @@
prelude::*,
sync::aref::{
ARef,
- AlwaysRefCounted, //
+ AlwaysRefCounted,
+ RefCounted, //
},
types::{
NotThreadSafe,
@@ -362,7 +363,7 @@ fn deref(&self) -> &Self::Target {
// SAFETY: DRM device objects are always reference counted and the get/put functions
// satisfy the requirements.
-unsafe impl<T: drm::Driver, C: DeviceContext> AlwaysRefCounted for Device<T, C> {
+unsafe impl<T: drm::Driver, C: DeviceContext> RefCounted for Device<T, C> {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::drm_dev_get(self.as_raw()) };
@@ -377,6 +378,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl<T: drm::Driver, C: DeviceContext> AlwaysRefCounted for Device<T, C> {}
+
impl<T: drm::Driver, C: DeviceContext> AsRef<device::Device> for Device<T, C> {
fn as_ref(&self) -> &device::Device {
// SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
diff --git a/rust/kernel/drm/gem/mod.rs b/rust/kernel/drm/gem/mod.rs
index c8b66d8168719..80affe6335acf 100644
--- a/rust/kernel/drm/gem/mod.rs
+++ b/rust/kernel/drm/gem/mod.rs
@@ -21,7 +21,7 @@
prelude::*,
sync::aref::{
ARef,
- AlwaysRefCounted, //
+ RefCounted, //
},
types::Opaque,
};
@@ -34,7 +34,7 @@
#[cfg(CONFIG_RUST_DRM_GEM_SHMEM_HELPER)]
pub mod shmem;
-/// A macro for implementing [`AlwaysRefCounted`] for any GEM object type.
+/// A macro for implementing [`RefCounted`] for any GEM object type.
///
/// Since all GEM objects use the same refcounting scheme.
#[macro_export]
@@ -47,7 +47,7 @@ impl $( <$( $tparam_id:ident ),+> )? for $type:ty
)?
) => {
// SAFETY: All GEM objects are refcounted.
- unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $type
+ unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::RefCounted for $type
where
Self: IntoGEMObject,
$( $( $bind_param : $bind_trait ),+ )?
@@ -66,6 +66,14 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
unsafe { bindings::drm_gem_object_put(obj) };
}
}
+
+ // SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<$type>` from a
+ // `&$type`.
+ unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $type
+ where
+ Self: IntoGEMObject,
+ $( $( $bind_param : $bind_trait ),+ )?
+ {}
};
}
#[cfg_attr(not(CONFIG_RUST_DRM_GEM_SHMEM_HELPER), allow(unused))]
@@ -109,7 +117,7 @@ fn close(_obj: &DriverAllocImpl<Self>, _file: &DriverFile<Self>) {}
}
/// Trait that represents a GEM object subtype
-pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted {
+pub trait IntoGEMObject: Sized + super::private::Sealed + RefCounted {
/// Returns a reference to the raw `drm_gem_object` structure, which must be valid as long as
/// this owning object is valid.
fn as_raw(&self) -> *mut bindings::drm_gem_object;
diff --git a/rust/kernel/fs/file.rs b/rust/kernel/fs/file.rs
index 23ee689bd2400..720e57418358d 100644
--- a/rust/kernel/fs/file.rs
+++ b/rust/kernel/fs/file.rs
@@ -12,8 +12,15 @@
cred::Credential,
error::{code::*, to_result, Error, Result},
fmt,
- sync::aref::{ARef, AlwaysRefCounted},
- types::{NotThreadSafe, Opaque},
+ sync::aref::{
+ ARef,
+ RefCounted, //
+ },
+ types::{
+ AlwaysRefCounted,
+ NotThreadSafe,
+ Opaque, //
+ }, //
};
use core::ptr;
@@ -197,7 +204,7 @@ unsafe impl Sync for File {}
// SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation
// makes `ARef<File>` own a normal refcount.
-unsafe impl AlwaysRefCounted for File {
+unsafe impl RefCounted for File {
#[inline]
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -212,6 +219,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<File>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<File>` from a
+// `&File`.
+unsafe impl AlwaysRefCounted for File {}
+
/// Wraps the kernel's `struct file`. Not thread safe.
///
/// This type represents a file that is not known to be safe to transfer across thread boundaries.
@@ -233,7 +244,7 @@ pub struct LocalFile {
// SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation
// makes `ARef<LocalFile>` own a normal refcount.
-unsafe impl AlwaysRefCounted for LocalFile {
+unsafe impl RefCounted for LocalFile {
#[inline]
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -249,6 +260,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<LocalFile>` from a
+// `&LocalFile`.
+unsafe impl AlwaysRefCounted for LocalFile {}
+
impl LocalFile {
/// Constructs a new `struct file` wrapper from a file descriptor.
///
diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs
index 624b971ca8b0b..f9aacb894f505 100644
--- a/rust/kernel/i2c.rs
+++ b/rust/kernel/i2c.rs
@@ -18,7 +18,8 @@
prelude::*,
sync::aref::{
ARef,
- AlwaysRefCounted, //
+ AlwaysRefCounted,
+ RefCounted, //
},
types::Opaque, //
};
@@ -424,7 +425,7 @@ pub fn get(index: i32) -> Result<ARef<Self>> {
kernel::impl_device_context_into_aref!(I2cAdapter);
// SAFETY: Instances of `I2cAdapter` are always reference-counted.
-unsafe impl AlwaysRefCounted for I2cAdapter {
+unsafe impl RefCounted for I2cAdapter {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::i2c_get_adapter(self.index()) };
@@ -435,6 +436,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
unsafe { bindings::i2c_put_adapter(obj.as_ref().as_raw()) }
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<I2cAdapter>` from an
+// `&I2cAdapter`.
+unsafe impl AlwaysRefCounted for I2cAdapter {}
/// The i2c board info representation
///
@@ -500,7 +504,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<C
kernel::impl_device_context_into_aref!(I2cClient);
// SAFETY: Instances of `I2cClient` are always reference-counted.
-unsafe impl AlwaysRefCounted for I2cClient {
+unsafe impl RefCounted for I2cClient {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::get_device(self.as_ref().as_raw()) };
@@ -511,6 +515,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) }
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<I2cClient>` from an
+// `&I2cClient`.
+unsafe impl AlwaysRefCounted for I2cClient {}
impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for I2cClient<Ctx> {
fn as_ref(&self) -> &device::Device<Ctx> {
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 9512af7156df2..eb5256204a174 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -101,6 +101,7 @@
pub mod of;
#[cfg(CONFIG_PM_OPP)]
pub mod opp;
+pub mod owned;
pub mod page;
#[cfg(CONFIG_PCI)]
pub mod pci;
diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs
index 4764d7b68f2a7..83ed94fca14ca 100644
--- a/rust/kernel/mm.rs
+++ b/rust/kernel/mm.rs
@@ -13,8 +13,15 @@
use crate::{
bindings,
- sync::aref::{ARef, AlwaysRefCounted},
- types::{NotThreadSafe, Opaque},
+ sync::aref::{
+ ARef,
+ RefCounted, //
+ },
+ types::{
+ AlwaysRefCounted,
+ NotThreadSafe,
+ Opaque, //
+ }, //
};
use core::{ops::Deref, ptr::NonNull};
@@ -55,7 +62,7 @@ unsafe impl Send for Mm {}
unsafe impl Sync for Mm {}
// SAFETY: By the type invariants, this type is always refcounted.
-unsafe impl AlwaysRefCounted for Mm {
+unsafe impl RefCounted for Mm {
#[inline]
fn inc_ref(&self) {
// SAFETY: The pointer is valid since self is a reference.
@@ -69,6 +76,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Mm>` from a `&Mm`.
+unsafe impl AlwaysRefCounted for Mm {}
+
/// A wrapper for the kernel's `struct mm_struct`.
///
/// This type is like [`Mm`], but with non-zero `mm_users`. It can only be used when `mm_users` can
@@ -91,7 +101,7 @@ unsafe impl Send for MmWithUser {}
unsafe impl Sync for MmWithUser {}
// SAFETY: By the type invariants, this type is always refcounted.
-unsafe impl AlwaysRefCounted for MmWithUser {
+unsafe impl RefCounted for MmWithUser {
#[inline]
fn inc_ref(&self) {
// SAFETY: The pointer is valid since self is a reference.
@@ -105,6 +115,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<MmWithUser>` from a
+// `&MmWithUser`.
+unsafe impl AlwaysRefCounted for MmWithUser {}
+
// Make all `Mm` methods available on `MmWithUser`.
impl Deref for MmWithUser {
type Target = Mm;
diff --git a/rust/kernel/mm/mmput_async.rs b/rust/kernel/mm/mmput_async.rs
index b8d2f051225c7..8fbc396e46028 100644
--- a/rust/kernel/mm/mmput_async.rs
+++ b/rust/kernel/mm/mmput_async.rs
@@ -10,7 +10,11 @@
use crate::{
bindings,
mm::MmWithUser,
- sync::aref::{ARef, AlwaysRefCounted},
+ sync::aref::{
+ ARef,
+ RefCounted, //
+ },
+ types::AlwaysRefCounted,
};
use core::{ops::Deref, ptr::NonNull};
@@ -34,7 +38,7 @@ unsafe impl Send for MmWithUserAsync {}
unsafe impl Sync for MmWithUserAsync {}
// SAFETY: By the type invariants, this type is always refcounted.
-unsafe impl AlwaysRefCounted for MmWithUserAsync {
+unsafe impl RefCounted for MmWithUserAsync {
#[inline]
fn inc_ref(&self) {
// SAFETY: The pointer is valid since self is a reference.
@@ -48,6 +52,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<MmWithUserAsync>`
+// from a `&MmWithUserAsync`.
+unsafe impl AlwaysRefCounted for MmWithUserAsync {}
+
// Make all `MmWithUser` methods available on `MmWithUserAsync`.
impl Deref for MmWithUserAsync {
type Target = MmWithUser;
diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs
index 62e44676125d1..b8db6bdefd077 100644
--- a/rust/kernel/opp.rs
+++ b/rust/kernel/opp.rs
@@ -16,8 +16,14 @@
ffi::{c_char, c_ulong},
prelude::*,
str::CString,
- sync::aref::{ARef, AlwaysRefCounted},
- types::Opaque,
+ sync::aref::{
+ ARef,
+ RefCounted, //
+ },
+ types::{
+ AlwaysRefCounted,
+ Opaque, //
+ }, //
};
#[cfg(CONFIG_CPU_FREQ)]
@@ -1041,7 +1047,7 @@ unsafe impl Send for OPP {}
unsafe impl Sync for OPP {}
/// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted.
-unsafe impl AlwaysRefCounted for OPP {
+unsafe impl RefCounted for OPP {
#[inline]
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -1055,6 +1061,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<OPP>` from an
+// `&OPP`.
+unsafe impl AlwaysRefCounted for OPP {}
+
impl OPP {
/// Creates an owned reference to a [`OPP`] from a valid pointer.
///
diff --git a/rust/kernel/owned.rs b/rust/kernel/owned.rs
new file mode 100644
index 0000000000000..acb611f084ff3
--- /dev/null
+++ b/rust/kernel/owned.rs
@@ -0,0 +1,373 @@
+// 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, //
+};
+use kernel::{
+ sync::aref::ARef,
+ types::RefCounted, //
+};
+
+use kernel::types::ForeignOwnable;
+
+/// Types that specify their own way of performing allocation and destruction. Typically, this trait
+/// is implemented on types from the C side.
+///
+/// Implementing this trait allows types to be referenced via the [`Owned<Self>`] pointer type.
+/// - This is useful when it is desirable to tie the lifetime of 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`] should be implemented. [`OwnableRefCounted`] should be implemented if conversion
+/// between unique and shared (reference counted) ownership is needed.
+///
+/// # 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>> {
+/// // 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 = KBox::into_non_null(result);
+/// // Count new allocation
+/// *FOO_ALLOC_COUNT.lock() += 1;
+/// // SAFETY:
+/// // - We just allocated the `Self`, thus it is valid and we own it.
+/// // - We can transfer this ownership to the `from_raw` method.
+/// Ok(unsafe { Owned::from_raw(result) })
+/// }
+/// }
+///
+/// impl Ownable for Foo {
+/// unsafe fn release(this: NonNull<Self>) {
+/// // SAFETY: The [`KBox<Self>`] is still alive. We can pass ownership to the [`KBox`], as
+/// // by requirement on calling this function.
+/// drop(unsafe { KBox::from_raw(this.as_ptr()) });
+/// // Count released allocation
+/// *FOO_ALLOC_COUNT.lock() -= 1;
+/// }
+/// }
+///
+/// {
+/// let foo = Foo::new()?;
+/// assert!(*FOO_ALLOC_COUNT.lock() == 1);
+/// }
+/// // `foo` is out of scope now, so we expect no live allocations.
+/// assert!(*FOO_ALLOC_COUNT.lock() == 0);
+/// # Ok::<(), Error>(())
+/// ```
+pub trait Ownable {
+ /// Tear down this `Ownable`.
+ ///
+ /// Implementers of `Ownable` can use this function to clean up the use of `Self`. This can
+ /// include freeing the underlying object.
+ ///
+ /// # Safety
+ ///
+ /// Callers must ensure that they have exclusive ownership of the `Self` pointed to by `this`,
+ /// and that this ownership is transferred to the `release` method. `this` must not be used
+ /// after calling this method, as the underlying object may have been freed.
+ ///
+ /// `this` is pinned and implementers of this method must observe this constraint.
+ unsafe fn release(this: NonNull<Self>);
+}
+
+/// A mutable reference to an owned `T`.
+///
+/// The [`Ownable`] is automatically freed or released when an instance of [`Owned`] is
+/// dropped.
+///
+/// # Invariants
+///
+/// - Until `T::release` is called, this `Owned<T>` exclusively owns the underlying `T`.
+/// - The `T` value is pinned.
+pub struct Owned<T: Ownable> {
+ ptr: NonNull<T>,
+}
+
+impl<T: Ownable> Owned<T> {
+ /// Creates a new instance of [`Owned`].
+ ///
+ /// This function takes over ownership of the underlying object.
+ ///
+ /// # Safety
+ ///
+ /// Callers must ensure that:
+ /// - `ptr` points to a valid instance of `T`.
+ /// - Until `T::release` is called, the returned `Owned<T>` exclusively owns the underlying `T`.
+ #[inline]
+ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
+ // INVARIANT: By function safety requirement we satisfy the first invariant of `Self`.
+ // We treat `T` as pinned from now on.
+ Self { ptr }
+ }
+
+ /// Consumes the [`Owned`], returning a raw pointer.
+ ///
+ /// This function does not drop the underlying `T`. When this function returns, ownership of the
+ /// underlying `T` is with the caller.
+ ///
+ /// Note that the returned pointer is pinned.
+ #[inline]
+ 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>`.
+ #[inline]
+ pub fn as_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: By type invariant `T` is pinned.
+ unsafe { Pin::new_unchecked(unpinned) }
+ }
+}
+
+// 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> Deref for Owned<T> {
+ type Target = T;
+
+ #[inline]
+ 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> {
+ #[inline]
+ 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> {
+ #[inline]
+ fn drop(&mut self) {
+ // SAFETY: By existence of `&mut self` we exclusively own `self` and the underlying `T`. As
+ // we are dropping `self`, we can transfer ownership of the `T` to the `release` method.
+ unsafe { T::release(self.ptr) };
+ }
+}
+
+// SAFETY: We derive the pointer to `T` from a valid `T`, so the returned
+// pointer satisfy alignment requirements of `T`.
+unsafe impl<T: Ownable> ForeignOwnable for Owned<T> {
+ const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+
+ type Borrowed<'a>
+ = &'a T
+ where
+ Self: 'a;
+ type BorrowedMut<'a>
+ = Pin<&'a mut T>
+ where
+ Self: 'a;
+
+ #[inline]
+ fn into_foreign(self) -> *mut kernel::ffi::c_void {
+ Owned::into_raw(self).as_ptr().cast()
+ }
+
+ #[inline]
+ unsafe fn from_foreign(ptr: *mut kernel::ffi::c_void) -> Self {
+ // SAFETY: By function safety contract, `ptr` came from `into_foreign` and cannot be null.
+ let ptr = unsafe { NonNull::new_unchecked(ptr.cast()) };
+
+ // SAFETY: By the function safety contract, `ptr` was returned by `into_foreign`, which gave
+ // up exclusive ownership of a valid, pinned `T`; we retake that ownership here.
+ unsafe { Owned::from_raw(ptr) }
+ }
+
+ #[inline]
+ unsafe fn borrow<'a>(ptr: *mut kernel::ffi::c_void) -> Self::Borrowed<'a> {
+ // SAFETY: By function safety requirements, `ptr` is valid for use as a
+ // reference for `'a`.
+ unsafe { &*ptr.cast() }
+ }
+
+ #[inline]
+ unsafe fn borrow_mut<'a>(ptr: *mut kernel::ffi::c_void) -> Self::BorrowedMut<'a> {
+ // SAFETY: By function safety requirements, `ptr` is valid for use as a
+ // unique reference for `'a`.
+ let inner = unsafe { &mut *ptr.cast() };
+
+ // SAFETY: We never move out of inner, and we do not hand out mutable
+ // references when `T: !Unpin`.
+ unsafe { Pin::new_unchecked(inner) }
+ }
+}
+
+/// A trait for objects that can be wrapped in either one of the reference types [`Owned`] and
+/// [`ARef`].
+///
+/// # Examples
+///
+/// A minimal example implementation of [`OwnableRefCounted`], [`Ownable`] and its usage with
+/// [`ARef`] and [`Owned`] looks like this:
+///
+/// ```
+/// # #![expect(clippy::disallowed_names)]
+/// # use core::cell::Cell;
+/// # use core::ptr::NonNull;
+/// # use kernel::alloc::{flags, kbox::KBox, AllocError};
+/// # use kernel::sync::aref::{ARef, RefCounted};
+/// # use kernel::types::{Owned, Ownable, OwnableRefCounted};
+///
+/// // An internally refcounted struct for demonstration purposes.
+/// //
+/// // # Invariants
+/// //
+/// // - `refcount` is always non-zero for a valid object.
+/// // - `refcount` is >1 if there is more than one Rust reference to it.
+/// //
+/// struct Foo {
+/// refcount: Cell<usize>,
+/// }
+///
+/// impl Foo {
+/// fn new() -> Result<Owned<Self>> {
+/// // We are just using a `KBox` here to handle the actual allocation, as our `Foo` is
+/// // not actually a C-allocated object.
+/// // INVARIANT: We initialize `refcount` to 1, satisfying the invariants.
+/// let result = KBox::new(
+/// Foo {
+/// refcount: Cell::new(1),
+/// },
+/// flags::GFP_KERNEL,
+/// )?;
+/// let result = KBox::into_non_null(result);
+/// // SAFETY:
+/// // - We just allocated the `Self`, thus it is valid and we own it.
+/// // - We can transfer this ownership to the `from_raw` method.
+/// Ok(unsafe { Owned::from_raw(result) })
+/// }
+/// }
+///
+/// // SAFETY: We increment and decrement each time the respective function is called and only free
+/// // the `Foo` when the refcount reaches zero.
+/// unsafe impl RefCounted for Foo {
+/// fn inc_ref(&self) {
+/// self.refcount.replace(self.refcount.get() + 1);
+/// }
+///
+/// unsafe fn dec_ref(this: NonNull<Self>) {
+/// // SAFETY: By requirement on calling this function, the refcount is non-zero,
+/// // implying the underlying object is valid.
+/// let refcount = unsafe { &this.as_ref().refcount };
+/// let new_refcount = refcount.get() - 1;
+/// if new_refcount == 0 {
+/// // The `Foo` will be dropped when `KBox` goes out of scope.
+/// // SAFETY: The [`KBox<Foo>`] is still alive as the old refcount is 1. We can pass
+/// // ownership to the [`KBox`] as by requirement on calling this function,
+/// // the `Self` will no longer be used by the caller.
+/// unsafe { KBox::from_raw(this.as_ptr()) };
+/// } else {
+/// refcount.replace(new_refcount);
+/// }
+/// }
+/// }
+///
+/// impl OwnableRefCounted for Foo {
+/// fn try_from_shared(this: ARef<Self>) -> Result<Owned<Self>, ARef<Self>> {
+/// if this.refcount.get() == 1 {
+/// // SAFETY: The `Foo` is still alive and has no other Rust references as the refcount
+/// // is 1.
+/// Ok(unsafe { Owned::from_raw(ARef::into_raw(this)) })
+/// } else {
+/// Err(this)
+/// }
+/// }
+///
+/// fn into_shared(this: Owned<Self>) -> ARef<Self> {
+/// // SAFETY: An `Owned<Foo>` holds the unique reference (refcount 1), which we transfer to
+/// // the new `ARef`.
+/// unsafe { ARef::from_raw(Owned::into_raw(this)) }
+/// }
+/// }
+///
+/// impl Ownable for Foo {
+/// unsafe fn release(this: NonNull<Self>) {
+/// // SAFETY: Using `dec_ref()` from [`RefCounted`] to release is okay, as the refcount is
+/// // always 1 for an [`Owned<Foo>`].
+/// unsafe { Foo::dec_ref(this) };
+/// }
+/// }
+///
+/// let foo = Foo::new()?;
+/// let foo = ARef::from(foo);
+/// {
+/// let bar = foo.clone();
+/// assert!(Owned::try_from(bar).is_err());
+/// }
+/// assert!(Owned::try_from(foo).is_ok());
+/// # Ok::<(), Error>(())
+/// ```
+pub trait OwnableRefCounted: RefCounted + Ownable + Sized {
+ /// Checks if the [`ARef`] is unique and converts it to an [`Owned`] if that is the case.
+ /// Otherwise it returns again an [`ARef`] to the same underlying object.
+ fn try_from_shared(this: ARef<Self>) -> Result<Owned<Self>, ARef<Self>>;
+
+ /// Converts the [`Owned`] into an [`ARef`].
+ fn into_shared(this: Owned<Self>) -> ARef<Self>;
+}
+
+impl<T: OwnableRefCounted> TryFrom<ARef<T>> for Owned<T> {
+ type Error = ARef<T>;
+ /// Tries to convert the [`ARef`] to an [`Owned`] by calling
+ /// [`try_from_shared()`](OwnableRefCounted::try_from_shared). In case the [`ARef`] is not
+ /// unique, it returns again an [`ARef`] to the same underlying object.
+ #[inline]
+ fn try_from(b: ARef<T>) -> Result<Owned<T>, Self::Error> {
+ T::try_from_shared(b)
+ }
+}
diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index 1c0796ea229f0..32dd030c83159 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -12,16 +12,16 @@
code::*,
Result, //
},
+ types::{
+ Opaque,
+ Ownable,
+ Owned, //
+ },
uaccess::UserSliceReader, //
};
-use core::{
- marker::PhantomData,
- mem::ManuallyDrop,
- ops::Deref,
- ptr::{
- self,
- NonNull, //
- }, //
+use core::ptr::{
+ self,
+ NonNull, //
};
/// A bitwise shift for the page size.
@@ -65,93 +65,29 @@ pub const fn page_align(addr: usize) -> Option<usize> {
Some(sum & PAGE_MASK)
}
-/// Representation of a non-owning reference to a [`Page`].
-///
-/// This type provides a borrowed version of a [`Page`] that is owned by some other entity, e.g. a
-/// [`Vmalloc`] allocation such as [`VBox`].
-///
-/// # Example
-///
-/// ```
-/// # use kernel::{bindings, prelude::*};
-/// use kernel::page::{BorrowedPage, Page, PAGE_SIZE};
-/// # use core::{mem::MaybeUninit, ptr, ptr::NonNull };
-///
-/// fn borrow_page<'a>(vbox: &'a mut VBox<MaybeUninit<[u8; PAGE_SIZE]>>) -> BorrowedPage<'a> {
-/// let ptr = ptr::from_ref(&**vbox);
-///
-/// // SAFETY: `ptr` is a valid pointer to `Vmalloc` memory.
-/// let page = unsafe { bindings::vmalloc_to_page(ptr.cast()) };
-///
-/// // SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid
-/// // pointer to `Vmalloc` memory.
-/// let page = unsafe { NonNull::new_unchecked(page) };
-///
-/// // SAFETY:
-/// // - `self.0` is a valid pointer to a `struct page`.
-/// // - `self.0` is valid for the entire lifetime of `self`.
-/// unsafe { BorrowedPage::from_raw(page) }
-/// }
-///
-/// let mut vbox = VBox::<[u8; PAGE_SIZE]>::new_uninit(GFP_KERNEL)?;
-/// let page = borrow_page(&mut vbox);
-///
-/// // SAFETY: There is no concurrent read or write to this page.
-/// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
-/// # Ok::<(), Error>(())
-/// ```
-///
-/// # Invariants
-///
-/// The borrowed underlying pointer to a `struct page` is valid for the entire lifetime `'a`.
-///
-/// [`VBox`]: kernel::alloc::VBox
-/// [`Vmalloc`]: kernel::alloc::allocator::Vmalloc
-pub struct BorrowedPage<'a>(ManuallyDrop<Page>, PhantomData<&'a Page>);
-
-impl<'a> BorrowedPage<'a> {
- /// Constructs a [`BorrowedPage`] from a raw pointer to a `struct page`.
- ///
- /// # Safety
- ///
- /// - `ptr` must point to a valid `bindings::page`.
- /// - `ptr` must remain valid for the entire lifetime `'a`.
- pub unsafe fn from_raw(ptr: NonNull<bindings::page>) -> Self {
- let page = Page { page: ptr };
-
- // INVARIANT: The safety requirements guarantee that `ptr` is valid for the entire lifetime
- // `'a`.
- Self(ManuallyDrop::new(page), PhantomData)
- }
-}
-
-impl<'a> Deref for BorrowedPage<'a> {
- type Target = Page;
-
- fn deref(&self) -> &Self::Target {
- &self.0
- }
-}
-
-/// Trait to be implemented by types which provide an [`Iterator`] implementation of
-/// [`BorrowedPage`] items, such as [`VmallocPageIter`](kernel::alloc::allocator::VmallocPageIter).
+/// Trait to be implemented by types which provide an [`Iterator`] of [`Page`] references, such as
+/// [`VmallocPageIter`](kernel::alloc::allocator::VmallocPageIter).
pub trait AsPageIter {
/// The [`Iterator`] type, e.g. [`VmallocPageIter`](kernel::alloc::allocator::VmallocPageIter).
- type Iter<'a>: Iterator<Item = BorrowedPage<'a>>
+ type Iter<'a>: Iterator<Item = &'a Page>
where
Self: 'a;
- /// Returns an [`Iterator`] of [`BorrowedPage`] items over all pages owned by `self`.
+ /// Returns an [`Iterator`] of [`Page`] references over all pages owned by `self`.
fn page_iter(&mut self) -> Self::Iter<'_>;
}
-/// A pointer to a page that owns the page allocation.
+/// A `struct page`.
+///
+/// A `Page` is accessed through a shared reference or through an owning [`Owned<Page>`]; the latter
+/// frees the page allocation when it is dropped.
///
/// # Invariants
///
-/// The pointer is valid, and has ownership over the page.
+/// The `Page` is backed by a valid `struct page`.
+#[repr(transparent)]
pub struct Page {
- page: NonNull<bindings::page>,
+ page: Opaque<bindings::page>,
}
// SAFETY: Pages have no logic that relies on them staying on a given thread, so moving them across
@@ -185,19 +121,20 @@ impl Page {
/// # Ok::<(), kernel::alloc::AllocError>(())
/// ```
#[inline]
- pub fn alloc_page(flags: Flags) -> Result<Self, AllocError> {
+ pub fn alloc_page(flags: Flags) -> Result<Owned<Self>, AllocError> {
// SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
// is always safe to call this method.
let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) };
let page = NonNull::new(page).ok_or(AllocError)?;
- // INVARIANT: We just successfully allocated a page, so we now have ownership of the newly
- // allocated page. We transfer that ownership to the new `Page` object.
- Ok(Self { page })
+ // SAFETY: We just successfully allocated a page, so we now have ownership of the newly
+ // allocated page. We transfer that ownership to the new `Owned<Page>` object.
+ // Since `Page` is transparent, we can cast the pointer directly.
+ Ok(unsafe { Owned::from_raw(page.cast()) })
}
/// Returns a raw pointer to the page.
pub fn as_ptr(&self) -> *mut bindings::page {
- self.page.as_ptr()
+ self.page.get()
}
/// Get the node id containing this page.
@@ -207,6 +144,20 @@ pub fn nid(&self) -> i32 {
unsafe { bindings::page_to_nid(self.as_ptr()) }
}
+ /// Create a `&Page` from a raw `struct page` pointer.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must be convertible to a shared reference with a lifetime of `'a`.
+ #[inline]
+ pub unsafe fn from_raw<'a>(ptr: *const bindings::page) -> &'a Self {
+ // INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`, so
+ // the returned reference upholds the type invariant of `Page`.
+ // SAFETY: By function safety requirements, `ptr` is not null and is convertible to a shared
+ // reference.
+ unsafe { &*ptr.cast() }
+ }
+
/// Runs a piece of code with this page mapped to an address.
///
/// The page is unmapped when this call returns.
@@ -373,10 +324,11 @@ pub unsafe fn copy_from_user_slice_raw(
}
}
-impl Drop for Page {
+impl Ownable for Page {
#[inline]
- fn drop(&mut self) {
- // SAFETY: By the type invariants, we have ownership of the page and can free it.
- unsafe { bindings::__free_pages(self.page.as_ptr(), 0) };
+ unsafe fn release(this: NonNull<Self>) {
+ // SAFETY: By the function safety requirements, we have ownership of the page and can free
+ // it. Since Page is transparent, we can cast the raw pointer directly.
+ unsafe { bindings::__free_pages(this.as_ptr().cast(), 0) };
}
}
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 5071cae6543fd..ea9ef99cecb07 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -19,6 +19,10 @@
},
prelude::*,
str::CStr,
+ sync::aref::{
+ AlwaysRefCounted,
+ RefCounted, //
+ },
types::Opaque,
ThisModule, //
};
@@ -481,7 +485,7 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
+unsafe impl RefCounted for Device {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::pci_dev_get(self.as_raw()) };
@@ -493,6 +497,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl AlwaysRefCounted for Device {}
+
impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
fn as_ref(&self) -> &device::Device<Ctx> {
// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
diff --git a/rust/kernel/pid_namespace.rs b/rust/kernel/pid_namespace.rs
index 979a9718f153d..067f68b99e8c5 100644
--- a/rust/kernel/pid_namespace.rs
+++ b/rust/kernel/pid_namespace.rs
@@ -7,7 +7,14 @@
//! C header: [`include/linux/pid_namespace.h`](srctree/include/linux/pid_namespace.h) and
//! [`include/linux/pid.h`](srctree/include/linux/pid.h)
-use crate::{bindings, sync::aref::AlwaysRefCounted, types::Opaque};
+use crate::{
+ bindings,
+ sync::aref::RefCounted,
+ types::{
+ AlwaysRefCounted,
+ Opaque, //
+ }, //
+};
use core::ptr;
/// Wraps the kernel's `struct pid_namespace`. Thread safe.
@@ -41,7 +48,7 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::pid_namespace) -> &'a Self {
}
// SAFETY: Instances of `PidNamespace` are always reference-counted.
-unsafe impl AlwaysRefCounted for PidNamespace {
+unsafe impl RefCounted for PidNamespace {
#[inline]
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -55,6 +62,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<PidNamespace>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<PidNamespace>` from
+// a `&PidNamespace`.
+unsafe impl AlwaysRefCounted for PidNamespace {}
+
// SAFETY:
// - `PidNamespace::dec_ref` can be called from any thread.
// - It is okay to send ownership of `PidNamespace` across thread boundaries.
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index d41555a4b31d2..a4ddaa1cc3a40 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -24,6 +24,10 @@
},
of,
prelude::*,
+ sync::aref::{
+ AlwaysRefCounted,
+ RefCounted, //
+ },
types::Opaque,
ThisModule, //
};
@@ -519,7 +523,7 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
+unsafe impl RefCounted for Device {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::get_device(self.as_ref().as_raw()) };
@@ -531,6 +535,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl AlwaysRefCounted for Device {}
+
impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
fn as_ref(&self) -> &device::Device<Ctx> {
// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
diff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs
index 6c9d667009ef7..2d1cd74dd98e1 100644
--- a/rust/kernel/pwm.rs
+++ b/rust/kernel/pwm.rs
@@ -13,7 +13,11 @@
devres,
error::{self, to_result},
prelude::*,
- sync::aref::{ARef, AlwaysRefCounted},
+ sync::aref::{
+ ARef,
+ AlwaysRefCounted,
+ RefCounted, //
+ },
types::Opaque, //
};
use core::{
@@ -629,7 +633,7 @@ pub fn new<'a>(
}
// SAFETY: Implements refcounting for `Chip` using the embedded `struct device`.
-unsafe impl<T: PwmOps> AlwaysRefCounted for Chip<T> {
+unsafe impl<T: PwmOps> RefCounted for Chip<T> {
#[inline]
fn inc_ref(&self) {
// SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists.
@@ -647,6 +651,10 @@ unsafe fn dec_ref(obj: NonNull<Chip<T>>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Chip<T>>` from a
+// `&Chip<T>`.
+unsafe impl<T: PwmOps> AlwaysRefCounted for Chip<T> {}
+
// SAFETY: `Chip` is a wrapper around `*mut bindings::pwm_chip`. The underlying C
// structure's state is managed and synchronized by the kernel's device model
// and PWM core locking mechanisms. Therefore, it is safe to move the `Chip`
diff --git a/rust/kernel/sync/aref.rs b/rust/kernel/sync/aref.rs
index b721b2e00b986..e6ffe7c650c39 100644
--- a/rust/kernel/sync/aref.rs
+++ b/rust/kernel/sync/aref.rs
@@ -11,7 +11,7 @@
//! underlying object, but this refcount is internal to the object. It essentially is a Rust
//! implementation of the `get_` and `put_` pattern used in C for reference counting.
//!
-//! To make use of [`ARef<MyType>`], `MyType` needs to implement [`AlwaysRefCounted`]. It is a trait
+//! To make use of [`ARef<MyType>`], `MyType` needs to implement [`RefCounted`]. It is a trait
//! for accessing the internal reference count of an object of the `MyType` type.
//!
//! [`Arc`]: crate::sync::Arc
@@ -23,26 +23,35 @@
ops::Deref,
ptr::NonNull, //
};
+use kernel::types::{
+ OwnableRefCounted,
+ Owned, //
+};
-/// 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
/// 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). Implementing the trait
+/// [`OwnableRefCounted`] allows to convert between unique and
+/// shared references (i.e. [`Owned<Self>`](crate::types::Owned) and
+/// [`ARef<Self>`]).
+///
/// # Safety
///
/// Implementers must ensure that increments to the reference count keep the object alive in memory
/// 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 +64,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 deriving 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 violating the uniqueness guarantee
+/// of [`crate::types::Owned<T>`] by dereferencing 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 +95,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,19 +104,19 @@ 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> {}
// Even if `T` is pinned, pointers to `T` can still move.
-impl<T: AlwaysRefCounted> Unpin for ARef<T> {}
+impl<T: RefCounted> Unpin 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.
@@ -120,19 +145,21 @@ 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 {
+ /// // SAFETY: The `RefCounted` implementation for `Empty` does not count references and never
+ /// // frees the underlying object. Thus we can act as owning an increment on the refcount for
+ /// // the object that we pass to the newly created `ARef`.
+ /// unsafe impl RefCounted for Empty {
/// fn inc_ref(&self) {}
/// unsafe fn dec_ref(_obj: NonNull<Self>) {}
/// }
///
/// 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);
///
@@ -143,7 +170,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.
@@ -151,7 +178,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 {
@@ -168,7 +195,14 @@ fn from(b: &T) -> Self {
}
}
-impl<T: AlwaysRefCounted> Drop for ARef<T> {
+impl<T: OwnableRefCounted> From<Owned<T>> for ARef<T> {
+ #[inline]
+ fn from(b: Owned<T>) -> Self {
+ T::into_shared(b)
+ }
+}
+
+impl<T: RefCounted> Drop for ARef<T> {
fn drop(&mut self) {
// SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to
// decrement.
@@ -178,19 +212,19 @@ fn drop(&mut self) {
impl<T, U> PartialEq<ARef<U>> for ARef<T>
where
- T: AlwaysRefCounted + PartialEq<U>,
- U: AlwaysRefCounted,
+ T: RefCounted + PartialEq<U>,
+ U: RefCounted,
{
#[inline]
fn eq(&self, other: &ARef<U>) -> bool {
T::eq(&**self, &**other)
}
}
-impl<T: AlwaysRefCounted + Eq> Eq for ARef<T> {}
+impl<T: RefCounted + Eq> Eq for ARef<T> {}
impl<T, U> PartialEq<&'_ U> for ARef<T>
where
- T: AlwaysRefCounted + PartialEq<U>,
+ T: RefCounted + PartialEq<U>,
{
#[inline]
fn eq(&self, other: &&U) -> bool {
diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs
index 38273f4eedb51..6259430b0ca31 100644
--- a/rust/kernel/task.rs
+++ b/rust/kernel/task.rs
@@ -10,7 +10,12 @@
pid_namespace::PidNamespace,
prelude::*,
sync::aref::ARef,
- types::{NotThreadSafe, Opaque},
+ types::{
+ AlwaysRefCounted,
+ NotThreadSafe,
+ Opaque,
+ RefCounted, //
+ },
};
use core::{
ops::Deref,
@@ -347,7 +352,7 @@ pub fn group_leader(&self) -> &Task {
}
// SAFETY: The type invariants guarantee that `Task` is always refcounted.
-unsafe impl crate::sync::aref::AlwaysRefCounted for Task {
+unsafe impl RefCounted for Task {
#[inline]
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
@@ -361,6 +366,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Task>` from a
+// `&Task`.
+unsafe impl AlwaysRefCounted for Task {}
+
impl PartialEq for Task {
#[inline]
fn eq(&self, other: &Self) -> bool {
diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index ac316fd7b538f..6aa760952cb63 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -15,6 +15,18 @@
pub mod for_lt;
pub use for_lt::ForLt;
+pub use crate::{
+ owned::{
+ Ownable,
+ OwnableRefCounted,
+ Owned, //
+ },
+ sync::aref::{
+ AlwaysRefCounted,
+ RefCounted, //
+ }, //
+};
+
/// Used to transfer ownership to and from foreign (non-Rust) languages.
///
/// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and
diff --git a/rust/kernel/usb.rs b/rust/kernel/usb.rs
index 7aff0c82d0afc..59350c6b0df2a 100644
--- a/rust/kernel/usb.rs
+++ b/rust/kernel/usb.rs
@@ -18,7 +18,10 @@
to_result, //
},
prelude::*,
- sync::aref::AlwaysRefCounted,
+ sync::aref::{
+ AlwaysRefCounted,
+ RefCounted, //
+ },
types::Opaque,
ThisModule, //
};
@@ -392,7 +395,7 @@ fn as_ref(&self) -> &Device {
}
// SAFETY: Instances of `Interface` are always reference-counted.
-unsafe impl AlwaysRefCounted for Interface {
+unsafe impl RefCounted for Interface {
fn inc_ref(&self) {
// SAFETY: The invariants of `Interface` guarantee that `self.as_raw()`
// returns a valid `struct usb_interface` pointer, for which we will
@@ -406,6 +409,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Interface>` from a
+// `&Interface`.
+unsafe impl AlwaysRefCounted for Interface {}
+
// SAFETY: A `Interface` is always reference-counted and can be released from any thread.
unsafe impl Send for Interface {}
@@ -443,7 +450,7 @@ fn as_raw(&self) -> *mut bindings::usb_device {
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl AlwaysRefCounted for Device {
+unsafe impl RefCounted for Device {
fn inc_ref(&self) {
// SAFETY: The invariants of `Device` guarantee that `self.as_raw()`
// returns a valid `struct usb_device` pointer, for which we will
@@ -457,6 +464,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl AlwaysRefCounted for Device {}
+
impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
fn as_ref(&self) -> &device::Device<Ctx> {
// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
index 7e253b6f299ce..77673b8ea45fb 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -192,7 +192,7 @@
sync::{
aref::{
ARef,
- AlwaysRefCounted, //
+ RefCounted, //
},
Arc,
LockClassKey, //
@@ -954,7 +954,7 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Pin<KBox<T>>
// implementation of `WorkItemPointer` for `ARef<T>`.
unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T>
where
- T: AlwaysRefCounted,
+ T: RefCounted,
T: WorkItem<ID, Pointer = Self>,
T: HasWork<T, ID>,
{
@@ -987,7 +987,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T>
// requirements of `WorkItemPointer`.
unsafe impl<T, const ID: u64> RawWorkItem<ID> for ARef<T>
where
- T: AlwaysRefCounted,
+ T: RefCounted,
T: WorkItem<ID, Pointer = Self>,
T: HasWork<T, ID>,
{
@@ -1020,7 +1020,7 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for ARef<T>
where
T: WorkItem<ID, Pointer = Self>,
T: HasDelayedWork<T, ID>,
- T: AlwaysRefCounted,
+ T: RefCounted,
{
}
|
| 3/2 | 2026/08/24 13:12 | llm | patch-evaluator |
0mModel:gemini-3.1-pro-preview Args: null Results: null Tokens: input: 23137 output: 113 thoughts: 1232 Thoughts: **WorthFuzzing=false: A Deep Dive into Rust Abstraction Refactoring** Alright, let's break down this patch series and determine if it warrants fuzzing. My initial impression is that it's primarily concerned with restructuring Rust abstractions for the Linux kernel, specifically introducing `Owned<T>` and `Ownable` traits. We're also seeing a refactoring of `AlwaysRefCounted` into `RefCounted` and `AlwaysRefCounted`, and changes in how `Page` and `PageInfo` are handled, now using `Owned<Page>` in allocation. My primary concern is whether these changes introduce any new functional behavior that could expose vulnerabilities. On initial review, it seems like we're mostly dealing with: * `AlwaysRefCounted` split into `RefCounted` and `AlwaysRefCounted` * Introduction of `Owned<T>` as a pointer type. * `Page` allocation now returning `Owned<Page>`. * `PageInfo` in Android Binder using `Owned<Page>`. I need to confirm if these changes touch any core kernel logic or drivers. Scanning `drivers/android/binder/page_range.rs`, I see changes related to `set_page`. However, this appears to be another Rust abstraction shift, dealing with `Option<Owned<Page>>` instead of `Option<Page>`. The `Owned<T>` essentially wraps `NonNull<T>`. `Page` was previously represented as `NonNull<bindings::page>`. Now, it’s `NonNull<Page>`, which effectively becomes `NonNull<Opaque<bindings::page>>`. This means the size and layout are identical. Also, the drop logic for `Owned<Page>` is the same as the prior drop logic for the original `Page`. Looking deeper, `rust/kernel/alloc/allocator.rs` is interesting. Previously, `to_page` returned a `BorrowedPage`, now it is returning `&page::Page`. `BorrowedPage` was a wrapper around `ManuallyDrop<Page>`. It appears to be another Rust type system change. So, are there any *functional* implications? No. It seems this is a pure refactoring of Rust types and traits. Introducing `Owned` and `Ownable` and splitting `AlwaysRefCounted` doesn't seem to alter execution flow or core kernel behavior. Let's make sure I'm not missing anything. I need to make sure there are no new features or logic as a result of these changes. I'm seeing a new file, `rust/kernel/owned.rs`, but it's just definitions for the new types and traits. Reviewing the changes in `drivers/android/binder/page_range.rs`, `rust/kernel/alloc/allocator.rs`, and `rust/kernel/owned.rs` again, it looks purely like an API refactoring. The compiled code will almost certainly remain exactly the same. No functional change. Let me make absolutely sure, and double-check all the files touched in this series. - `drivers/android/binder/page_range.rs`: Switched from `Option<Page>` to `Option<Owned<Page>>`. - `rust/kernel/alloc/allocator.rs`: Switched from `BorrowedPage` to `&Page`. - `rust/kernel/alloc/kbox.rs`: Added `into_non_null`. - `rust/kernel/auxiliary.rs`: Changed `AlwaysRefCounted` to `RefCounted` + `AlwaysRefCounted`. - `rust/kernel/block/mq/request.rs`: Same. - `rust/kernel/cred.rs`: Same. - `rust/kernel/device.rs`: Same. - `rust/kernel/device/property.rs`: Same. - `rust/kernel/drm/device.rs`: Same. - `rust/kernel/drm/gem/mod.rs`: Same. - `rust/kernel/fs/file.rs`: Same. - `rust/kernel/i2c.rs`: Same. - `rust/kernel/mm.rs`: Same. - `rust/kernel/mm/mmput_async.rs`: Same. - `rust/kernel/opp.rs`: Same. - `rust/kernel/owned.rs`: New file with `Ownable`, `Owned`, `OwnableRefCounted`. - `rust/kernel/page.rs`: `BorrowedPage` removed, `Page` now uses `Ownable`, `alloc_page` returns `Owned<Page>`. - `rust/kernel/pci.rs`: Same refcount changes. - |
| 4/2 | 2026/08/24 13:12 | tool | set-results |
0mArgs:{
"EnableConfigs": [],
"FocusSymbols": [],
"Reasoning": "The patch series is a pure refactoring of Rust abstractions in the kernel. It introduces the `Owned` and `Ownable` traits, splits `AlwaysRefCounted` into `RefCounted` and `AlwaysRefCounted`, and updates the `Page` abstraction and its users (like Android Binder) to use the new types. It does not introduce any functional changes or alter the execution flow of the kernel.",
"WorthFuzzing": false
}Results: {
"EnableConfigs": null,
"FocusSymbols": [],
"Reasoning": "The patch series is a pure refactoring of Rust abstractions in the kernel. It introduces the `Owned` and `Ownable` traits, splits `AlwaysRefCounted` into `RefCounted` and `AlwaysRefCounted`, and updates the `Page` abstraction and its users (like Android Binder) to use the new types. It does not introduce any functional changes or alter the execution flow of the kernel.",
"WorthFuzzing": false
} |
| 5/1 | 2026/08/24 13:12 | action | If |
0mArgs:{
"WorthFuzzing": false
}Results: null |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|