[PATCH v8 2/7] rust: pwm: Add core 'Device' and 'Chip' object wrappers
Danilo Krummrich
dakr at kernel.org
Fri Jul 4 08:12:20 PDT 2025
On Fri, Jul 04, 2025 at 02:01:12PM +0200, Michal Wilczynski wrote:
> +impl<T: 'static + ForeignOwnable> Chip<T> {
> + /// Allocates and wraps a PWM chip using `bindings::pwmchip_alloc`.
> + ///
> + /// Returns an [`ARef<Chip>`] managing the chip's lifetime via refcounting
> + /// on its embedded `struct device`.
> + pub fn new(
> + parent_dev: &device::Device,
> + npwm: u32,
> + sizeof_priv: usize,
> + drvdata: T,
> + ) -> Result<ARef<Self>> {
> + // SAFETY: `parent_device_for_dev_field.as_raw()` is valid.
> + // `bindings::pwmchip_alloc` returns a valid `*mut bindings::pwm_chip` (refcount 1)
> + // or an ERR_PTR.
> + let c_chip_ptr_raw =
> + unsafe { bindings::pwmchip_alloc(parent_dev.as_raw(), npwm, sizeof_priv) };
> +
> + let c_chip_ptr: *mut bindings::pwm_chip = error::from_err_ptr(c_chip_ptr_raw)?;
> +
> + // Cast the `*mut bindings::pwm_chip` to `*mut Chip`. This is valid because
> + // `Chip` is `repr(transparent)` over `Opaque<bindings::pwm_chip>`, and
> + // `Opaque<T>` is `repr(transparent)` over `T`.
> + let chip_ptr_as_self = c_chip_ptr.cast::<Self>();
> +
> + // SAFETY: The pointer is valid, so we can create a temporary ref to set data.
> + let chip_ref = unsafe { &*chip_ptr_as_self };
> + // SAFETY: `chip_ref` points to a valid chip from `pwmchip_alloc` and `drvdata` is a valid,
> + // owned pointer from `ForeignOwnable` to be stored in the chip's private data.
> + unsafe { bindings::pwmchip_set_drvdata(chip_ref.as_raw(), drvdata.into_foreign().cast()) }
I think that's great now, but you're missing one last piece: You have to ensure
that drvdata is freed eventually. Here you call into_foreign(), but I think
you're missing from_foreign() in pwm_ops::free.
You also have to ensure that your pwm_ops::free() callback is properly called if
a Chip<T> is dropped *before* it has been registered.
Note that, since Chip is now generic over T, you can easily make the
PwmOpsVTable a const within Chip and set the vtable in Chip::new().
See also how drm::Device does this in [1].
[1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/rust/kernel/drm/device.rs
> +
> + // SAFETY: `chip_ptr_as_self` points to a valid `Chip` (layout-compatible with
> + // `bindings::pwm_chip`) whose embedded device has refcount 1.
> + // `ARef::from_raw` takes this pointer and manages it via `AlwaysRefCounted`.
> + Ok(unsafe { ARef::from_raw(NonNull::new_unchecked(chip_ptr_as_self)) })
> + }
More information about the linux-riscv
mailing list