From nobody Wed Oct 8 00:54:23 2025 Received: from mailout2.w1.samsung.com (mailout2.w1.samsung.com [210.118.77.12]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 663D62D640B for ; Fri, 4 Jul 2025 12:02:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=210.118.77.12 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751630545; cv=none; b=X8TbQJ1dVyQUCS9GFZOw9cG2dCIlLnEyJeHrbZGNeBEZGy3GhtyIrAYHHCiR31fYt/I3pjmTffnZ07MZxHCTtg0HhT6Msq9BJbtIccS5t8zRl/hTBE+gGxE6BKWjnBnJ8Yq8PGwlrVbtJwuh2M4/N9FzWiE6/KEYunz2U7qGsyk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751630545; c=relaxed/simple; bh=DczjI35ZY7BAzTfO19RxJOiKoYPwpsomUHNHQ53TFB0=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=TXx30XG6qwbMjhJvcRJW/T/c/GwVKrSahGGgISoMvrR59spzAlCMVK3/t3e7C1tjnFv4vcy4JbCLDRVvD4lLk67JGpS/OtzINfIlEbMqKtULMB0FhJn8Npxu2EVIiLhxxzOywNsO6wrGf8B25sQuCJ8TX6boPJY60xwyyNA8YTw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=samsung.com; spf=pass smtp.mailfrom=samsung.com; dkim=pass (1024-bit key) header.d=samsung.com header.i=@samsung.com header.b=Y42Bvtgs; arc=none smtp.client-ip=210.118.77.12 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=samsung.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=samsung.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=samsung.com header.i=@samsung.com header.b="Y42Bvtgs" Received: from eucas1p1.samsung.com (unknown [182.198.249.206]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250704120213euoutp026251dfc18e9b7d180bcbc08577b2782b~PCrCku78D1047910479euoutp02Q for ; Fri, 4 Jul 2025 12:02:13 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250704120213euoutp026251dfc18e9b7d180bcbc08577b2782b~PCrCku78D1047910479euoutp02Q DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1751630533; bh=3X5nMi7+YNW25BArZ2DX4aFZ8IPmZROtEC5Cbq+AlGw=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=Y42BvtgsDXqiA9T6VpEuHnf6LH+l4dFd0RRpYf6Zwo0OwQoz+Kiq/HNsZzwVO+TGz qWnlMn3YNuNQxxPF8ZtEnsuSfreveJAnR7Bv3poQ0OVyeO1GWgIZSVtGJB/SLE+aeN HDjOyv8+uMUTZ75D7D5sYG4yjK8+hXa35zvYrfF0= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p1.samsung.com (KnoxPortal) with ESMTPA id 20250704120212eucas1p1c9ffeefa41b0ddb27db74d26174831bf~PCrBmHxox1819018190eucas1p1r; Fri, 4 Jul 2025 12:02:12 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250704120211eusmtip12522615cdee71b47938f19820c85f210~PCrAf6SAh0801408014eusmtip1j; Fri, 4 Jul 2025 12:02:11 +0000 (GMT) From: Michal Wilczynski Date: Fri, 04 Jul 2025 14:01:12 +0200 Subject: [PATCH v8 2/7] rust: pwm: Add core 'Device' and 'Chip' object wrappers Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Message-Id: <20250704-rust-next-pwm-working-fan-for-sending-v8-2-951e5482c9fd@samsung.com> In-Reply-To: <20250704-rust-next-pwm-working-fan-for-sending-v8-0-951e5482c9fd@samsung.com> To: =?utf-8?q?Uwe_Kleine-K=C3=B6nig?= , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Michal Wilczynski , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Drew Fustini , Benno Lossin , Drew Fustini Cc: linux-kernel@vger.kernel.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-riscv@lists.infradead.org, devicetree@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250704120212eucas1p1c9ffeefa41b0ddb27db74d26174831bf X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250704120212eucas1p1c9ffeefa41b0ddb27db74d26174831bf X-EPHeader: CA X-CMS-RootMailID: 20250704120212eucas1p1c9ffeefa41b0ddb27db74d26174831bf References: <20250704-rust-next-pwm-working-fan-for-sending-v8-0-951e5482c9fd@samsung.com> Building on the basic data types, this commit introduces the central object abstractions for the PWM subsystem: Device and Chip. It also includes the core trait implementations that make the Chip wrapper a complete, safe, and managed object. The main components of this change are: - Device and Chip Structs: These structs wrap the underlying struct pwm_device and struct pwm_chip C objects, providing safe, idiomatic methods to access their fields. - High-Level `Device` API: Exposes safe wrappers for the modern `waveform` API, allowing consumers to apply, read, and pre-validate hardware configurations. - Core Trait Implementations for Chip: - AlwaysRefCounted: Links the Chip's lifetime to its embedded struct device reference counter. This enables automatic lifetime management via ARef. - Send and Sync: Marks the Chip wrapper as safe for use across threads. This is sound because the C core handles all necessary locking for the underlying object's state. These wrappers and traits form a robust foundation for building PWM drivers in Rust. Reviewed-by: Danilo Krummrich Signed-off-by: Michal Wilczynski --- rust/kernel/pwm.rs | 266 +++++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 263 insertions(+), 3 deletions(-) diff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs index 3fad101406eac728d9b12083fad7abf7b7f89b25..ba2f5a0ce5b9c4ca64f2984a627= 324aa8ab669cc 100644 --- a/rust/kernel/pwm.rs +++ b/rust/kernel/pwm.rs @@ -7,11 +7,12 @@ //! C header: [`include/linux/pwm.h`](srctree/include/linux/pwm.h). =20 use crate::{ - bindings, + bindings, device, + error::{self, to_result}, prelude::*, - types::Opaque, + types::{ARef, AlwaysRefCounted, ForeignOwnable, Opaque}, }; -use core::convert::TryFrom; +use core::{convert::TryFrom, ptr::NonNull}; =20 /// PWM polarity. Mirrors [`enum pwm_polarity`](srctree/include/linux/pwm.= h). #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -135,3 +136,262 @@ pub fn enabled(&self) -> bool { self.0.enabled } } + +/// Describes the outcome of a `round_waveform` operation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RoundingOutcome { + /// The requested waveform was achievable exactly or by rounding value= s down. + ExactOrRoundedDown, + + /// The requested waveform could only be achieved by rounding up. + RoundedUp, +} + +/// Wrapper for a PWM device [`struct pwm_device`](srctree/include/linux/p= wm.h). +#[repr(transparent)] +pub struct Device(Opaque); + +impl Device { + /// Creates a reference to a [`Device`] from a valid C pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for t= he lifetime of the + /// returned [`Device`] reference. + pub(crate) unsafe fn as_ref<'a>(ptr: *mut bindings::pwm_device) -> &'a= Self { + // SAFETY: The safety requirements guarantee the validity of the d= ereference, while the + // `Device` type being transparent makes the cast ok. + unsafe { &*ptr.cast::() } + } + + /// Returns a raw pointer to the underlying `pwm_device`. + fn as_raw(&self) -> *mut bindings::pwm_device { + self.0.get() + } + + /// Gets the hardware PWM index for this device within its chip. + pub fn hwpwm(&self) -> u32 { + // SAFETY: `self.as_raw()` provides a valid pointer for `self`'s l= ifetime. + unsafe { (*self.as_raw()).hwpwm } + } + + /// Gets a reference to the parent `Chip` that this device belongs to. + pub fn chip(&self) -> &Chip { + // SAFETY: `self.as_raw()` provides a valid pointer. (*self.as_raw= ()).chip + // is assumed to be a valid pointer to `pwm_chip` managed by the k= ernel. + // Chip::as_ref's safety conditions must be met. + unsafe { Chip::::as_ref((*self.as_raw()).chip) } + } + + /// Gets the label for this PWM device, if any. + pub fn label(&self) -> Option<&CStr> { + // SAFETY: self.as_raw() provides a valid pointer. + let label_ptr =3D unsafe { (*self.as_raw()).label }; + if label_ptr.is_null() { + None + } else { + // SAFETY: label_ptr is non-null and points to a C string + // managed by the kernel, valid for the lifetime of the PWM de= vice. + Some(unsafe { CStr::from_char_ptr(label_ptr) }) + } + } + + /// Gets a copy of the board-dependent arguments for this PWM device. + pub fn args(&self) -> Args { + // SAFETY: self.as_raw() gives a valid pointer to `pwm_device`. + // The `args` field is a valid `pwm_args` struct embedded within `= pwm_device`. + // `Args::from_c_ptr`'s safety conditions are met by providing thi= s pointer. + unsafe { Args::from_c_ptr(&(*self.as_raw()).args) } + } + + /// Gets a copy of the current state of this PWM device. + pub fn state(&self) -> State { + // SAFETY: `self.as_raw()` gives a valid pointer. `(*self.as_raw()= ).state` + // is a valid `pwm_state` struct. `State::from_c` copies this data. + State::from_c(unsafe { (*self.as_raw()).state }) + } + + /// Sets the PWM waveform configuration and enables the PWM signal. + pub fn set_waveform(&self, wf: &Waveform, exact: bool) -> Result { + let c_wf =3D bindings::pwm_waveform::from(*wf); + + // SAFETY: `self.as_raw()` provides a valid `*mut pwm_device` poin= ter. + // `&c_wf` is a valid pointer to a `pwm_waveform` struct. The C fu= nction + // handles all necessary internal locking. + let ret =3D unsafe { bindings::pwm_set_waveform_might_sleep(self.a= s_raw(), &c_wf, exact) }; + to_result(ret) + } + + /// Queries the hardware for the configuration it would apply for a gi= ven + /// request. + pub fn round_waveform(&self, wf: &mut Waveform) -> Result { + let mut c_wf =3D bindings::pwm_waveform::from(*wf); + + // SAFETY: `self.as_raw()` provides a valid `*mut pwm_device` poin= ter. + // `&mut c_wf` is a valid pointer to a mutable `pwm_waveform` stru= ct that + // the C function will update. + let ret =3D unsafe { bindings::pwm_round_waveform_might_sleep(self= .as_raw(), &mut c_wf) }; + + to_result(ret)?; + + *wf =3D Waveform::from(c_wf); + + if ret =3D=3D 1 { + Ok(RoundingOutcome::RoundedUp) + } else { + Ok(RoundingOutcome::ExactOrRoundedDown) + } + } + + /// Reads the current waveform configuration directly from the hardwar= e. + pub fn get_waveform(&self) -> Result { + let mut c_wf =3D bindings::pwm_waveform::default(); + + // SAFETY: `self.as_raw()` is a valid pointer. We provide a valid = pointer + // to a stack-allocated `pwm_waveform` struct for the kernel to fi= ll. + let ret =3D unsafe { bindings::pwm_get_waveform_might_sleep(self.a= s_raw(), &mut c_wf) }; + + to_result(ret)?; + + Ok(Waveform::from(c_wf)) + } +} + +/// Wrapper for a PWM chip/controller ([`struct pwm_chip`](srctree/include= /linux/pwm.h)). +#[repr(transparent)] +pub struct Chip(Opaque, PhantomData= ); + +impl Chip { + /// Creates a reference to a [`Chip`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for t= he lifetime of the + /// returned [`Chip`] reference. + pub(crate) unsafe fn as_ref<'a>(ptr: *mut bindings::pwm_chip) -> &'a S= elf { + // SAFETY: The safety requirements guarantee the validity of the d= ereference, while the + // `Chip` type being transparent makes the cast ok. + unsafe { &*ptr.cast::() } + } + + /// Returns a raw pointer to the underlying `pwm_chip`. + pub(crate) fn as_raw(&self) -> *mut bindings::pwm_chip { + self.0.get() + } + + /// Gets the number of PWM channels (hardware PWMs) on this chip. + pub fn npwm(&self) -> u32 { + // SAFETY: `self.as_raw()` provides a valid pointer for `self`'s l= ifetime. + unsafe { (*self.as_raw()).npwm } + } + + /// Returns `true` if the chip supports atomic operations for configur= ation. + pub fn is_atomic(&self) -> bool { + // SAFETY: `self.as_raw()` provides a valid pointer for `self`'s l= ifetime. + unsafe { (*self.as_raw()).atomic } + } + + /// Returns a reference to the embedded `struct device` abstraction. + pub fn device(&self) -> &device::Device { + // SAFETY: `self.as_raw()` provides a valid pointer to `bindings::= pwm_chip`. + // The `dev` field is an instance of `bindings::device` embedded w= ithin `pwm_chip`. + // Taking a pointer to this embedded field is valid. + // `device::Device` is `#[repr(transparent)]`. + // The lifetime of the returned reference is tied to `self`. + unsafe { device::Device::as_ref(&raw mut (*self.as_raw()).dev) } + } + + /// Returns a reference to the parent device of this PWM chip's device. + /// + /// # Safety + /// + /// The caller must guarantee that the parent device exists and is bou= nd. + /// This is guaranteed by the PWM core during `PwmOps` callbacks. + unsafe fn bound_parent_device(&self) -> &device::Device { + // SAFETY: Per the function's safety contract, the parent device e= xists. + let parent =3D unsafe { self.device().parent().unwrap_unchecked() = }; + + // SAFETY: Per the function's safety contract, the parent device i= s bound. + // The pointer is cast from `&Device` to `&Device`. + unsafe { &*core::ptr::from_ref(parent).cast::>() } + } +} + +impl Chip { + /// Allocates and wraps a PWM chip using `bindings::pwmchip_alloc`. + /// + /// Returns an [`ARef`] managing the chip's lifetime via refcoun= ting + /// on its embedded `struct device`. + pub fn new( + parent_dev: &device::Device, + npwm: u32, + sizeof_priv: usize, + drvdata: T, + ) -> Result> { + // SAFETY: `parent_device_for_dev_field.as_raw()` is valid. + // `bindings::pwmchip_alloc` returns a valid `*mut bindings::pwm_c= hip` (refcount 1) + // or an ERR_PTR. + let c_chip_ptr_raw =3D + unsafe { bindings::pwmchip_alloc(parent_dev.as_raw(), npwm, si= zeof_priv) }; + + let c_chip_ptr: *mut bindings::pwm_chip =3D error::from_err_ptr(c_= chip_ptr_raw)?; + + // Cast the `*mut bindings::pwm_chip` to `*mut Chip`. This is vali= d because + // `Chip` is `repr(transparent)` over `Opaque`= , and + // `Opaque` is `repr(transparent)` over `T`. + let chip_ptr_as_self =3D c_chip_ptr.cast::(); + + // SAFETY: The pointer is valid, so we can create a temporary ref = to set data. + let chip_ref =3D 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()) } + + // SAFETY: `chip_ptr_as_self` points to a valid `Chip` (layout-com= patible with + // `bindings::pwm_chip`) whose embedded device has refcount 1. + // `ARef::from_raw` takes this pointer and manages it via `AlwaysR= efCounted`. + Ok(unsafe { ARef::from_raw(NonNull::new_unchecked(chip_ptr_as_self= )) }) + } + + /// Gets the *typed* driver-specific data associated with this chip's = embedded device. + pub fn drvdata(&self) -> T::Borrowed<'_> { + // SAFETY: `self.as_raw()` gives a valid pwm_chip pointer. + // `bindings::pwmchip_get_drvdata` is the C function to retrieve d= river data. + let ptr =3D unsafe { bindings::pwmchip_get_drvdata(self.as_raw()) = }; + + // SAFETY: The only way to create a chip is through Chip::new, whi= ch initializes + // this pointer. + unsafe { T::borrow(ptr.cast()) } + } +} + +// SAFETY: Implements refcounting for `Chip` using the embedded `struct de= vice`. +unsafe impl AlwaysRefCounted for Chip { + #[inline] + fn inc_ref(&self) { + // SAFETY: `self.0.get()` points to a valid `pwm_chip` because `se= lf` exists. + // The embedded `dev` is valid. `get_device` increments its refcou= nt. + unsafe { bindings::get_device(&raw mut (*self.0.get()).dev); } + } + + #[inline] + unsafe fn dec_ref(obj: NonNull>) { + let c_chip_ptr =3D obj.cast::().as_ptr(); + + // SAFETY: `obj` is a valid pointer to a `Chip` (and thus `binding= s::pwm_chip`) + // with a non-zero refcount. `put_device` handles decrement and fi= nal release. + unsafe { bindings::put_device(&raw mut (*c_chip_ptr).dev); } + } +} + +// SAFETY: `Chip` is a wrapper around `*mut bindings::pwm_chip`. The under= lying C +// structure's state is managed and synchronized by the kernel's device mo= del +// and PWM core locking mechanisms. Therefore, it is safe to move the `Chi= p` +// wrapper (and the pointer it contains) across threads. +unsafe impl Send for Chip {} + +// SAFETY: It is safe for multiple threads to have shared access (`&Chip`)= because +// the `Chip` data is immutable from the Rust side without holding the app= ropriate +// kernel locks, which the C core is responsible for. Any interior mutabil= ity is +// handled and synchronized by the C kernel code. +unsafe impl Sync for Chip {} --=20 2.34.1