`AlwaysRefCounted` is renamed to `RefCounted`.
`AlwaysRefCounted` will become a marker trait to indicate that it is
allowed to obtain an `ARef<T>` from a `&T`, which cannot be allowed for
types which are also Ownable.
Signed-off-by: Oliver Mangold <oliver.mangold@pm.me>
Suggested-by: Alice Ryhl <aliceryhl@google.com>
---
rust/kernel/block/mq/request.rs | 15 +++++++++------
rust/kernel/cred.rs | 8 ++++++--
rust/kernel/device.rs | 8 ++++++--
rust/kernel/fs/file.rs | 10 +++++++---
rust/kernel/mm.rs | 13 ++++++++++---
rust/kernel/mm/mmput_async.rs | 9 +++++++--
rust/kernel/opp.rs | 8 ++++++--
rust/kernel/pci.rs | 6 +++++-
rust/kernel/pid_namespace.rs | 8 ++++++--
rust/kernel/platform.rs | 6 +++++-
rust/kernel/task.rs | 6 +++++-
rust/kernel/types.rs | 41 ++++++++++++++++++++++++-----------------
rust/kernel/types/ownable.rs | 4 ++--
13 files changed, 98 insertions(+), 44 deletions(-)
diff --git a/rust/kernel/block/mq/request.rs b/rust/kernel/block/mq/request.rs
index 4a5b7ec914efa598c65881b07c4ece59214fd7e7..ca02d07f13ade252bc3b4d2ca3e5e21a16a7288e 100644
--- a/rust/kernel/block/mq/request.rs
+++ b/rust/kernel/block/mq/request.rs
@@ -8,7 +8,7 @@
bindings,
block::mq::Operations,
error::Result,
- types::{ARef, AlwaysRefCounted, Opaque},
+ types::{ARef, AlwaysRefCounted, Opaque, RefCounted},
};
use core::{
marker::PhantomData,
@@ -226,11 +226,10 @@ fn atomic_relaxed_op_unless(target: &AtomicU64, op: impl Fn(u64) -> u64, pred: u
.is_ok()
}
-// 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) {
let refcount = &self.wrapper_ref().refcount();
@@ -260,3 +259,7 @@ unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
}
}
}
+
+// SAFETY: We currently do not implement `Ownable`, thus it is okay to can 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 2599f01e8b285f2106aefd27c315ae2aff25293c..87fa2808050dd8a2838a0f5c21cd7f567ba6b534 100644
--- a/rust/kernel/cred.rs
+++ b/rust/kernel/cred.rs
@@ -11,7 +11,7 @@
use crate::{
bindings,
task::Kuid,
- types::{AlwaysRefCounted, Opaque},
+ types::{AlwaysRefCounted, Opaque, RefCounted},
};
/// Wraps the kernel's `struct cred`.
@@ -74,7 +74,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.
@@ -88,3 +88,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 can 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 dea06b79ecb536cee4d2b90c21b74658658417c7..afddb4d70d2f375c891facac7f83501cd9918f54 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -7,7 +7,7 @@
use crate::{
bindings,
str::CStr,
- types::{ARef, Opaque},
+ types::{ARef, AlwaysRefCounted, Opaque, RefCounted},
};
use core::{fmt, marker::PhantomData, ptr};
@@ -216,7 +216,7 @@ pub fn property_present(&self, name: &CStr) -> bool {
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::types::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()) };
@@ -228,6 +228,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `Device<Task>` 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/fs/file.rs b/rust/kernel/fs/file.rs
index 72d84fb0e2664643619ad7fbcbbb55b3adc9f9b4..489f6d1f17508af7e064e3f506349797fff497ae 100644
--- a/rust/kernel/fs/file.rs
+++ b/rust/kernel/fs/file.rs
@@ -11,7 +11,7 @@
bindings,
cred::Credential,
error::{code::*, Error, Result},
- types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque},
+ types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque, RefCounted},
};
use core::ptr;
@@ -190,7 +190,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.
@@ -205,6 +205,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<File>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can 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.
@@ -226,7 +230,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.
diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs
index 43f525c0d16ce87340ba4f991c45d4e82a050eae..9bbb317896eaa06f0e654873993ae9ff531d4c61 100644
--- a/rust/kernel/mm.rs
+++ b/rust/kernel/mm.rs
@@ -13,7 +13,7 @@
use crate::{
bindings,
- types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque},
+ types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque, RefCounted},
};
use core::{ops::Deref, ptr::NonNull};
@@ -54,7 +54,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.
@@ -68,6 +68,9 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can 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
@@ -90,7 +93,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.
@@ -104,6 +107,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can 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 9289e05f7a676b577e4edf45949c0fab6aacec14..1b8c5cc32123ed406079aa1505e623ea6af81011 100644
--- a/rust/kernel/mm/mmput_async.rs
+++ b/rust/kernel/mm/mmput_async.rs
@@ -10,7 +10,7 @@
use crate::{
bindings,
mm::MmWithUser,
- types::{ARef, AlwaysRefCounted},
+ types::{ARef, AlwaysRefCounted, RefCounted},
};
use core::{ops::Deref, ptr::NonNull};
@@ -34,7 +34,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 +48,11 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+
+// SAFETY: We do not implement `Ownable`, thus it is okay to can 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 a566fc3e7dcb87237c68eb7d174efa5658712ddb..b8a3dace7a616cd8944e3f647293cc4ca79235bd 100644
--- a/rust/kernel/opp.rs
+++ b/rust/kernel/opp.rs
@@ -16,7 +16,7 @@
ffi::c_ulong,
prelude::*,
str::CString,
- types::{ARef, AlwaysRefCounted, Opaque},
+ types::{ARef, AlwaysRefCounted, Opaque, RefCounted},
};
#[cfg(CONFIG_CPU_FREQ)]
@@ -1042,7 +1042,7 @@ unsafe impl Send for OPP {}
unsafe impl Sync for OPP {}
/// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted.
-unsafe impl AlwaysRefCounted for OPP {
+unsafe impl RefCounted for OPP {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
unsafe { bindings::dev_pm_opp_get(self.0.get()) };
@@ -1054,6 +1054,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can 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/pci.rs b/rust/kernel/pci.rs
index 8435f8132e38129ccc3495e7c4d3237fcaa97ad9..e56f48bfe1e60096208bc49963046fbdd070afee 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -435,7 +435,7 @@ pub fn set_master(&self) {
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::types::AlwaysRefCounted for Device {
+unsafe impl crate::types::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()) };
@@ -447,6 +447,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl crate::types::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 0e93808e4639b37dd77add5d79f64058dac7cb87..b5e319fa050002179fa920dd40f02a08f8473b22 100644
--- a/rust/kernel/pid_namespace.rs
+++ b/rust/kernel/pid_namespace.rs
@@ -9,7 +9,7 @@
use crate::{
bindings,
- types::{AlwaysRefCounted, Opaque},
+ types::{AlwaysRefCounted, Opaque, RefCounted},
};
use core::ptr;
@@ -44,7 +44,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.
@@ -58,6 +58,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<PidNamespace>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can 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 5b21fa517e55348582622ec10471918919502959..c37ba50e5dcc53891e08706343fcd446d640cda1 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -196,7 +196,7 @@ fn as_raw(&self) -> *mut bindings::platform_device {
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
-unsafe impl crate::types::AlwaysRefCounted for Device {
+unsafe impl crate::types::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()) };
@@ -208,6 +208,10 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `ARef<Device>` from a
+// `&Device`.
+unsafe impl crate::types::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/task.rs b/rust/kernel/task.rs
index 927413d854846477578cbaf06e27d1fc867d0682..6c16f03c50591d6aafe4b9176c5c934e1a7b81ba 100644
--- a/rust/kernel/task.rs
+++ b/rust/kernel/task.rs
@@ -340,7 +340,7 @@ pub fn active_pid_ns(&self) -> Option<&PidNamespace> {
}
// SAFETY: The type invariants guarantee that `Task` is always refcounted.
-unsafe impl crate::types::AlwaysRefCounted for Task {
+unsafe impl crate::types::RefCounted for Task {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
unsafe { bindings::get_task_struct(self.as_ptr()) };
@@ -352,6 +352,10 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+// SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `ARef<Task>` from a
+// `&Task`.
+unsafe impl crate::types::AlwaysRefCounted for Task {}
+
impl Kuid {
/// Get the current euid.
#[inline]
diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index c12ff4d2a3f2d79b760c34c0b84a51b507d0cfb1..40c0138bd336057e7d3a835a9e81391baa2fd2b1 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -418,11 +418,9 @@ pub const fn raw_get(this: *const Self) -> *mut T {
}
}
-/// 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
@@ -438,9 +436,8 @@ pub const fn raw_get(this: *const Self) -> *mut T {
/// 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);
@@ -453,11 +450,21 @@ 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>);
}
+/// An extension to RefCounted, which declares that it is allowed to convert from a shared reference
+/// `&T` to an owned reference [`ARef<T>`].
+///
+/// # Safety
+///
+/// Implementers must ensure that no safety invariants are violated by upgrading an `&T` to an
+/// [`ARef<T>`]. In particular that implies [`AlwaysRefCounted`] and [`Ownable`] cannot be
+/// implemented for the same type, as this would allow to violate the uniqueness guarantee of
+/// [`Owned<T>`] by derefencing it into an `&T` and obtaining an [`ARef`] from that.
+pub unsafe trait AlwaysRefCounted: RefCounted {}
+
/// An owned reference to an always-reference-counted object.
///
/// The object's reference count is automatically decremented when an instance of [`ARef`] is
@@ -468,7 +475,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>,
}
@@ -477,16 +484,16 @@ pub struct ARef<T: AlwaysRefCounted> {
// it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
// `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a
// mutable reference, for example, when the reference count reaches zero and `T` is dropped.
-unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {}
+unsafe impl<T: RefCounted + Sync + Send> Send for ARef<T> {}
// SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync`
// because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
// it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an
// `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for
// example, when the reference count reaches zero and `T` is dropped.
-unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {}
+unsafe impl<T: RefCounted + Sync + Send> Sync for ARef<T> {}
-impl<T: AlwaysRefCounted> ARef<T> {
+impl<T: RefCounted> ARef<T> {
/// Creates a new instance of [`ARef`].
///
/// It takes over an increment of the reference count on the underlying object.
@@ -515,12 +522,12 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
///
/// ```
/// use core::ptr::NonNull;
- /// use kernel::types::{ARef, AlwaysRefCounted};
+ /// use kernel::types::{ARef, RefCounted};
///
/// struct Empty {}
///
/// # // SAFETY: TODO.
- /// unsafe impl AlwaysRefCounted for Empty {
+ /// unsafe impl RefCounted for Empty {
/// fn inc_ref(&self) {}
/// unsafe fn dec_ref(_obj: NonNull<Self>) {}
/// }
@@ -538,7 +545,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.
@@ -546,7 +553,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 {
@@ -563,7 +570,7 @@ fn from(b: &T) -> Self {
}
}
-impl<T: AlwaysRefCounted> Drop for ARef<T> {
+impl<T: RefCounted> Drop for ARef<T> {
fn drop(&mut self) {
// SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to
// decrement.
diff --git a/rust/kernel/types/ownable.rs b/rust/kernel/types/ownable.rs
index f4065a0d627a62d3ecb15edabf306e9b812556e1..80cd990f6601767aa5a742a6c0997f4f67d06453 100644
--- a/rust/kernel/types/ownable.rs
+++ b/rust/kernel/types/ownable.rs
@@ -18,8 +18,8 @@
///
/// Note: Implementing this trait allows types to be wrapped in an [`Owned<Self>`]. This does not
/// provide reference counting but represents a unique, owned reference. If reference counting is
-/// required [`AlwaysRefCounted`](crate::types::AlwaysRefCounted) should be implemented which allows
-/// types to be wrapped in an [`ARef<Self>`](crate::types::ARef).
+/// required [`RefCounted`](crate::types::RefCounted) should be implemented which allows types to be
+/// wrapped in an [`ARef<Self>`](crate::types::ARef).
///
/// # Safety
///
--
2.49.0
On Wed Jun 18, 2025 at 2:27 PM CEST, Oliver Mangold wrote: > diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs > index c12ff4d2a3f2d79b760c34c0b84a51b507d0cfb1..40c0138bd336057e7d3a835a9e81391baa2fd2b1 100644 > --- a/rust/kernel/types.rs > +++ b/rust/kernel/types.rs > @@ -418,11 +418,9 @@ pub const fn raw_get(this: *const Self) -> *mut T { > } > } > > -/// 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 > @@ -438,9 +436,8 @@ pub const fn raw_get(this: *const Self) -> *mut T { > /// 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); This seems a bit problematic for `Owned`, since now I can do: fn bad<T: Ownable + RefCounted>(t: &Owned<T>) { t.inc_ref(); } And now the `Owned<T>` is no longer "unique" in the sense that the refcount is 1... Similarly, we should probably make this an associated function, such that people don't accidentally call `.inc_ref()` on `ARef<T>`. > @@ -453,11 +450,21 @@ 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>); > } > > +/// An extension to RefCounted, which declares that it is allowed to convert from a shared reference > +/// `&T` to an owned reference [`ARef<T>`]. This is a bit too long for the first sentence... How about Always reference counted type. Allows the creation of `ARef<T>` from `&T`. Feel free to add more information. > +/// > +/// # Safety > +/// > +/// Implementers must ensure that no safety invariants are violated by upgrading an `&T` to an > +/// [`ARef<T>`]. In particular that implies [`AlwaysRefCounted`] and [`Ownable`] cannot be > +/// implemented for the same type, as this would allow to violate the uniqueness guarantee of > +/// [`Owned<T>`] by derefencing it into an `&T` and obtaining an [`ARef`] from that. > +pub unsafe trait AlwaysRefCounted: RefCounted {} It's a bit sad that we can't just say `: !Ownable` (or rather a blanket-implemented marker trait, since that might land earlier). Anyone aware of progress in this area? --- Cheers, Benno > + > /// An owned reference to an always-reference-counted object. > /// > /// The object's reference count is automatically decremented when an instance of [`ARef`] is
On 250702 1323, Benno Lossin wrote: > On Wed Jun 18, 2025 at 2:27 PM CEST, Oliver Mangold wrote: > > diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs > > index c12ff4d2a3f2d79b760c34c0b84a51b507d0cfb1..40c0138bd336057e7d3a835a9e81391baa2fd2b1 100644 > > --- a/rust/kernel/types.rs > > +++ b/rust/kernel/types.rs > > @@ -418,11 +418,9 @@ pub const fn raw_get(this: *const Self) -> *mut T { > > } > > } > > > > -/// 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 > > @@ -438,9 +436,8 @@ pub const fn raw_get(this: *const Self) -> *mut T { > > /// 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); > > This seems a bit problematic for `Owned`, since now I can do: > > fn bad<T: Ownable + RefCounted>(t: &Owned<T>) { > t.inc_ref(); > } > > And now the `Owned<T>` is no longer "unique" in the sense that the > refcount is 1... Yes, that is clear. But that isn't a soundness issue or is it? It just means the `T` can be leaked, but that cannot be prevented anyway. > Similarly, we should probably make this an associated function, such > that people don't accidentally call `.inc_ref()` on `ARef<T>`. > > > @@ -453,11 +450,21 @@ 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>); > > } > > > > +/// An extension to RefCounted, which declares that it is allowed to convert from a shared reference > > +/// `&T` to an owned reference [`ARef<T>`]. > > This is a bit too long for the first sentence... How about > > Always reference counted type. > > Allows the creation of `ARef<T>` from `&T`. > > Feel free to add more information. Yes, should be okay. > > +/// > > +/// # Safety > > +/// > > +/// Implementers must ensure that no safety invariants are violated by upgrading an `&T` to an > > +/// [`ARef<T>`]. In particular that implies [`AlwaysRefCounted`] and [`Ownable`] cannot be > > +/// implemented for the same type, as this would allow to violate the uniqueness guarantee of > > +/// [`Owned<T>`] by derefencing it into an `&T` and obtaining an [`ARef`] from that. > > +pub unsafe trait AlwaysRefCounted: RefCounted {} > > It's a bit sad that we can't just say `: !Ownable` (or rather a > blanket-implemented marker trait, since that might land earlier). Anyone > aware of progress in this area? Yes. But as far as I am aware negative constraints are considered to be deeply problematic because of combinatoric explosion in binary logic. Best, Oliver
On Mon Jul 7, 2025 at 9:42 AM CEST, Oliver Mangold wrote: > On 250702 1323, Benno Lossin wrote: >> On Wed Jun 18, 2025 at 2:27 PM CEST, Oliver Mangold wrote: >> > diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs >> > index c12ff4d2a3f2d79b760c34c0b84a51b507d0cfb1..40c0138bd336057e7d3a835a9e81391baa2fd2b1 100644 >> > --- a/rust/kernel/types.rs >> > +++ b/rust/kernel/types.rs >> > @@ -418,11 +418,9 @@ pub const fn raw_get(this: *const Self) -> *mut T { >> > } >> > } >> > >> > -/// 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 >> > @@ -438,9 +436,8 @@ pub const fn raw_get(this: *const Self) -> *mut T { >> > /// 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); >> >> This seems a bit problematic for `Owned`, since now I can do: >> >> fn bad<T: Ownable + RefCounted>(t: &Owned<T>) { >> t.inc_ref(); >> } >> >> And now the `Owned<T>` is no longer "unique" in the sense that the >> refcount is 1... > > Yes, that is clear. But that isn't a soundness issue or is it? It just > means the `T` can be leaked, but that cannot be prevented anyway. Yeah that is true. >> Similarly, we should probably make this an associated function, such >> that people don't accidentally call `.inc_ref()` on `ARef<T>`. Filed https://github.com/Rust-for-Linux/linux/issues/1177 --- Cheers, Benno
Hi Oliver, kernel test robot noticed the following build errors: [auto build test ERROR on e04c78d86a9699d136910cfc0bdcf01087e3267e] url: https://github.com/intel-lab-lkp/linux/commits/Oliver-Mangold/rust-types-Add-Ownable-Owned-types/20250618-203524 base: e04c78d86a9699d136910cfc0bdcf01087e3267e patch link: https://lore.kernel.org/r/20250618-unique-ref-v11-2-49eadcdc0aa6%40pm.me patch subject: [PATCH v11 2/4] rust: Split `AlwaysRefCounted` into two traits config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20250619/202506191023.smOZ1Mpy-lkp@intel.com/config) compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff) rustc: rustc 1.78.0 (9b00956e5 2024-04-29) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250619/202506191023.smOZ1Mpy-lkp@intel.com/reproduce) If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202506191023.smOZ1Mpy-lkp@intel.com/ All errors (new ones prefixed by >>): PATH=/opt/cross/clang-18/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin INFO PATH=/opt/cross/rustc-1.78.0-bindgen-0.65.1/cargo/bin:/opt/cross/clang-18/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS= -Wno-error=return-type -Wreturn-type -funsigned-char -Wundef W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck make: Entering directory '/kbuild/src/consumer' make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust' >> Diff in rust/kernel/mm/mmput_async.rs at line 48: } } - // SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `ARef<MmWithUserAsync>` // from a `&MmWithUserAsync`. unsafe impl AlwaysRefCounted for MmWithUserAsync {} >> Diff in rust/kernel/mm/mmput_async.rs at line 48: } } - // SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `ARef<MmWithUserAsync>` // from a `&MmWithUserAsync`. unsafe impl AlwaysRefCounted for MmWithUserAsync {} >> Diff in rust/kernel/mm/mmput_async.rs at line 48: } } - // SAFETY: We do not implement `Ownable`, thus it is okay to can obtain an `ARef<MmWithUserAsync>` // from a `&MmWithUserAsync`. unsafe impl AlwaysRefCounted for MmWithUserAsync {} make[2]: *** [Makefile:1825: rustfmt] Error 123 make[2]: Target 'rustfmtcheck' not remade because of errors. make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust' make[1]: *** [Makefile:248: __sub-make] Error 2 make[1]: Target 'rustfmtcheck' not remade because of errors. make: *** [Makefile:248: __sub-make] Error 2 make: Target 'rustfmtcheck' not remade because of errors. make: Leaving directory '/kbuild/src/consumer' -- >> error[E0277]: the trait bound `auxiliary::Device: types::RefCounted` is not satisfied --> rust/kernel/device.rs:329:56 | 329 | impl ::core::convert::From<&$device<$src>> for $crate::types::ARef<$device> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `types::RefCounted` is not implemented for `auxiliary::Device` | ::: rust/kernel/auxiliary.rs:250:1 | 250 | kernel::impl_device_context_into_aref!(Device); | ---------------------------------------------- in this macro invocation | = help: the following other types implement trait `types::RefCounted`: block::mq::request::Request<T> cred::Credential device::Device fs::file::File fs::file::LocalFile mm::mmput_async::MmWithUserAsync mm::Mm mm::MmWithUser and 4 others note: required by a bound in `types::ARef` --> rust/kernel/types.rs:478:20 | 478 | pub struct ARef<T: RefCounted> { | ^^^^^^^^^^ required by this bound in `ARef` = note: this error originates in the macro `::kernel::__impl_device_context_into_aref` which comes from the expansion of the macro `kernel::impl_device_context_into_aref` (in Nightly builds, run with -Z macro-backtrace for more info) -- >> error[E0277]: the trait bound `auxiliary::Device: types::RefCounted` is not satisfied --> rust/kernel/auxiliary.rs:253:48 | 253 | unsafe impl crate::types::AlwaysRefCounted for Device { | ^^^^^^ the trait `types::RefCounted` is not implemented for `auxiliary::Device` | = help: the following other types implement trait `types::RefCounted`: block::mq::request::Request<T> cred::Credential device::Device fs::file::File fs::file::LocalFile mm::mmput_async::MmWithUserAsync mm::Mm mm::MmWithUser and 4 others note: required by a bound in `types::AlwaysRefCounted` --> rust/kernel/types.rs:466:36 | 466 | pub unsafe trait AlwaysRefCounted: RefCounted {} | ^^^^^^^^^^ required by this bound in `AlwaysRefCounted` -- >> error[E0277]: the trait bound `auxiliary::Device: types::RefCounted` is not satisfied --> rust/kernel/device.rs:330:45 | 330 | fn from(dev: &$device<$src>) -> Self { | ^^^^ the trait `types::RefCounted` is not implemented for `auxiliary::Device` | ::: rust/kernel/auxiliary.rs:250:1 | 250 | kernel::impl_device_context_into_aref!(Device); | ---------------------------------------------- in this macro invocation | = help: the following other types implement trait `types::RefCounted`: block::mq::request::Request<T> cred::Credential device::Device fs::file::File fs::file::LocalFile mm::mmput_async::MmWithUserAsync mm::Mm mm::MmWithUser and 4 others note: required by a bound in `types::ARef` --> rust/kernel/types.rs:478:20 | 478 | pub struct ARef<T: RefCounted> { | ^^^^^^^^^^ required by this bound in `ARef` = note: this error originates in the macro `::kernel::__impl_device_context_into_aref` which comes from the expansion of the macro `kernel::impl_device_context_into_aref` (in Nightly builds, run with -Z macro-backtrace for more info) -- >> error[E0277]: the trait bound `auxiliary::Device: types::RefCounted` is not satisfied --> rust/kernel/device.rs:331:17 | 331 | (&**dev).into() | ^^^^^^^^^^^^^^^ the trait `types::RefCounted` is not implemented for `auxiliary::Device` | ::: rust/kernel/auxiliary.rs:250:1 | 250 | kernel::impl_device_context_into_aref!(Device); | ---------------------------------------------- in this macro invocation | = help: the following other types implement trait `types::RefCounted`: block::mq::request::Request<T> cred::Credential device::Device fs::file::File fs::file::LocalFile mm::mmput_async::MmWithUserAsync mm::Mm mm::MmWithUser and 4 others note: required by a bound in `types::ARef` --> rust/kernel/types.rs:478:20 | 478 | pub struct ARef<T: RefCounted> { | ^^^^^^^^^^ required by this bound in `ARef` = note: this error originates in the macro `::kernel::__impl_device_context_into_aref` which comes from the expansion of the macro `kernel::impl_device_context_into_aref` (in Nightly builds, run with -Z macro-backtrace for more info) -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
© 2016 - 2025 Red Hat, Inc.