Re: [PATCH V10 13/15] rust: cpufreq: Extend abstractions for driver registration

From: Danilo Krummrich
Date: Wed Apr 16 2025 - 05:05:21 EST


On Wed, Apr 16, 2025 at 12:09:30PM +0530, Viresh Kumar wrote:
> + /// Registers a CPU frequency driver with the cpufreq core.
> + pub fn new() -> Result<Self> {
> + let drv: *const bindings::cpufreq_driver = &Self::VTABLE;
> + let drv = drv.cast_mut();
> +
> + // SAFETY: It is safe to register the driver with the cpufreq core in the kernel C code.
> + to_result(unsafe { bindings::cpufreq_register_driver(drv) })?;

You need to justify why drv is a valid pointer to be passed to
cpufreq_register_driver(), i.e. something like

// SAFETY:
// - `drv` comes from Self::VTABLE and hence is a valid pointer to a `struct cpufreq_driver`,
// - `cpufreq_register_driver()` never attempts to modify the data `drv` points to

> +
> + Ok(Self(
> + NonNull::new(drv.cast()).ok_or(AllocError)?,

We know `drv` can't be NULL, hence it's better to use NonNull::new_unchecked().

> + PhantomData,
> + ))
> + }
> +
> + /// Same as [`Registration::new`], but does not return a [`Registration`] instance.
> + ///
> + /// Instead the [`Registration`] is owned by [`Devres`] and will be revoked / dropped, once the
> + /// device is detached.
> + pub fn new_foreign_owned(dev: &Device) -> Result<()> {
> + Devres::new_foreign_owned(dev, Self::new()?, GFP_KERNEL)?;

If you remove the question mark operator and the semicolon, you can remove the
below.

> + Ok(())
> + }
> +}

<snip>

> +impl<T: Driver> Drop for Registration<T> {
> + // Removes the `Registration` from the kernel, if it has initialized successfully earlier.
> + fn drop(&mut self) {
> + // SAFETY: The driver was earlier registered from `new`.

Should be similar to the safety comment in Self::new().

> + unsafe { bindings::cpufreq_unregister_driver(self.0.as_ptr()) };
> + }
> +}

With those fixed,

Reviewed-by: Danilo Krummrich <dakr@xxxxxxxxxx>