Re: [PATCH v2] rust/kernel: Add faux device bindings
From: Alice Ryhl
Date: Fri Feb 07 2025 - 04:32:39 EST
On Fri, Feb 7, 2025 at 10:25 AM Greg Kroah-Hartman
<gregkh@xxxxxxxxxxxxxxxxxxx> wrote:
>
> On Thu, Feb 06, 2025 at 07:40:45PM -0500, Lyude Paul wrote:
> > This introduces a crate for working with faux devices in rust, along with
> > adding sample code to show how the API is used. Unlike other types of
> > devices, we don't provide any hooks for device probe/removal - since these
> > are optional for the faux API and are unnecessary in rust.
> >
> > Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
> > Cc: Greg Kroah-Hartman <gregkh@xxxxxxxxxxxxxxxxxxx>
> > Cc: Maíra Canal <mairacanal@xxxxxxxxxx>
> > +impl AsRef<device::Device> for Registration {
> > + fn as_ref(&self) -> &device::Device {
> > + // SAFETY: The underlying `device` in `faux_device` is guaranteed by the C API to be
> > + // a valid initialized `device`.
> > + unsafe { device::Device::as_ref(addr_of_mut!((*self.as_raw()).dev)) }
>
> Just curious, this is returning an incremented "struct device" to the
> caller, right? And then when it goes out of scope it will have the
> reference decremented? And do you need a wrapper in C to get to ".dev"
> of the faux_device structure or are you ok doing it like this?
This uses the &_ pointer type which does not involve any refcount
increments or decrements. What you describe only happens if the
ARef<_> pointer type is used instead.
Safety is ensured by the borrow checker that fails compilation if the
returned reference is used after the Registration object is destroyed
- i.e. it's assumed that the value is safe to access without refcount
increments as long as the Registration is still alive.
Alice