Re: [PATCH V6 04/15] rust: device: Add few helpers

From: Greg Kroah-Hartman
Date: Tue Jan 07 2025 - 06:56:20 EST


On Tue, Jan 07, 2025 at 04:51:37PM +0530, Viresh Kumar wrote:
> Add from_cpu() and property_present() helpers to the device bindings.

That says what, but not why.

Also those are two totally different things, I'm going to argue with you
about one of them...

> + /// Creates a new ref-counted instance of device of a CPU.
> + pub fn from_cpu(cpu: u32) -> Result<ARef<Self>> {

Why is this a reference counted device, yet the C structure is NOT
properly reference counted at all? Are you _sure_ this is going to work
properly?

And really, we should fix up the C side to properly reference count all
of this. Just read the comment in cpu_device_release() for a hint at
what needs to be done here.

> + // SAFETY: It is safe to call `get_cpu_device()` for any CPU number.

For any number at all, no need to say "CPU" here, right?

> + let ptr = unsafe { bindings::get_cpu_device(cpu) };
> + if ptr.is_null() {
> + return Err(ENODEV);
> + }
> +
> + // SAFETY: By the safety requirements, ptr is valid.
> + Ok(unsafe { Device::get_device(ptr) })

So why is this device reference counted? I get it that it should be,
but how does that play with the "real" device here?

> + }
> +
> /// Obtain the raw `struct device *`.
> pub(crate) fn as_raw(&self) -> *mut bindings::device {
> self.0.get()
> @@ -180,6 +195,12 @@ unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) {
> )
> };
> }
> +
> + /// Checks if property is present or not.
> + pub fn property_present(&self, name: &CString) -> bool {
> + // SAFETY: `name` is null-terminated. `self.as_raw` is valid because `self` is valid.
> + unsafe { bindings::device_property_present(self.as_raw(), name.as_ptr() as *const _) }

is "self.as_raw()" a constant pointer too?

thanks,

greg k-h