Re: [PATCH v2 1/4] rust: device: implement Device::parent()

From: Danilo Krummrich
Date: Thu Mar 20 2025 - 19:46:25 EST


On Thu, Mar 20, 2025 at 10:44:38PM +0000, Benno Lossin wrote:
> On Thu Mar 20, 2025 at 11:27 PM CET, Danilo Krummrich wrote:
> > Device::parent() returns a reference to the device' parent device, if
> > any.
> >
> > Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
> > Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
> > ---
> > rust/kernel/device.rs | 15 +++++++++++++++
> > 1 file changed, 15 insertions(+)
> >
> > diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
> > index 21b343a1dc4d..f6bdc2646028 100644
> > --- a/rust/kernel/device.rs
> > +++ b/rust/kernel/device.rs
> > @@ -65,6 +65,21 @@ pub(crate) fn as_raw(&self) -> *mut bindings::device {
> > self.0.get()
> > }
> >
> > + /// Returns a reference to the parent device, if any.
> > + pub fn parent<'a>(&self) -> Option<&'a Self> {
> > + // SAFETY:
> > + // - By the type invariant `self.as_raw()` is always valid.
> > + // - The parent device is only ever set at device creation.
> > + let parent = unsafe { (*self.as_raw()).parent };
> > +
> > + if parent.is_null() {
> > + None
> > + } else {
> > + // SAFETY: Since `parent` is not NULL, it must be a valid pointer to a `struct device`.
> > + Some(unsafe { Self::as_ref(parent) })
>
> Why is this valid for `'static`? Since you declare the lifetime `'a`
> independently from the elided one on `&self`, the user can set it to
> `'static`.

Good catch -- this is indeed a problem when the &Device comes from an
ARef<Device>, rather than Device::as_ref(), which is what I had in mind
originally.