Re: [PATCH 2/4] rust: devres: replace Devres::new_foreign_owned()

From: Benno Lossin
Date: Sat Jun 21 2025 - 17:10:31 EST


On Thu Jun 12, 2025 at 4:51 PM CEST, Danilo Krummrich wrote:
> diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs
> index b0a9c6182aec..f20636079f7a 100644
> --- a/rust/kernel/cpufreq.rs
> +++ b/rust/kernel/cpufreq.rs
> @@ -12,7 +12,7 @@
> clk::Hertz,
> cpumask,
> device::{Bound, Device},
> - devres::Devres,
> + devres,
> error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR},
> ffi::{c_char, c_ulong},
> prelude::*,
> @@ -910,7 +910,7 @@ unsafe impl<T: Driver> Sync for Registration<T> {}
> /// thread.
> unsafe impl<T: Driver> Send for Registration<T> {}
>
> -impl<T: Driver> Registration<T> {
> +impl<T: Driver + 'static> Registration<T> {

This change should probably be its own patch? If not, then it should be
mentioned in the commit message.

> const VTABLE: bindings::cpufreq_driver = bindings::cpufreq_driver {
> name: Self::copy_name(T::NAME),
> boost_enabled: T::BOOST_ENABLED,
> @@ -1044,10 +1044,10 @@ pub fn new() -> Result<Self> {
>
> /// 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
> + /// Instead the [`Registration`] is owned by [`kernel::devres`] and will be dropped, once the
> /// device is detached.
> pub fn new_foreign_owned(dev: &Device<Bound>) -> Result {

I think we can improve the names here. How about `new_attached`? See
more below.

> - Devres::new_foreign_owned(dev, Self::new()?, GFP_KERNEL)
> + devres::register_foreign_boxed(dev, Self::new()?, GFP_KERNEL)
> }
> }

> +/// Encapsulate `data` in a [`KBox`] and [`Drop::drop`] `data` once `dev` is unbound.
> +///
> +/// # Examples
> +///
> +/// ```no_run
> +/// use kernel::{device::{Bound, Device}, devres};
> +///
> +/// struct Registration;
> +///
> +/// impl Registration {
> +/// fn new() -> Self {
> +/// // register (e.g. class device, IRQ, etc.)
> +///
> +/// Self
> +/// }
> +/// }
> +///
> +/// impl Drop for Registration {
> +/// fn drop(&mut self) {
> +/// // unregister
> +/// }
> +/// }
> +///
> +/// fn from_bound_context(dev: &Device<Bound>) -> Result {
> +/// devres::register_foreign_boxed(dev, Registration::new(), GFP_KERNEL)
> +/// }
> +/// ```
> +pub fn register_foreign_boxed<T, E>(

I don't really get the name of this function. The data isn't really
foreign and that the user also shouldn't really care about the fact that
you use `KBox` under the hood.

How about we call this something like `attach_data`?

---
Cheers,
Benno

> + dev: &Device<Bound>,
> + data: impl PinInit<T, E>,
> + flags: Flags,
> +) -> Result
> +where
> + T: 'static,
> + Error: From<E>,
> +{
> + let data = KBox::pin_init(data, flags)?;
> +
> + register_foreign(dev, data)
> +}