From nobody Thu Oct 9 13:19:09 2025 Received: from mailout1.w1.samsung.com (mailout1.w1.samsung.com [210.118.77.11]) (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 6CFFD2E7F1B for ; Tue, 17 Jun 2025 14:08:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=210.118.77.11 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169320; cv=none; b=YlQixkmDxFRVurPOcjxfs4YNl3rSBkyG0Z5Ku8q6iCWuZMu6336bW8V8/4cgqEZ+YPFfHXl1lGGcJmwEPe/8PIzg8XuCvF6yJtn1a/N9mAxa3p6CcPczV02tQO7PrUcqKNUcSH2wY8G9gkD7AEG1GwV/Fa9dcbFAxPOYtXcj00g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169320; c=relaxed/simple; bh=3x4XA8rVGvcqRMp60zC+GETWnoMG7/3bwXr/LsWy2A0=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=lWM9k3QcIHk5FueHh/Xoe5zinqyr1ielmRNSFMbPsgZd3nvy06H6hgJBFJTKSXbNQ4TzojU5xtjvZWrWgZdQmVXNovXqVi9SEsX5KVuEoZ5xtfPJpH6aBsFGAB263Jbj0D02RDpDS7WZJ8192jrHQdd0oJxZrahJdpSJrwgtFXg= 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=L82f03LB; arc=none smtp.client-ip=210.118.77.11 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="L82f03LB" Received: from eucas1p2.samsung.com (unknown [182.198.249.207]) by mailout1.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140836euoutp01da19183200ba28d1c177e0e4ac77acbd~J2biHs71Z2798627986euoutp01H for ; Tue, 17 Jun 2025 14:08:36 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout1.w1.samsung.com 20250617140836euoutp01da19183200ba28d1c177e0e4ac77acbd~J2biHs71Z2798627986euoutp01H DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169316; bh=J65JaRuGLW1MK7iS3wcUH4sUEKCN5P+oJvskSjmp6ks=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=L82f03LBoT+iBBVmFpUUR6v4ASOgp9PN7Mtz+zU/qy+RfiXwW2V1C64aJ7iTGt/mt b+x2gZZgKspweuoFzP0wJbla3Jfz+FFpvfYN0tzzLO1q8NCoA21LXbozaVo+kEMLz9 ZS3s1viGBGOhv+5d7+S8sj5vu9+7Jp8Bux8oy6Vw= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p2.samsung.com (KnoxPortal) with ESMTPA id 20250617140835eucas1p2f54c36c63fa7470724a6d027a81d73ff~J2bhECcFv1657216572eucas1p2s; Tue, 17 Jun 2025 14:08:35 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140834eusmtip16812335f79834953ba89f1c46df1cd87~J2bf7MMIK2596425964eusmtip1U; Tue, 17 Jun 2025 14:08:34 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:24 +0200 Subject: [PATCH v3 1/9] rust: pwm: Add Kconfig and basic data structures 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-1-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140835eucas1p2f54c36c63fa7470724a6d027a81d73ff X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140835eucas1p2f54c36c63fa7470724a6d027a81d73ff X-EPHeader: CA X-CMS-RootMailID: 20250617140835eucas1p2f54c36c63fa7470724a6d027a81d73ff References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Introduce the foundational support for PWM abstractions in Rust. This commit adds the `RUST_PWM_ABSTRACTIONS` Kconfig option to enable the feature, along with the necessary build-system support and C helpers. It also introduces the first set of safe wrappers for the PWM subsystem, covering the basic data carrying C structs and enums: - `Polarity`: A safe wrapper for `enum pwm_polarity`. - `Waveform`: A wrapper for `struct pwm_waveform`. - `Args`: A wrapper for `struct pwm_args`. - `State`: A wrapper for `struct pwm_state`. These types provide memory safe, idiomatic Rust representations of the core PWM data structures and form the building blocks for the abstractions that will follow. Signed-off-by: Michal Wilczynski --- MAINTAINERS | 6 ++ drivers/pwm/Kconfig | 13 +++ rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/kernel/lib.rs | 2 + rust/kernel/pwm.rs | 198 ++++++++++++++++++++++++++++++++++++= ++++ 6 files changed, 221 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 0c1d245bf7b84f8a78b811e0c9c5a3edc09edc22..a575622454a2ef57ce055c8a8c4= 765fa4fddc490 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -20073,6 +20073,12 @@ F: include/linux/pwm.h F: include/linux/pwm_backlight.h K: pwm_(config|apply_might_sleep|apply_atomic|ops) =20 +PWM SUBSYSTEM BINDINGS [RUST] +M: Michal Wilczynski +S: Maintained +F: rust/helpers/pwm.c +F: rust/kernel/pwm.rs + PXA GPIO DRIVER M: Robert Jarzmik L: linux-gpio@vger.kernel.org diff --git a/drivers/pwm/Kconfig b/drivers/pwm/Kconfig index d9bcd1e8413eaed1602d6686873e263767c58f5f..cfddeae0eab3523f04f361fb41c= cd1345c0c937b 100644 --- a/drivers/pwm/Kconfig +++ b/drivers/pwm/Kconfig @@ -790,4 +790,17 @@ config PWM_XILINX To compile this driver as a module, choose M here: the module will be called pwm-xilinx. =20 + config RUST_PWM_ABSTRACTIONS + bool "Rust PWM abstractions support" + depends on RUST + depends on PWM=3Dy + help + This option enables the safe Rust abstraction layer for the PWM + subsystem. It provides idiomatic wrappers and traits necessary for + writing PWM controller drivers in Rust. + + The abstractions handle resource management (like memory and reference + counting) and provide safe interfaces to the underlying C core, + allowing driver logic to be written in safe Rust. + endif diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 693cdd01f9290fa01375cf78cac0e5a90df74c6c..6fe7dd529577952bf7adb4fe052= 6b0d5fbd6f3bd 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -64,6 +64,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 16fa9bca5949b85e8d4cdcfe8e6886124f72d8d8..60879e6d794ce0f87e39caafc54= 95bf5e8acf8f0 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -31,6 +31,7 @@ #include "platform.c" #include "pci.c" #include "pid_namespace.c" +#include "pwm.c" #include "rbtree.c" #include "rcu.c" #include "refcount.c" diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 6b4774b2b1c37f4da1866e993be6230bc6715841..ce1d08b14e456905dbe7b625bbb= 8ca8b08deae2a 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -105,6 +105,8 @@ pub mod seq_file; pub mod sizes; mod static_assert; +#[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)] +pub mod pwm; #[doc(hidden)] pub mod std_vendor; pub mod str; diff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs new file mode 100644 index 0000000000000000000000000000000000000000..ed681b228c414e7ae8bf80ca649= ad497c9dc4ec3 --- /dev/null +++ b/rust/kernel/pwm.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-2.0 +// Copyright (c) 2025 Samsung Electronics Co., Ltd. +// Author: Michal Wilczynski + +//! PWM subsystem abstractions. +//! +//! C header: [`include/linux/pwm.h`](srctree/include/linux/pwm.h). + +use crate::{ + bindings, + prelude::*, + types::Opaque, +}; +use core::convert::TryFrom; + +/// Maximum size for the hardware-specific waveform representation buffer. +/// +/// From C: `#define WFHWSIZE 20` +pub const WFHW_MAX_SIZE: usize =3D 20; + +/// PWM polarity. Mirrors [`enum pwm_polarity`](srctree/include/linux/pwm.= h). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Polarity { + /// Normal polarity (duty cycle defines the high period of the signal). + Normal, + + /// Inversed polarity (duty cycle defines the low period of the signal= ). + Inversed, +} + +impl TryFrom for Polarity { + type Error =3D Error; + + fn try_from(polarity: bindings::pwm_polarity) -> Result { + match polarity { + bindings::pwm_polarity_PWM_POLARITY_NORMAL =3D> Ok(Polarity::N= ormal), + bindings::pwm_polarity_PWM_POLARITY_INVERSED =3D> Ok(Polarity:= :Inversed), + _ =3D> Err(EINVAL), + } + } +} + +impl From for bindings::pwm_polarity { + fn from(polarity: Polarity) -> Self { + match polarity { + Polarity::Normal =3D> bindings::pwm_polarity_PWM_POLARITY_NORM= AL, + Polarity::Inversed =3D> bindings::pwm_polarity_PWM_POLARITY_IN= VERSED, + } + } +} + +/// Represents a PWM waveform configuration. +/// Mirrors struct [`struct pwm_waveform`](srctree/include/linux/pwm.h). +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct Waveform { + /// Total duration of one complete PWM cycle, in nanoseconds. + pub period_length_ns: u64, + + /// Duty-cycle active time, in nanoseconds. + /// + /// For a typical normal polarity configuration (active-high) this is = the + /// high time of the signal. + pub duty_length_ns: u64, + + /// Duty-cycle start offset, in nanoseconds. + /// + /// Delay from the beginning of the period to the first active edge. + /// In most simple PWM setups this is `0`, so the duty cycle starts + /// immediately at each period=E2=80=99s start. + pub duty_offset_ns: u64, +} + +impl From for Waveform { + fn from(wf: bindings::pwm_waveform) -> Self { + Waveform { + period_length_ns: wf.period_length_ns, + duty_length_ns: wf.duty_length_ns, + duty_offset_ns: wf.duty_offset_ns, + } + } +} + +impl From for bindings::pwm_waveform { + fn from(wf: Waveform) -> Self { + bindings::pwm_waveform { + period_length_ns: wf.period_length_ns, + duty_length_ns: wf.duty_length_ns, + duty_offset_ns: wf.duty_offset_ns, + } + } +} + +/// Wrapper for board-dependent PWM arguments [`struct pwm_args`](srctree/= include/linux/pwm.h). +#[repr(transparent)] +pub struct Args(Opaque); + +impl Args { + /// Creates an `Args` wrapper from a C struct pointer. + /// + /// # Safety + /// + /// The caller must ensure that `c_args_ptr` is a valid, non-null poin= ter + /// to `bindings::pwm_args` and that the pointed-to data is valid + /// for the duration of this function call (as data is copied). + unsafe fn from_c_ptr(c_args_ptr: *const bindings::pwm_args) -> Self { + // SAFETY: Caller guarantees `c_args_ptr` is valid. We dereference= it to copy. + Args(Opaque::new(unsafe { *c_args_ptr })) + } + + /// Returns the period of the PWM signal in nanoseconds. + pub fn period(&self) -> u64 { + // SAFETY: `self.0.get()` returns a pointer to the `bindings::pwm_= args` + // managed by the `Opaque` wrapper. This pointer is guaranteed to = be + // valid and aligned for the lifetime of `self` because `Opaque` o= wns a copy. + unsafe { (*self.0.get()).period } + } + + /// Returns the polarity of the PWM signal. + pub fn polarity(&self) -> Result { + // SAFETY: `self.0.get()` returns a pointer to the `bindings::pwm_= args` + // managed by the `Opaque` wrapper. This pointer is guaranteed to = be + // valid and aligned for the lifetime of `self`. + let raw_polarity =3D unsafe { (*self.0.get()).polarity }; + Polarity::try_from(raw_polarity) + } +} + +/// Wrapper for PWM state [`struct pwm_state`](srctree/include/linux/pwm.h= ). +#[repr(transparent)] +pub struct State(bindings::pwm_state); + +impl Default for State { + fn default() -> Self { + Self::new() + } +} + +impl State { + /// Creates a new zeroed `State`. + pub fn new() -> Self { + State(bindings::pwm_state::default()) + } + + /// Creates a `State` wrapper by taking ownership of a C `pwm_state` v= alue. + pub(crate) fn from_c(c_state: bindings::pwm_state) -> Self { + State(c_state) + } + + /// Gets the period of the PWM signal in nanoseconds. + pub fn period(&self) -> u64 { + self.0.period + } + + /// Sets the period of the PWM signal in nanoseconds. + pub fn set_period(&mut self, period_ns: u64) { + self.0.period =3D period_ns; + } + + /// Gets the duty cycle of the PWM signal in nanoseconds. + pub fn duty_cycle(&self) -> u64 { + self.0.duty_cycle + } + + /// Sets the duty cycle of the PWM signal in nanoseconds. + pub fn set_duty_cycle(&mut self, duty_ns: u64) { + self.0.duty_cycle =3D duty_ns; + } + + /// Returns `true` if the PWM signal is enabled. + pub fn enabled(&self) -> bool { + self.0.enabled + } + + /// Sets the enabled state of the PWM signal. + pub fn set_enabled(&mut self, enabled: bool) { + self.0.enabled =3D enabled; + } + + /// Gets the polarity of the PWM signal. + pub fn polarity(&self) -> Result { + Polarity::try_from(self.0.polarity) + } + + /// Sets the polarity of the PWM signal. + pub fn set_polarity(&mut self, polarity: Polarity) { + self.0.polarity =3D polarity.into(); + } + + /// Returns `true` if the PWM signal is configured for power usage hin= t. + pub fn usage_power(&self) -> bool { + self.0.usage_power + } + + /// Sets the power usage hint for the PWM signal. + pub fn set_usage_power(&mut self, usage_power: bool) { + self.0.usage_power =3D usage_power; + } +} --=20 2.34.1 From nobody Thu Oct 9 13:19:09 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 E5E192E88A5 for ; Tue, 17 Jun 2025 14:08:40 +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=1750169323; cv=none; b=YR+/2PtkXGQs0+y6PcGKMkDoUg+ATVsSrxtU7XTE377TVdL434Qnn9A73aQwDosDIA13rBrH2VW4AQqOk5O5EhYdakOz5bUtzQPXj9ImIQ5nJbAaPWv2rH8i3PWk4dtl55b/15QZAKo1HeBQLgdsrR6bngXFbO6U8+7dE683ld8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169323; c=relaxed/simple; bh=ju74EzJTUXYF36RcUpC17pYuS1lChtpc175U1ulUcNc=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=lBKDVU1SPuSOHyRv+Oqwe+30hLeaMsHn1Xj3tu7JRb84XKk7JPDVs3ey5gBM2b9CCiY1mHa8tzugBXRGhrs/jNtephYhgOwApkGleF8UbHf/S6lKrH24SQLqIa+Msh20MP8zuURM8cPwDTbnZnU5CQ8Yk0mu8fJJfjBPATf+Nmc= 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=FMJ7/DP2; 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="FMJ7/DP2" Received: from eucas1p2.samsung.com (unknown [182.198.249.207]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140837euoutp022efa61f384bb0e6eeaf532a573e5e1a4~J2bi_a-Jz0211802118euoutp02_ for ; Tue, 17 Jun 2025 14:08:37 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250617140837euoutp022efa61f384bb0e6eeaf532a573e5e1a4~J2bi_a-Jz0211802118euoutp02_ DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169317; bh=qO3jU7spwp9AnsPu6rlaK9fzxjqj1cRECEod63pnXa0=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=FMJ7/DP2nk9W7Lw/N8GJcJEa1OGw+jt2V1rFSejISYpNfxdudyMFMUoGzcZpSHBj6 gjAxojbL/LRW+rXwvs1aspRaJgqvsHDfaDfAH/JgjyLaLerRUz/OGnCea88WH3EXWS eFwafNTzcYEHYw0v6XGY9EFwkf4a1MXesF0YWnxE= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p1.samsung.com (KnoxPortal) with ESMTPA id 20250617140836eucas1p1531fccff82c0fcec217ca3526ae09124~J2biTJd7d0447904479eucas1p19; Tue, 17 Jun 2025 14:08:36 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140835eusmtip1f182b6f740177efd358f7dc18d1468f8~J2bhITtQI2854428544eusmtip1I; Tue, 17 Jun 2025 14:08:35 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:25 +0200 Subject: [PATCH v3 2/9] 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-2-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140836eucas1p1531fccff82c0fcec217ca3526ae09124 X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140836eucas1p1531fccff82c0fcec217ca3526ae09124 X-EPHeader: CA X-CMS-RootMailID: 20250617140836eucas1p1531fccff82c0fcec217ca3526ae09124 References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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. - 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. Signed-off-by: Michal Wilczynski --- rust/kernel/pwm.rs | 227 +++++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 225 insertions(+), 2 deletions(-) diff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs index ed681b228c414e7ae8bf80ca649ad497c9dc4ec3..8c4c27a4e4fc9da2fc8ea5015df= 2a315cfc6b932 100644 --- a/rust/kernel/pwm.rs +++ b/rust/kernel/pwm.rs @@ -8,10 +8,12 @@ =20 use crate::{ bindings, + device, + error, prelude::*, - types::Opaque, + types::{ARef, AlwaysRefCounted, ForeignOwnable, Opaque}, }; -use core::convert::TryFrom; +use core::{convert::TryFrom, ptr::NonNull}; =20 /// Maximum size for the hardware-specific waveform representation buffer. /// @@ -196,3 +198,224 @@ pub fn set_usage_power(&mut self, usage_power: bool) { self.0.usage_power =3D usage_power; } } + +/// Wrapper for a PWM device [`struct pwm_device`](srctree/include/linux/p= wm.h). +#[repr(transparent)] +pub struct Device(Opaque); + +impl Device { + /// Creates a temporary `&mut Device` from a raw C pointer for use in = callbacks. + /// + /// It returns a mutable reference (`&mut Self`) because the underlyin= g C APIs + /// for PWM operations use non-const pointers (`struct pwm_device *`).= This + /// signals that the functions in the vtable are permitted to mutate t= he + /// device's state (e.g., by writing to hardware registers). Using `&m= ut` + /// allows the `PwmOps` trait to accurately model this behavior and le= verage + /// Rust's aliasing rules for greater safety. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is a valid, non-null pointer to + /// `bindings::pwm_device` that is properly initialized. + /// The `pwm_device` must remain valid for the lifetime `'a`. + /// The caller must also ensure that Rust's aliasing rules are upheld. + pub(crate) unsafe fn from_ptr<'a>(ptr: *mut bindings::pwm_device) -> &= 'a mut Self { + // SAFETY: Caller guarantees `ptr` is valid and meets lifetime/ali= asing. + // `Self` is `#[repr(transparent)]`, so casting is valid. + unsafe { &mut *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::from_ptr's safety conditions must be met. + unsafe { Chip::from_ptr((*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 }) + } + + /// Returns `true` if the PWM signal is currently enabled based on its= state. + pub fn is_enabled(&self) -> bool { + self.state().enabled() + } +} + +/// Wrapper for a PWM chip/controller ([`struct pwm_chip`](srctree/include= /linux/pwm.h)). +#[repr(transparent)] +pub struct Chip(Opaque); + +impl Chip { + /// Creates a temporary `&mut Chip` from a raw C pointer for use in ca= llbacks. + /// + /// It returns a mutable reference (`&mut Self`) because the underlyin= g C APIs + /// for PWM operations use non-const pointers (`struct pwm_chip *`). T= his + /// signals that the functions in the vtable are permitted to mutate t= he + /// chip's state (e.g., by calling `set_drvdata` or through operations= that + /// modify hardware registers). Using `&mut` is essential for these ca= ses. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is a valid, non-null pointer to + /// `bindings::pwm_chip` that is properly initialized. + /// The `pwm_chip` must remain valid for the lifetime `'a`. + /// The caller must also ensure that Rust's aliasing rules are upheld. + pub(crate) unsafe fn from_ptr<'a>(ptr: *mut bindings::pwm_chip) -> &'a= mut Self { + // SAFETY: Caller guarantees `ptr` is valid and meets lifetime/ali= asing. + // `Self` is `#[repr(transparent)]`, so casting is valid. + unsafe { &mut *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`. + let dev_field_ptr =3D unsafe { core::ptr::addr_of!((*self.as_raw()= ).dev) }; + // SAFETY: `dev_field_ptr` is a valid pointer to `bindings::device= `. + // Casting and dereferencing is safe due to `repr(transparent)` an= d lifetime. + unsafe { &*(dev_field_ptr.cast::()) } + } + + /// Returns a reference to the parent device of this PWM chip's device. + pub fn parent_device(&self) -> Option<&device::Device> { + self.device().parent() + } + + /// Gets the *typed* driver-specific data associated with this chip's = embedded device. + pub fn drvdata(&self) -> Option<&T> { + // 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()) = }; + if ptr.is_null() { + None + } else { + // SAFETY: `ptr` is non-null. Caller ensures `T` is the correc= t type. + // Lifetime of data is managed by the driver that set it. + unsafe { Some(&*(ptr.cast::())) } + } + } + + /// Sets the *typed* driver-specific data associated with this chip's = embedded device. + pub fn set_drvdata(&self, data: T) { + // SAFETY: `self.as_raw()` gives a valid pwm_chip pointer. + // `bindings::pwmchip_set_drvdata` is the C function to set driver= data. + // `data.into_foreign()` provides a valid `*mut c_void`. + unsafe { bindings::pwmchip_set_drvdata(self.as_raw(), data.into_fo= reign().cast()) } + } + + /// 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)= -> 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: `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= )) }) + } +} + +// 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(core::ptr::addr_of_mut!((*self.0.get()).d= ev)); + } + } + + #[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(core::ptr::addr_of_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 From nobody Thu Oct 9 13:19:09 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 5D1C92E7F1D for ; Tue, 17 Jun 2025 14:08:41 +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=1750169324; cv=none; b=SFSGerQ1hK4uzjQ+H8D4FAEDHDLJigjqLIe3kZV2zNh/WlQng/Y+RcjCLICBcAEmPmgW/ElMpZBTiJH9+Ex+3rdOU7P9yRmnmduK7KCogsuQddqNNUS84Cpt61iF4g98BQx/P3V94ZctLf+jF1CbwuUoDAYfZhrGQ2cKSj7PzC4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169324; c=relaxed/simple; bh=PqPmG7LLWKvnVKOK34Udaecl39RMqDb2VheKIq5I+RM=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=akEPfZK4PLj7phHKl5MxRdGPbobzY/dOUIMi1Ga5+UMVszUGnQ0qNnDdqKHPxcEvF7lewP0VTbNmwQKssZrTews6RXKVHgjKeybwyjFWnRA4EQ4SK6qfPEc8LS/+y0gGXPvfigVPtPrBL2NARc7RtfcgyFOx6mSGmolKGVD4+UI= 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=buWb5B0X; 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="buWb5B0X" Received: from eucas1p1.samsung.com (unknown [182.198.249.206]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140839euoutp023d39d79c036914046c85b0ce91933c36~J2bkXYwZP0208502085euoutp028 for ; Tue, 17 Jun 2025 14:08:39 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250617140839euoutp023d39d79c036914046c85b0ce91933c36~J2bkXYwZP0208502085euoutp028 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169319; bh=HLGeBBxVh4s0amVT/Rdjdx5pFJtAmPQ9fVS1AXrdlMc=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=buWb5B0X4ad8hr+YSOoN9fzlMT8HpgN/2lGeLJoP9LCa3XLVlaIMjWABW8MRZIN7t TWgeG+/B0m/fOPNFTqGrB7iifdOJoEIfwGbOTzc4SdKGEzN3SauEjQX7erTSv3aTth SJwY2p9aOVnuAu6q0AT14DAW6mnwZwacfXJ4z8Tw= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p2.samsung.com (KnoxPortal) with ESMTPA id 20250617140838eucas1p2a31af5a73297580c2421263c1c6ba700~J2bjpps3Z1901919019eucas1p28; Tue, 17 Jun 2025 14:08:38 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140837eusmtip19080d4986e3ed16c4afcd038c58f6574~J2biW8HbF2540625406eusmtip1J; Tue, 17 Jun 2025 14:08:37 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:26 +0200 Subject: [PATCH v3 3/9] rust: pwm: Add driver operations trait and registration support 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-3-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140838eucas1p2a31af5a73297580c2421263c1c6ba700 X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140838eucas1p2a31af5a73297580c2421263c1c6ba700 X-EPHeader: CA X-CMS-RootMailID: 20250617140838eucas1p2a31af5a73297580c2421263c1c6ba700 References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Complete the PWM abstraction layer by adding the final components required to implement and register a driver. The main additions are: - PwmOps Trait: An interface that drivers can implement to provide their hardware specific logic. It mirrors the C pwm_ops interface, providing hooks for standard PWM operations like apply, request, and waveform handling. - FFI VTable and Adapter: The Adapter struct, PwmOpsVTable wrapper, and create_pwm_ops function are introduced. This scaffolding handles the unsafe FFI translation, bridging the gap between the idiomatic PwmOps trait and the C kernel's function-pointer-based vtable. - Registration Guard: A final RAII guard that uses the vtable to safely register a Chip with the PWM core via pwmchip_add. Its Drop implementation guarantees that pwmchip_remove is always called, preventing resource leaks. With this patch, the PWM abstraction layer is now complete and ready to be used for writing PWM chip drivers in Rust. Signed-off-by: Michal Wilczynski --- rust/kernel/pwm.rs | 471 +++++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 468 insertions(+), 3 deletions(-) diff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs index 8c4c27a4e4fc9da2fc8ea5015df2a315cfc6b932..64210411450cd3d964d21f1e712= fcfd4d8aed988 100644 --- a/rust/kernel/pwm.rs +++ b/rust/kernel/pwm.rs @@ -8,12 +8,12 @@ =20 use crate::{ bindings, - device, - error, + device::{self, Bound}, + error::{self, to_result}, prelude::*, types::{ARef, AlwaysRefCounted, ForeignOwnable, Opaque}, }; -use core::{convert::TryFrom, ptr::NonNull}; +use core::{convert::TryFrom, marker::PhantomData, mem::ManuallyDrop, ptr::= NonNull}; =20 /// Maximum size for the hardware-specific waveform representation buffer. /// @@ -419,3 +419,468 @@ unsafe impl Send for Chip {} // 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 {} + +/// Manages the registration of a PWM chip, ensuring `pwmchip_remove` is c= alled on drop. +pub struct Registration { + chip: ManuallyDrop>, +} + +impl Registration { + /// Registers a PWM chip (obtained via `Chip::new`) with the PWM subsy= stem. + /// + /// Takes an [`ARef`]. On `Drop` of the returned `Registration` = object, + /// `pwmchip_remove` is called for the chip. + pub fn new(chip: ARef, ops_vtable: &'static PwmOpsVTable) -> Res= ult { + // Get the raw C pointer from ARef. + let c_chip_ptr =3D chip.as_raw().cast::(); + + // SAFETY: `c_chip_ptr` is valid (guaranteed by ARef existing). + // `ops_vtable.as_raw()` provides a valid `*const bindings::pwm_op= s`. + // `bindings::__pwmchip_add` preconditions (valid pointers, ops se= t on chip) are met. + unsafe { + (*c_chip_ptr).ops =3D ops_vtable.as_raw(); + to_result(bindings::__pwmchip_add(c_chip_ptr, core::ptr::null_= mut()))?; + } + Ok(Registration { + chip: ManuallyDrop::new(chip), + }) + } +} + +impl Drop for Registration { + fn drop(&mut self) { + let chip =3D &**self.chip; + let chip_raw: *mut bindings::pwm_chip =3D chip.as_raw(); + + // SAFETY: `chip_raw` points to a chip that was successfully regis= tered via `Self::new`. + // `bindings::pwmchip_remove` is the correct C function to unregis= ter it. + unsafe { + bindings::pwmchip_remove(chip_raw); + ManuallyDrop::drop(&mut self.chip); // Drops the ARef + } + } +} + +/// Trait defining the operations for a PWM driver. +pub trait PwmOps: 'static + Sized { + /// The driver-specific hardware representation of a waveform. + /// + /// This type must be [`Copy`], [`Default`], and fit within [`WFHW_MAX= _SIZE`]. + type WfHw: Copy + Default; + + /// Optional hook to atomically apply a new PWM config. + fn apply( + _chip: &mut Chip, + _pwm: &mut Device, + _state: &State, + _parent_dev: &device::Device, + ) -> Result { + Err(ENOTSUPP) + } + + /// Optional hook for when a PWM device is requested. + fn request(_chip: &mut Chip, _pwm: &mut Device, _parent_dev: &device::= Device) -> Result { + Ok(()) + } + + /// Optional hook for when a PWM device is freed. + fn free(_chip: &mut Chip, _pwm: &mut Device, _parent_dev: &device::Dev= ice) {} + + /// Optional hook for capturing a PWM signal. + fn capture( + _chip: &mut Chip, + _pwm: &mut Device, + _result: &mut bindings::pwm_capture, + _timeout: usize, + _parent_dev: &device::Device, + ) -> Result { + Err(ENOTSUPP) + } + + /// Optional hook to get the current hardware state. + fn get_state( + _chip: &mut Chip, + _pwm: &mut Device, + _state: &mut State, + _parent_dev: &device::Device, + ) -> Result { + Err(ENOTSUPP) + } + + /// Convert a generic waveform to the hardware-specific representation. + /// This is typically a pure calculation and does not perform I/O. + fn round_waveform_tohw( + _chip: &mut Chip, + _pwm: &mut Device, + _wf: &Waveform, + ) -> Result<(c_int, Self::WfHw)> { + Err(ENOTSUPP) + } + + /// Convert a hardware-specific representation back to a generic wavef= orm. + /// This is typically a pure calculation and does not perform I/O. + fn round_waveform_fromhw( + _chip: &mut Chip, + _pwm: &Device, + _wfhw: &Self::WfHw, + _wf: &mut Waveform, + ) -> Result { + Err(ENOTSUPP) + } + + /// Read the current hardware configuration into the hardware-specific= representation. + fn read_waveform( + _chip: &mut Chip, + _pwm: &mut Device, + _parent_dev: &device::Device, + ) -> Result { + Err(ENOTSUPP) + } + + /// Write a hardware-specific waveform configuration to the hardware. + fn write_waveform( + _chip: &mut Chip, + _pwm: &mut Device, + _wfhw: &Self::WfHw, + _parent_dev: &device::Device, + ) -> Result { + Err(ENOTSUPP) + } +} +/// Bridges Rust `PwmOps` to the C `pwm_ops` vtable. +struct Adapter { + _p: PhantomData, +} + +impl Adapter { + /// # Safety + /// + /// `wfhw_ptr` must be valid for writes of `size_of::()` byte= s. + unsafe fn serialize_wfhw(wfhw: &T::WfHw, wfhw_ptr: *mut c_void) -> Res= ult { + let size =3D core::mem::size_of::(); + if size > WFHW_MAX_SIZE { + return Err(EINVAL); + } + + // SAFETY: The caller ensures `wfhw_ptr` is valid for `size` bytes. + unsafe { + core::ptr::copy_nonoverlapping(wfhw as *const _ as *const u8, = wfhw_ptr.cast(), size); + } + + Ok(()) + } + + /// # Safety + /// + /// `wfhw_ptr` must be valid for reads of `size_of::()` bytes. + unsafe fn deserialize_wfhw(wfhw_ptr: *const c_void) -> Result= { + let size =3D core::mem::size_of::(); + if size > WFHW_MAX_SIZE { + return Err(EINVAL); + } + + let mut wfhw =3D T::WfHw::default(); + // SAFETY: The caller ensures `wfhw_ptr` is valid for `size` bytes. + unsafe { + core::ptr::copy_nonoverlapping(wfhw_ptr.cast(), &mut wfhw as *= mut _ as *mut u8, size); + } + + Ok(wfhw) + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn apply_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + s: *const bindings::pwm_state, + ) -> c_int { + // SAFETY: This block relies on the function's safety contract: th= e C caller + // provides valid pointers. `Chip::from_ptr` and `Device::from_ptr= ` are `unsafe fn` + // whose preconditions are met by this contract. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return EINVAL.to_errno(); + } + }; + + // SAFETY: The PWM core guarantees callbacks only happen on a live= , bound device. + let bound_parent =3D + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + + // SAFETY: The state provided by the callback is guaranteed to be = valid + let state =3D State::from_c(unsafe { *s }); + match T::apply(chip, pwm, &state, bound_parent) { + Ok(()) =3D> 0, + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn request_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + ) -> c_int { + // SAFETY: PWM core guarentees `c` and `p` are valid pointers. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return EINVAL.to_errno(); + } + }; + + let bound_parent =3D + // SAFETY: The PWM core guarantees the device is bound during callbacks. + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + match T::request(chip, pwm, bound_parent) { + Ok(()) =3D> 0, + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn free_callback(c: *mut bindings::pwm_chip, p: *mut= bindings::pwm_device) { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return; + } + }; + + let bound_parent =3D + // SAFETY: The PWM core guarantees the device is bound during callbacks. + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + T::free(chip, pwm, bound_parent); + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn capture_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + res: *mut bindings::pwm_capture, + timeout: usize, + ) -> c_int { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm, result) =3D unsafe { (Chip::from_ptr(c), Device::f= rom_ptr(p), &mut *res) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return EINVAL.to_errno(); + } + }; + + let bound_parent =3D + // SAFETY: The PWM core guarantees the device is bound during cal= lbacks. + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + match T::capture(chip, pwm, result, timeout, bound_parent) { + Ok(()) =3D> 0, + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn get_state_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + s: *mut bindings::pwm_state, + ) -> c_int { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return EINVAL.to_errno(); + } + }; + let bound_parent =3D + // SAFETY: The PWM core guarantees the device is bound during callbacks. + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + let mut rust_state =3D State::new(); + match T::get_state(chip, pwm, &mut rust_state, bound_parent) { + Ok(()) =3D> { + // SAFETY: `s` is guaranteed valid by the C caller. + unsafe { + *s =3D rust_state.0; + }; + 0 + } + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn round_waveform_tohw_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + w: *const bindings::pwm_waveform, + wh: *mut c_void, + ) -> c_int { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm, wf) =3D + unsafe { (Chip::from_ptr(c), Device::from_ptr(p), Waveform::fr= om(*w)) }; + match T::round_waveform_tohw(chip, pwm, &wf) { + Ok((status, wfhw)) =3D> { + // SAFETY: `wh` is valid per this function's safety contra= ct. + if unsafe { Self::serialize_wfhw(&wfhw, wh) }.is_err() { + return EINVAL.to_errno(); + } + status + } + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn round_waveform_fromhw_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + wh: *const c_void, + w: *mut bindings::pwm_waveform, + ) -> c_int { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + // SAFETY: `deserialize_wfhw`'s safety contract is met by this fun= ction's contract. + let wfhw =3D match unsafe { Self::deserialize_wfhw(wh) } { + Ok(v) =3D> v, + Err(e) =3D> return e.to_errno(), + }; + + let mut rust_wf =3D Waveform::default(); + match T::round_waveform_fromhw(chip, pwm, &wfhw, &mut rust_wf) { + Ok(ret) =3D> { + // SAFETY: `w` is guaranteed valid by the C caller. + unsafe { + *w =3D rust_wf.into(); + }; + ret + } + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn read_waveform_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + wh: *mut c_void, + ) -> c_int { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return EINVAL.to_errno(); + } + }; + + let bound_parent =3D + // SAFETY: The PWM core guarantees the device is bound during callbacks. + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + match T::read_waveform(chip, pwm, bound_parent) { + // SAFETY: `wh` is valid per this function's safety contract. + Ok(wfhw) =3D> match unsafe { Self::serialize_wfhw(&wfhw, wh) }= { + Ok(()) =3D> 0, + Err(e) =3D> e.to_errno(), + }, + Err(e) =3D> e.to_errno(), + } + } + + /// # Safety + /// + /// Pointers from C must be valid. + unsafe extern "C" fn write_waveform_callback( + c: *mut bindings::pwm_chip, + p: *mut bindings::pwm_device, + wh: *const c_void, + ) -> c_int { + // SAFETY: Relies on the function's contract that `c` and `p` are = valid pointers. + let (chip, pwm) =3D unsafe { (Chip::from_ptr(c), Device::from_ptr(= p)) }; + let parent_dev =3D match chip.parent_device() { + Some(dev) =3D> dev, + None =3D> { + return EINVAL.to_errno(); + } + }; + + let bound_parent =3D + // SAFETY: The PWM core guarantees the device is bound during cal= lbacks. + unsafe { &*(parent_dev as *const device::Device as *const devi= ce::Device) }; + // SAFETY: `wh` is valid per this function's safety contract. + let wfhw =3D match unsafe { Self::deserialize_wfhw(wh) } { + Ok(v) =3D> v, + Err(e) =3D> return e.to_errno(), + }; + match T::write_waveform(chip, pwm, &wfhw, bound_parent) { + Ok(()) =3D> 0, + Err(e) =3D> e.to_errno(), + } + } +} + +/// VTable structure wrapper for PWM operations. +/// Mirrors [`struct pwm_ops`](srctree/include/linux/pwm.h). +#[repr(transparent)] +pub struct PwmOpsVTable(Opaque); + +// SAFETY: PwmOpsVTable is Send. The vtable contains only function pointers +// and a size, which are simple data types that can be safely moved across +// threads. The thread-safety of calling these functions is handled by the +// kernel's locking mechanisms. +unsafe impl Send for PwmOpsVTable {} + +// SAFETY: PwmOpsVTable is Sync. The vtable is immutable after it is creat= ed, +// so it can be safely referenced and accessed concurrently by multiple th= reads +// e.g. to read the function pointers. +unsafe impl Sync for PwmOpsVTable {} + +impl PwmOpsVTable { + /// Returns a raw pointer to the underlying `pwm_ops` struct. + pub(crate) fn as_raw(&self) -> *const bindings::pwm_ops { + self.0.get() + } +} + +/// Creates a PWM operations vtable for a type `T` that implements `PwmOps= `. +/// +/// This is used to bridge Rust trait implementations to the C `struct pwm= _ops` +/// expected by the kernel. +pub const fn create_pwm_ops() -> PwmOpsVTable { + // SAFETY: `core::mem::zeroed()` is unsafe. For `pwm_ops`, all fields = are + // `Option` or data, so a zeroed pattern (None/0) = is valid initially. + let mut ops: bindings::pwm_ops =3D unsafe { core::mem::zeroed() }; + + ops.apply =3D Some(Adapter::::apply_callback); + ops.request =3D Some(Adapter::::request_callback); + ops.free =3D Some(Adapter::::free_callback); + ops.capture =3D Some(Adapter::::capture_callback); + ops.get_state =3D Some(Adapter::::get_state_callback); + + ops.round_waveform_tohw =3D Some(Adapter::::round_waveform_tohw_cal= lback); + ops.round_waveform_fromhw =3D Some(Adapter::::round_waveform_fromhw= _callback); + ops.read_waveform =3D Some(Adapter::::read_waveform_callback); + ops.write_waveform =3D Some(Adapter::::write_waveform_callback); + ops.sizeof_wfhw =3D core::mem::size_of::(); + + PwmOpsVTable(Opaque::new(ops)) +} --=20 2.34.1 From nobody Thu Oct 9 13:19:09 2025 Received: from mailout1.w1.samsung.com (mailout1.w1.samsung.com [210.118.77.11]) (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 07A332E92DE for ; Tue, 17 Jun 2025 14:08:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=210.118.77.11 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169326; cv=none; b=MiI5JVseDFaSHkPP1q+v2P7R71CRvuPEs5HR7PEvj7dyaaue9NATiah/D0R7Zsc4i+XVFd4MoZyfXEp4pgrOcrpWkMrnP1uFuCcdx402vcng2ziN6QgfhAIRi/XCuHlXADXB9dvX4P+LmNZb7v4kdpMf/e1ae+BBJwXFtV70yBs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169326; c=relaxed/simple; bh=eOTeNlAWL/NZ6JtTCr5bYb+W3ctzCCOe0/FkvuBwsLo=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=S2zmuE4sPZbvzDJd3kIsJR6VGyDkNKPEVG8st8jx1BRcuwMLSb2sLOeqLL/F9bg68wmXaloP7ctbES09Ju5q/rf2JAbxwilzt2FpD+N1lWv1KYjt5NCwOGCwrwMAxLK5qBKd8DiSIUFnbU7h3Qpp9j6/DC5TTEsnPt9KndlRjZI= 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=EgrQU47M; arc=none smtp.client-ip=210.118.77.11 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="EgrQU47M" Received: from eucas1p1.samsung.com (unknown [182.198.249.206]) by mailout1.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140840euoutp0114939c9533917470c418921fbda4b6c4~J2blWsWSE2798627986euoutp01L for ; Tue, 17 Jun 2025 14:08:40 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout1.w1.samsung.com 20250617140840euoutp0114939c9533917470c418921fbda4b6c4~J2blWsWSE2798627986euoutp01L DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169320; bh=BT1lMq6lahvT/o04lTM4nrNGxThufjSeoMSMdHevWBM=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=EgrQU47MvIdBnBpTVNWVNFgsvE02ohN3SYu7g0eiXKtpB3UcWU0K89+dzn9t1ljCZ RqVA46TEmrM80nD5mzf42nKWQ94EqkET9eo7UXcYEzEkZUQrPN3LkMpSL7qXE4goAw ZxLbAkbW6Kp90g4VsX2aFT+J5G/ZOfv1lEA/uV+0= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p2.samsung.com (KnoxPortal) with ESMTPA id 20250617140839eucas1p2d13775f8e6d34a516e93d3b426d5fb16~J2bkv477M2188521885eucas1p2z; Tue, 17 Jun 2025 14:08:39 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140838eusmtip1eb10904b9006886acf2ae30694f494d7~J2bjmNhYH2516525165eusmtip1C; Tue, 17 Jun 2025 14:08:38 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:27 +0200 Subject: [PATCH v3 4/9] pwm: Add Rust driver for T-HEAD TH1520 SoC 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-4-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140839eucas1p2d13775f8e6d34a516e93d3b426d5fb16 X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140839eucas1p2d13775f8e6d34a516e93d3b426d5fb16 X-EPHeader: CA X-CMS-RootMailID: 20250617140839eucas1p2d13775f8e6d34a516e93d3b426d5fb16 References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Introduce a PWM driver for the T-HEAD TH1520 SoC, written in Rust and utilizing the safe PWM abstractions from the preceding commit. The driver implements the pwm::PwmOps trait using the modern waveform API (round_waveform_tohw, write_waveform, etc.) to support configuration of period, duty cycle, and polarity for the TH1520's PWM channels. Resource management is handled using idiomatic Rust patterns. The PWM chip object is allocated via pwm::Chip::new and its registration with the PWM core is managed by the pwm::Registration RAII guard. This ensures pwmchip_remove is always called when the driver unbinds, preventing resource leaks. Device managed resources are used for the MMIO region, and the clock lifecycle is correctly managed in the driver's private data Drop implementation. The driver's core logic is written entirely in safe Rust, with no unsafe blocks. Signed-off-by: Michal Wilczynski --- MAINTAINERS | 1 + drivers/pwm/Kconfig | 10 ++ drivers/pwm/Makefile | 1 + drivers/pwm/pwm_th1520.rs | 328 ++++++++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 340 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index a575622454a2ef57ce055c8a8c4765fa4fddc490..879870471e86dcec4a0e8f5c45d= 2cc3409411fdd 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -21402,6 +21402,7 @@ F: drivers/mailbox/mailbox-th1520.c F: drivers/net/ethernet/stmicro/stmmac/dwmac-thead.c F: drivers/pinctrl/pinctrl-th1520.c F: drivers/pmdomain/thead/ +F: drivers/pwm/pwm_th1520.rs F: drivers/reset/reset-th1520.c F: include/dt-bindings/clock/thead,th1520-clk-ap.h F: include/dt-bindings/power/thead,th1520-power.h diff --git a/drivers/pwm/Kconfig b/drivers/pwm/Kconfig index cfddeae0eab3523f04f361fb41ccd1345c0c937b..a675b3bd68392d1b05a47a2a139= 0c5606647ca15 100644 --- a/drivers/pwm/Kconfig +++ b/drivers/pwm/Kconfig @@ -719,6 +719,16 @@ config PWM_TEGRA To compile this driver as a module, choose M here: the module will be called pwm-tegra. =20 +config PWM_TH1520 + tristate "TH1520 PWM support" + depends on RUST_PWM_ABSTRACTIONS + help + This option enables the driver for the PWM controller found on the + T-HEAD TH1520 SoC. + + To compile this driver as a module, choose M here; the module + will be called pwm-th1520. If you are unsure, say N. + config PWM_TIECAP tristate "ECAP PWM support" depends on ARCH_OMAP2PLUS || ARCH_DAVINCI_DA8XX || ARCH_KEYSTONE || ARCH_= K3 || COMPILE_TEST diff --git a/drivers/pwm/Makefile b/drivers/pwm/Makefile index 96160f4257fcb0e0951581af0090615c0edf5260..a410747095327a315a6bcd24ae3= 43ce7857fe323 100644 --- a/drivers/pwm/Makefile +++ b/drivers/pwm/Makefile @@ -66,6 +66,7 @@ obj-$(CONFIG_PWM_STMPE) +=3D pwm-stmpe.o obj-$(CONFIG_PWM_SUN4I) +=3D pwm-sun4i.o obj-$(CONFIG_PWM_SUNPLUS) +=3D pwm-sunplus.o obj-$(CONFIG_PWM_TEGRA) +=3D pwm-tegra.o +obj-$(CONFIG_PWM_TH1520) +=3D pwm_th1520.o obj-$(CONFIG_PWM_TIECAP) +=3D pwm-tiecap.o obj-$(CONFIG_PWM_TIEHRPWM) +=3D pwm-tiehrpwm.o obj-$(CONFIG_PWM_TWL) +=3D pwm-twl.o diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs new file mode 100644 index 0000000000000000000000000000000000000000..7869a118be94068861a64346258= 732aeec13a521 --- /dev/null +++ b/drivers/pwm/pwm_th1520.rs @@ -0,0 +1,328 @@ +// SPDX-License-Identifier: GPL-2.0 +// Copyright (c) 2025 Samsung Electronics Co., Ltd. +// Author: Michal Wilczynski + +//! Rust T-HEAD TH1520 PWM driver +//! +//! Limitations: +//! - The period and duty cycle are controlled by 32-bit hardware register= s, +//! limiting the maximum resolution. +//! - The driver supports continuous output mode only; one-shot mode is not +//! implemented. +//! - The controller hardware provides up to 6 PWM channels. +//! + +use core::ops::Deref; +use kernel::{ + c_str, + clk::Clk, + device::{Bound, Core, Device}, + devres, + io::mem::IoMem, + of, platform, + prelude::*, + pwm, time, +}; + +const MAX_PWM_NUM: u32 =3D 6; + +// Register offsets +const fn th1520_pwm_chn_base(n: u32) -> usize { + (n * 0x20) as usize +} + +const fn th1520_pwm_ctrl(n: u32) -> usize { + th1520_pwm_chn_base(n) +} + +const fn th1520_pwm_per(n: u32) -> usize { + th1520_pwm_chn_base(n) + 0x08 +} + +const fn th1520_pwm_fp(n: u32) -> usize { + th1520_pwm_chn_base(n) + 0x0c +} + +// Control register bits +const PWM_START: u32 =3D 1 << 0; +const PWM_CFG_UPDATE: u32 =3D 1 << 2; +const PWM_CONTINUOUS_MODE: u32 =3D 1 << 5; +const PWM_FPOUT: u32 =3D 1 << 8; + +const TH1520_PWM_REG_SIZE: usize =3D 0xB0; + +fn ns_to_cycles(ns: u64, rate_hz: u64) -> u64 { + const NSEC_PER_SEC_U64: u64 =3D time::NSEC_PER_SEC as u64; + + match ns.checked_mul(rate_hz) { + Some(product) =3D> product / NSEC_PER_SEC_U64, + None =3D> u64::MAX, + } +} + +fn cycles_to_ns(cycles: u64, rate_hz: u64) -> u64 { + const NSEC_PER_SEC_U64: u64 =3D time::NSEC_PER_SEC as u64; + + // Round up + let Some(numerator) =3D cycles + .checked_mul(NSEC_PER_SEC_U64) + .and_then(|p| p.checked_add(rate_hz - 1)) + else { + return u64::MAX; + }; + + numerator / rate_hz +} + +/// Hardware-specific waveform representation for TH1520. +#[derive(Copy, Clone, Debug, Default)] +struct Th1520WfHw { + period_cycles: u32, + duty_cycles: u32, + ctrl_val: u32, + enabled: bool, +} + +/// The driver's private data struct. It holds all necessary devres manage= d resources. +struct Th1520PwmDriverData { + iomem: devres::Devres>, + clk: Clk, +} + +impl pwm::PwmOps for Th1520PwmDriverData { + type WfHw =3D Th1520WfHw; + + fn round_waveform_tohw( + chip: &mut pwm::Chip, + _pwm: &mut pwm::Device, + wf: &pwm::Waveform, + ) -> Result<(c_int, Self::WfHw)> { + let data: &Self =3D chip.drvdata().ok_or(EINVAL)?; + + if wf.period_length_ns =3D=3D 0 { + return Ok(( + 0, + Th1520WfHw { + enabled: false, + ..Default::default() + }, + )); + } + + let rate_hz =3D data.clk.rate().as_hz() as u64; + + let period_cycles =3D ns_to_cycles(wf.period_length_ns, rate_hz).m= in(u32::MAX as u64); + let mut duty_cycles =3D ns_to_cycles(wf.duty_length_ns, rate_hz).m= in(u32::MAX as u64); + + let mut ctrl_val =3D PWM_CONTINUOUS_MODE; + + if wf.duty_offset_ns =3D=3D 0 { + ctrl_val |=3D PWM_FPOUT; + } else { + duty_cycles =3D period_cycles - duty_cycles; + } + + let wfhw =3D Th1520WfHw { + period_cycles: period_cycles as u32, + duty_cycles: duty_cycles as u32, + ctrl_val, + enabled: true, + }; + + dev_dbg!( + chip.device(), + "Requested: period {}ns, duty {}ns, offset {}ns -> HW: period = {} cyc, duty {} cyc, ctrl 0x{:x}\n", + wf.period_length_ns, + wf.duty_length_ns, + wf.duty_offset_ns, + wfhw.period_cycles, + wfhw.duty_cycles, + wfhw.ctrl_val + ); + + Ok((0, wfhw)) + } + + fn round_waveform_fromhw( + chip: &mut pwm::Chip, + _pwm: &pwm::Device, + wfhw: &Self::WfHw, + wf: &mut pwm::Waveform, + ) -> Result { + let data: &Self =3D chip.drvdata().ok_or(EINVAL)?; + let rate_hz =3D data.clk.rate().as_hz() as u64; + + wf.period_length_ns =3D cycles_to_ns(wfhw.period_cycles as u64, ra= te_hz); + + let duty_cycles =3D wfhw.duty_cycles as u64; + + if (wfhw.ctrl_val & PWM_FPOUT) !=3D 0 { + wf.duty_length_ns =3D cycles_to_ns(duty_cycles, rate_hz); + wf.duty_offset_ns =3D 0; + } else { + let period_cycles =3D wfhw.period_cycles as u64; + let original_duty_cycles =3D period_cycles.saturating_sub(duty= _cycles); + + wf.duty_length_ns =3D cycles_to_ns(original_duty_cycles, rate_= hz); + // We can't recover the original non-zero offset, so we just s= et it + // to a representative non-zero value. + wf.duty_offset_ns =3D 1; + } + + Ok(0) + } + + fn read_waveform( + chip: &mut pwm::Chip, + pwm: &mut pwm::Device, + parent_dev: &Device, + ) -> Result { + let data: &Self =3D chip.drvdata().ok_or(EINVAL)?; + let hwpwm =3D pwm.hwpwm(); + let iomem_guard =3D data.iomem.access(parent_dev)?; + let iomap =3D iomem_guard.deref(); + + let ctrl =3D iomap.try_read32(th1520_pwm_ctrl(hwpwm))?; + let period_cycles =3D iomap.try_read32(th1520_pwm_per(hwpwm))?; + let duty_cycles =3D iomap.try_read32(th1520_pwm_fp(hwpwm))?; + + let wfhw =3D Th1520WfHw { + period_cycles, + duty_cycles, + ctrl_val: ctrl, + enabled: duty_cycles !=3D 0, + }; + + dev_dbg!( + chip.device(), + "PWM-{}: read_waveform: Read hw state - period: {}, duty: {}, = ctrl: 0x{:x}, enabled: {}", + hwpwm, + wfhw.period_cycles, + wfhw.duty_cycles, + wfhw.ctrl_val, + wfhw.enabled + ); + + Ok(wfhw) + } + + fn write_waveform( + chip: &mut pwm::Chip, + pwm: &mut pwm::Device, + wfhw: &Self::WfHw, + parent_dev: &Device, + ) -> Result { + let data: &Self =3D chip.drvdata().ok_or(EINVAL)?; + let hwpwm =3D pwm.hwpwm(); + let iomem_guard =3D data.iomem.access(parent_dev)?; + let iomap =3D iomem_guard.deref(); + let was_enabled =3D pwm.state().enabled(); + + if !wfhw.enabled { + if was_enabled { + iomap.try_write32(wfhw.ctrl_val, th1520_pwm_ctrl(hwpwm))?; + iomap.try_write32(0, th1520_pwm_fp(hwpwm))?; + iomap.try_write32(wfhw.ctrl_val | PWM_CFG_UPDATE, th1520_p= wm_ctrl(hwpwm))?; + } + return Ok(()); + } + + iomap.try_write32(wfhw.ctrl_val, th1520_pwm_ctrl(hwpwm))?; + iomap.try_write32(wfhw.period_cycles, th1520_pwm_per(hwpwm))?; + iomap.try_write32(wfhw.duty_cycles, th1520_pwm_fp(hwpwm))?; + iomap.try_write32(wfhw.ctrl_val | PWM_CFG_UPDATE, th1520_pwm_ctrl(= hwpwm))?; + + // The `PWM_START` bit must be written in a separate, final transa= ction, and + // only when enabling the channel from a disabled state. + if !was_enabled { + iomap.try_write32(wfhw.ctrl_val | PWM_START, th1520_pwm_ctrl(h= wpwm))?; + } + + dev_dbg!( + chip.device(), + "PWM-{}: Wrote (per: {}, duty: {})", + hwpwm, + wfhw.period_cycles, + wfhw.duty_cycles, + ); + + Ok(()) + } +} + +impl Drop for Th1520PwmDriverData { + fn drop(&mut self) { + self.clk.disable_unprepare(); + } +} + +static TH1520_PWM_OPS: pwm::PwmOpsVTable =3D pwm::create_pwm_ops::(); + +struct Th1520PwmPlatformDriver { + _registration: pwm::Registration, +} + +kernel::of_device_table!( + OF_TABLE, + MODULE_OF_TABLE, + ::IdInfo, + [(of::DeviceId::new(c_str!("thead,th1520-pwm")), ())] +); + +impl platform::Driver for Th1520PwmPlatformDriver { + type IdInfo =3D (); + const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); + + fn probe( + pdev: &platform::Device, + _id_info: Option<&Self::IdInfo>, + ) -> Result>> { + let dev =3D pdev.as_ref(); + let resource =3D pdev.resource(0).ok_or(ENODEV)?; + let iomem =3D pdev.ioremap_resource_sized::(r= esource)?; + let clk =3D Clk::get(pdev.as_ref(), None)?; + + clk.prepare_enable()?; + + // TODO: Get exclusive ownership of the clock to prevent rate chan= ges. + // The Rust equivalent of `clk_rate_exclusive_get()` is not yet av= ailable. + // This should be updated once it is implemented. + let rate_hz =3D clk.rate().as_hz(); + if rate_hz =3D=3D 0 { + dev_err!(dev, "Clock rate is zero\n"); + return Err(EINVAL); + } + + if rate_hz > time::NSEC_PER_SEC as usize { + dev_err!( + dev, + "Clock rate {} Hz is too high, not supported.\n", + rate_hz + ); + return Err(ERANGE); + } + + let chip =3D pwm::Chip::new(dev, MAX_PWM_NUM, 0)?; + + let drvdata =3D KBox::new(Th1520PwmDriverData { iomem, clk }, GFP_= KERNEL)?; + chip.set_drvdata(drvdata); + + let registration =3D pwm::Registration::new(chip, &TH1520_PWM_OPS)= ?; + + Ok(KBox::new( + Th1520PwmPlatformDriver { + _registration: registration, + }, + GFP_KERNEL, + )? + .into()) + } +} + +kernel::module_platform_driver! { + type: Th1520PwmPlatformDriver, + name: "pwm-th1520", + authors: ["Michal Wilczynski "], + description: "T-HEAD TH1520 PWM driver", + license: "GPL v2", +} --=20 2.34.1 From nobody Thu Oct 9 13:19:09 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 56BF92E92B6 for ; Tue, 17 Jun 2025 14:08:44 +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=1750169328; cv=none; b=jejw3RYaWT9kBT+a4Gq6tFaBoiMe8LDxKQ+/L/yJDu8bgsWnUGVO8nKITQPm3NI/uTxihMh0upfYePp4251UvlFflUTZxtRwWvb3LPoGj9EineKHOM5hyzNo2nFnrK0Dl6SxxikqZO9LsDEbFIGhCZS0SUEDnhum2GpmEe01nhQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169328; c=relaxed/simple; bh=8QeexMQ+Ddp0T0hHsTz6gc6NzghXhdaWoVKahR3viso=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=sz8lLXKTZO3Mc0sYFQF1mjugHKwMwvyqANlb1ifr8F3wuGcV+Y5q9L7fZ5r9c9fl7Epb+qh5Ov9vFys4I4X27SqKPFFdWFQFc31zNwGXi04F2+okMWMIUqvUTC84m1HTi6QBEfWVHtj1lf6bO04otmxdoLS8B+OJ8ACTzN3BELQ= 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=h93Q01bQ; 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="h93Q01bQ" Received: from eucas1p2.samsung.com (unknown [182.198.249.207]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140841euoutp0277bb8cdce56d146815fd5b7dc4ae07bf~J2bmitXgT0208502085euoutp02B for ; Tue, 17 Jun 2025 14:08:41 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250617140841euoutp0277bb8cdce56d146815fd5b7dc4ae07bf~J2bmitXgT0208502085euoutp02B DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169321; bh=Xe91emMRSSYzgLVJyetcqSNKJQUn2nWDQDykjLFdeWE=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=h93Q01bQEEc+DY3q/0N4t1f8NQG+RuSu3lHP0XFktZm5TgNsC4Ejo37sn4fhegsMI TWkjuhIYVxvt/xTp4vfHNlRGTl5RFHY79OTcEl5xSk/MVdbr+3762y932/b5AloHm8 8Ex7eOothlZp6lki0ADswmmUEd5YAZgvm/EHkg7Y= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p1.samsung.com (KnoxPortal) with ESMTPA id 20250617140840eucas1p1a55fd5f902aac84c16299a0a19852e0d~J2bl_j4FS1046610466eucas1p1d; Tue, 17 Jun 2025 14:08:40 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140839eusmtip1a356f4868163ab79d3d8b399d3665470~J2bk0MDit2857428574eusmtip14; Tue, 17 Jun 2025 14:08:39 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:28 +0200 Subject: [PATCH v3 5/9] clk: thead: Mark essential bus clocks as CLK_IGNORE_UNUSED 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-5-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140840eucas1p1a55fd5f902aac84c16299a0a19852e0d X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140840eucas1p1a55fd5f902aac84c16299a0a19852e0d X-EPHeader: CA X-CMS-RootMailID: 20250617140840eucas1p1a55fd5f902aac84c16299a0a19852e0d References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Probing peripherals in the AON and PERI domains, such as the PVT thermal sensor and the PWM controller, can lead to boot hangs or unresponsive devices on the LPi4A board. The root cause is that their parent bus clocks ('CLK_CPU2AON_X2H' and the 'CLK_PERISYS_APB' clocks) are automatically gated by the kernel's power-saving mechanisms when the bus is perceived as idle. Alternative solutions were investigated, including modeling the parent bus in the Device Tree with 'simple-pm-bus' or refactoring the clock driver's parentage. The 'simple-pm-bus' approach is not viable due to the lack of defined bus address ranges in the hardware manual and its creation of improper dependencies on the 'pm_runtime' API for consumer drivers. Therefore, applying the'`CLK_IGNORE_UNUSED' flag directly to the essential bus clocks is the most direct and targeted fix. This prevents the kernel from auto-gating these buses and ensures peripherals remain accessible. This change fixes the boot hang associated with the PVT sensor and resolves the functional issues with the PWM controller. Link: https://lore.kernel.org/all/9e8a12db-236d-474c-b110-b3be96edf057@sams= ung.com/ [1] Reviewed-by: Drew Fustini Signed-off-by: Michal Wilczynski --- drivers/clk/thead/clk-th1520-ap.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/clk/thead/clk-th1520-ap.c b/drivers/clk/thead/clk-th15= 20-ap.c index ebfb1d59401d05443716eb0029403b01775e8f73..cf7f6bd428a0faa4611b3fc61ed= bbc6690e565d9 100644 --- a/drivers/clk/thead/clk-th1520-ap.c +++ b/drivers/clk/thead/clk-th1520-ap.c @@ -792,11 +792,12 @@ static CCU_GATE(CLK_AON2CPU_A2X, aon2cpu_a2x_clk, "ao= n2cpu-a2x", axi4_cpusys2_ac 0x134, BIT(8), 0); static CCU_GATE(CLK_X2X_CPUSYS, x2x_cpusys_clk, "x2x-cpusys", axi4_cpusys2= _aclk_pd, 0x134, BIT(7), 0); -static CCU_GATE(CLK_CPU2AON_X2H, cpu2aon_x2h_clk, "cpu2aon-x2h", axi_aclk_= pd, 0x138, BIT(8), 0); +static CCU_GATE(CLK_CPU2AON_X2H, cpu2aon_x2h_clk, "cpu2aon-x2h", axi_aclk_= pd, + 0x138, BIT(8), CLK_IGNORE_UNUSED); static CCU_GATE(CLK_CPU2PERI_X2H, cpu2peri_x2h_clk, "cpu2peri-x2h", axi4_c= pusys2_aclk_pd, 0x140, BIT(9), CLK_IGNORE_UNUSED); static CCU_GATE(CLK_PERISYS_APB1_HCLK, perisys_apb1_hclk, "perisys-apb1-hc= lk", perisys_ahb_hclk_pd, - 0x150, BIT(9), 0); + 0x150, BIT(9), CLK_IGNORE_UNUSED); static CCU_GATE(CLK_PERISYS_APB2_HCLK, perisys_apb2_hclk, "perisys-apb2-hc= lk", perisys_ahb_hclk_pd, 0x150, BIT(10), CLK_IGNORE_UNUSED); static CCU_GATE(CLK_PERISYS_APB3_HCLK, perisys_apb3_hclk, "perisys-apb3-hc= lk", perisys_ahb_hclk_pd, --=20 2.34.1 From nobody Thu Oct 9 13:19:09 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 C95652EA466 for ; Tue, 17 Jun 2025 14:08:45 +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=1750169328; cv=none; b=Gq0MK0NJKLGgXKwm8CnouNgCmFG0mRs4BcWDEt72g09VWeoK/YRv5cN8x83lr7TJhC/C1nLfpmjgBScObGvXGDQLI49S21VT1lVECtDWPHC5yn1/y64f6daHWgIZoJ/nJMCI2twxSoRgrLRWZvmOHSm7e30WPvMKBpiIa0zVXT0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169328; c=relaxed/simple; bh=j0ilmlWvuGDdPVedpFQAMvM2nuPCAwx7uovcp5sfOBM=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=GmrmbYK5LYgsb6OL0PWhB/7NR1B9mh1svwwUFKoy7CW3Fe2jl3D43Y5Ffej3gASBZPyRpmyjEd9cSbAWX+jFBUnMaL/SNeyd1UKzRI1iZzevjId9N5pLuAv0vOzpcercYWgwufoOQq+POBql9qvlVLbwRLXao9JS0jC8gda8Kcc= 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=jqbg0K/Z; 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="jqbg0K/Z" Received: from eucas1p1.samsung.com (unknown [182.198.249.206]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140843euoutp02d5ea17fee8203a5f2fddda98a3898e09~J2boKiKYW0211802118euoutp02H for ; Tue, 17 Jun 2025 14:08:43 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250617140843euoutp02d5ea17fee8203a5f2fddda98a3898e09~J2boKiKYW0211802118euoutp02H DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169323; bh=fxnoWq4OQxd1ZCOVWNMF+siSVgYpXr1G0SglMgA6Kss=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=jqbg0K/ZQgslWuBeBWCR/VYQEK+++Ml5utZGEgM3/BhZW45n9qiQE85Nod8AQB0Bl oaJw6mDyarlqjTtOX7pXpVjA0V4KujzRD0YDaJBkB+cyseio57n4xQrc5OU56/iBIR 1b/d1MmSoVEAK8YGs1Y+Qi4EvDA90+ZSzvt4f9ME= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p2.samsung.com (KnoxPortal) with ESMTPA id 20250617140842eucas1p22777d6dfc4881099161ecf9404d909b2~J2bnYZ7001709617096eucas1p2n; Tue, 17 Jun 2025 14:08:42 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140840eusmtip108f1c6553ca05a2d32cba322f7a4b807~J2bmCsuDM2238622386eusmtip1E; Tue, 17 Jun 2025 14:08:40 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:29 +0200 Subject: [PATCH v3 6/9] dt-bindings: pwm: thead: Add T-HEAD TH1520 PWM controller 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-6-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org, Krzysztof Kozlowski X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140842eucas1p22777d6dfc4881099161ecf9404d909b2 X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140842eucas1p22777d6dfc4881099161ecf9404d909b2 X-EPHeader: CA X-CMS-RootMailID: 20250617140842eucas1p22777d6dfc4881099161ecf9404d909b2 References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Add the Device Tree binding documentation for the T-HEAD TH1520 SoC PWM controller. Reviewed-by: Krzysztof Kozlowski Signed-off-by: Michal Wilczynski --- .../devicetree/bindings/pwm/thead,th1520-pwm.yaml | 48 ++++++++++++++++++= ++++ MAINTAINERS | 1 + 2 files changed, 49 insertions(+) diff --git a/Documentation/devicetree/bindings/pwm/thead,th1520-pwm.yaml b/= Documentation/devicetree/bindings/pwm/thead,th1520-pwm.yaml new file mode 100644 index 0000000000000000000000000000000000000000..855aec59ac53c430adc84927123= 5686e87b10e6c --- /dev/null +++ b/Documentation/devicetree/bindings/pwm/thead,th1520-pwm.yaml @@ -0,0 +1,48 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/pwm/thead,th1520-pwm.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: T-HEAD TH1520 PWM controller + +maintainers: + - Michal Wilczynski + +allOf: + - $ref: pwm.yaml# + +properties: + compatible: + const: thead,th1520-pwm + + reg: + maxItems: 1 + + clocks: + items: + - description: SoC PWM clock + + "#pwm-cells": + const: 3 + +required: + - compatible + - reg + - clocks + +unevaluatedProperties: false + +examples: + - | + #include + soc { + #address-cells =3D <2>; + #size-cells =3D <2>; + pwm@ffec01c000 { + compatible =3D "thead,th1520-pwm"; + reg =3D <0xff 0xec01c000 0x0 0x4000>; + clocks =3D <&clk CLK_PWM>; + #pwm-cells =3D <3>; + }; + }; diff --git a/MAINTAINERS b/MAINTAINERS index 879870471e86dcec4a0e8f5c45d2cc3409411fdd..8a55e8d88394a269aa152e80a03= c439a36e6062e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -21394,6 +21394,7 @@ F: Documentation/devicetree/bindings/firmware/thead= ,th1520-aon.yaml F: Documentation/devicetree/bindings/mailbox/thead,th1520-mbox.yaml F: Documentation/devicetree/bindings/net/thead,th1520-gmac.yaml F: Documentation/devicetree/bindings/pinctrl/thead,th1520-pinctrl.yaml +F: Documentation/devicetree/bindings/pwm/thead,th1520-pwm.yaml F: Documentation/devicetree/bindings/reset/thead,th1520-reset.yaml F: arch/riscv/boot/dts/thead/ F: drivers/clk/thead/clk-th1520-ap.c --=20 2.34.1 From nobody Thu Oct 9 13:19:09 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 EAD632E92A9 for ; Tue, 17 Jun 2025 14:08:45 +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=1750169328; cv=none; b=FDGiAWLfNOd++yTiHzyZsWiCO9X81zWUg+bjswNnUu3WltjPW9eTUHmEnuh0o620rlHYGtWH0w/HVSaJb+Y1oChupv3/U2I2+Y7iMAixqJW5dYCwJx3ZhrYFdFbA4ZdPORDCLflA+p90XEDF2GeRXVoQFgD3ZlYq1icX30ygCAQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169328; c=relaxed/simple; bh=G3Rcxmg/8RGJT9WdkJVO9/yG6cY6SHgkWJ+0LoMKMUY=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=eSiAC1vNzztaZlEv59hpTO2pF8HRBSlheUr/dISLf6rf5NrqVWcUa8Q+PrUxxhIcuZM8ikysloevC59ND8rMTCUXhNx5ahQQQmNkSjAeGI7rKroQatgZd02ZdsjGUYgeWx5n85A1iPHoCZ28XiYDb7mG95eUXaljLpbtd3DQNMo= 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=tOKD0EZ+; 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="tOKD0EZ+" Received: from eucas1p1.samsung.com (unknown [182.198.249.206]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140844euoutp0266a7c08ed1a5f629f64afa30580a0d55~J2bpN_7QO0431304313euoutp02C for ; Tue, 17 Jun 2025 14:08:44 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250617140844euoutp0266a7c08ed1a5f629f64afa30580a0d55~J2bpN_7QO0431304313euoutp02C DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169324; bh=tb9Nm7oCBfF8pKU9GqtVQRGVuCwKCYbxFHqowy9m/jM=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=tOKD0EZ+VyFAjmM5b0FA3+ylHu0+d4JzdbkihoIILWjUkL2/7g7dCK0PFN9Rg30i1 XfDvnlgF6bzyMjcKuSfOGd9pnOMVYgKqFeh06s6D2i9FR9GwizvMRr4LW5eDjfDVRx lLngSlqz1azpMTegIN7p8Szs1XDvgQZWGWWNg0tU= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p2.samsung.com (KnoxPortal) with ESMTPA id 20250617140843eucas1p21824efa35dec7b9169ed3114f9e92df9~J2bosQUTc1724917249eucas1p2k; Tue, 17 Jun 2025 14:08:43 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140842eusmtip14bbca11e5f3b918117cdc84a60ed2e51~J2bnTA_hH2540625406eusmtip1N; Tue, 17 Jun 2025 14:08:42 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:30 +0200 Subject: [PATCH v3 7/9] riscv: dts: thead: Add PWM controller node 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-7-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140843eucas1p21824efa35dec7b9169ed3114f9e92df9 X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140843eucas1p21824efa35dec7b9169ed3114f9e92df9 X-EPHeader: CA X-CMS-RootMailID: 20250617140843eucas1p21824efa35dec7b9169ed3114f9e92df9 References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Add the Device Tree node for the T-HEAD TH1520 SoC's PWM controller. Signed-off-by: Michal Wilczynski --- arch/riscv/boot/dts/thead/th1520.dtsi | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arch/riscv/boot/dts/thead/th1520.dtsi b/arch/riscv/boot/dts/th= ead/th1520.dtsi index 1db0054c4e093400e9dbebcee5fcfa5b5cae6e32..26996422e1efe5d2dde68819c2c= ec1c3fa782a23 100644 --- a/arch/riscv/boot/dts/thead/th1520.dtsi +++ b/arch/riscv/boot/dts/thead/th1520.dtsi @@ -490,6 +490,13 @@ uart2: serial@ffec010000 { status =3D "disabled"; }; =20 + pwm: pwm@ffec01c000 { + compatible =3D "thead,th1520-pwm"; + reg =3D <0xff 0xec01c000 0x0 0x4000>; + clocks =3D <&clk CLK_PWM>; + #pwm-cells =3D <3>; + }; + clk: clock-controller@ffef010000 { compatible =3D "thead,th1520-clk-ap"; reg =3D <0xff 0xef010000 0x0 0x1000>; --=20 2.34.1 From nobody Thu Oct 9 13:19:09 2025 Received: from mailout1.w1.samsung.com (mailout1.w1.samsung.com [210.118.77.11]) (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 BD8CB2F433E for ; Tue, 17 Jun 2025 14:08:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=210.118.77.11 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169331; cv=none; b=tMgkvr5FQO6FyQLlltzHm69AGwNP4dPqvQ9c2ClVsYVW+nopmTPTjedh/0/U9cVaI88u17AUhXdwAvbF6xBNYFUTWJAIKzSTQPpP76AOdlWCZY9ES3pFIdmLXfw/Tf3pBHcNRE3ai6aK+aisbjt8fYCRzD9hkISK7Jfkgf77R9c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169331; c=relaxed/simple; bh=N+2CmuFEvaFrCFvEiZxIZGe87T5yZ+GUUMGzk60ZImg=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=ouP1/GXldzOatfqqO9eiTAb8HgCrsyR5/BDg2r8tHfElXBkIXVlZ/GRfT4HfquQoEdSvgkRwWBggOqwfBCi5l0zyPqXq0k7jU6JleJS/8E0ZSyEIAw8J3249MLV6wUVpZ69FY0JAdeRRtEWGWEA2Qnu+9/LBfPdywxVZejFHC4k= 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=NLt0IGUr; arc=none smtp.client-ip=210.118.77.11 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="NLt0IGUr" Received: from eucas1p2.samsung.com (unknown [182.198.249.207]) by mailout1.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140845euoutp01ca040f93ff99a2df1d8500f42850fbc3~J2bqUo21e2798127981euoutp01i for ; Tue, 17 Jun 2025 14:08:45 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout1.w1.samsung.com 20250617140845euoutp01ca040f93ff99a2df1d8500f42850fbc3~J2bqUo21e2798127981euoutp01i DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169325; bh=ZbpbiGCkq+bc/Hnq9ouJryKcDkGL17+XHPFX3q85en0=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=NLt0IGUrkhdCV21WBpKsTA+V+/CN/O93MjfOgOr0bNGbC3rtHkEJnpr12fg3zmxun 8abHfrba09p+IeXYopaAJ8d7L6TzS66R+eq2TVjFV2UEqDyJxk/9iYIZ9HPX0ZTuFE vwesuei4g24HKVPGHXVu9GNyZjblpkDtm5K7pEa0= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p2.samsung.com (KnoxPortal) with ESMTPA id 20250617140844eucas1p2ec26280d366f9cdb4c7846cb2690196a~J2bpr16ft2865928659eucas1p2h; Tue, 17 Jun 2025 14:08:44 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140843eusmtip151df0a7a6e746e98a4069d02c042c444~J2bohODD92540625406eusmtip1O; Tue, 17 Jun 2025 14:08:43 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:31 +0200 Subject: [PATCH v3 8/9] riscv: dts: thead: Add PVT node 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-8-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140844eucas1p2ec26280d366f9cdb4c7846cb2690196a X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140844eucas1p2ec26280d366f9cdb4c7846cb2690196a X-EPHeader: CA X-CMS-RootMailID: 20250617140844eucas1p2ec26280d366f9cdb4c7846cb2690196a References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Add PVT DT node for thermal sensor. Signed-off-by: Michal Wilczynski --- arch/riscv/boot/dts/thead/th1520.dtsi | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arch/riscv/boot/dts/thead/th1520.dtsi b/arch/riscv/boot/dts/th= ead/th1520.dtsi index 26996422e1efe5d2dde68819c2cec1c3fa782a23..bef30780034e06b07aa29b27b02= 25ea891a4b531 100644 --- a/arch/riscv/boot/dts/thead/th1520.dtsi +++ b/arch/riscv/boot/dts/thead/th1520.dtsi @@ -669,6 +669,17 @@ padctrl_aosys: pinctrl@fffff4a000 { thead,pad-group =3D <1>; }; =20 + pvt: pvt@fffff4e000 { + compatible =3D "moortec,mr75203"; + reg =3D <0xff 0xfff4e000 0x0 0x80>, + <0xff 0xfff4e080 0x0 0x100>, + <0xff 0xfff4e180 0x0 0x680>, + <0xff 0xfff4e800 0x0 0x600>; + reg-names =3D "common", "ts", "pd", "vm"; + clocks =3D <&aonsys_clk>; + #thermal-sensor-cells =3D <1>; + }; + gpio@fffff52000 { compatible =3D "snps,dw-apb-gpio"; reg =3D <0xff 0xfff52000 0x0 0x1000>; --=20 2.34.1 From nobody Thu Oct 9 13:19:09 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 AC8652EAD1C for ; Tue, 17 Jun 2025 14:08:48 +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=1750169331; cv=none; b=clkjRBTBMITeuBtg27TmLROG/PNL5vEfdjNda92q6+gx4MujSEYs5kSQTKO0TKOgpIvffuJeJEBnUv9eiBlJXixFUw7QRKBsW7x+OOmWrsCrSbV8qz8cECkiea506PzgiCQ3OtcymntztNhfbk6FcuUmNpoe92gjJumswpd7t5g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1750169331; c=relaxed/simple; bh=pQpdhYmfxqh3Yfxmei5sPv11PaCzGkgZVRufLVaDNj8=; h=From:Date:Subject:MIME-Version:Message-Id:In-Reply-To:To:Cc: Content-Type:References; b=C8f90/snKc7R+NOATCKPAPgh7V9KsLuNCttJgBShlOuH54d5r3iPy5RlAocBJgthxoBSFmzCTNnLb1ndL1UJZjPIKj3a52Sz0Uxz4E96oRhClNPk3nBWgQ58DBFXkp7LIBb2xmuuMOagF69nDGDUZu9kZmJrRpBv+WskUR8uPZA= 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=bqR5K1cG; 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="bqR5K1cG" Received: from eucas1p2.samsung.com (unknown [182.198.249.207]) by mailout2.w1.samsung.com (KnoxPortal) with ESMTP id 20250617140847euoutp02d355a214cf8b143502b7f7c33ab2bc20~J2br3Q_ts0422804228euoutp02V for ; Tue, 17 Jun 2025 14:08:47 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 mailout2.w1.samsung.com 20250617140847euoutp02d355a214cf8b143502b7f7c33ab2bc20~J2br3Q_ts0422804228euoutp02V DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=samsung.com; s=mail20170921; t=1750169327; bh=Thc/4MnT4r5I8ag38cbivyQhpbuX345C1nEB0lzCSSU=; h=From:Date:Subject:In-Reply-To:To:Cc:References:From; b=bqR5K1cGenFKlvxjFwc/n9ZOjkCawOIekyfoDCstUtqtvua/K6L5VF1CgF3EHtuZi 48dvsCPwnNtfcB+02xKXoYxHY6mPr0IkwiwEmXpfBjxm5b/lG1cTRsJ/WGy7FEcD1p 9DOLSppvNqU55W07SUNeJjSEAY1TB9E7Lyqw4FMs= Received: from eusmtip1.samsung.com (unknown [203.254.199.221]) by eucas1p1.samsung.com (KnoxPortal) with ESMTPA id 20250617140846eucas1p1af47d138896b71aabb8ad36245b0466a~J2brHP_001267612676eucas1p1W; Tue, 17 Jun 2025 14:08:46 +0000 (GMT) Received: from AMDC4942.eu.corp.samsungelectronics.net (unknown [106.210.136.40]) by eusmtip1.samsung.com (KnoxPortal) with ESMTPA id 20250617140844eusmtip127f5a6f49be177d7d686592b8f6bf512~J2bpwD3x52596425964eusmtip1X; Tue, 17 Jun 2025 14:08:44 +0000 (GMT) From: Michal Wilczynski Date: Tue, 17 Jun 2025 16:07:32 +0200 Subject: [PATCH v3 9/9] riscv: dts: thead: Add PWM fan and thermal control 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: <20250617-rust-next-pwm-working-fan-for-sending-v3-9-1cca847c6f9f@samsung.com> In-Reply-To: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@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 , Drew Fustini , Guo Ren , Fu Wei , Rob Herring , Krzysztof Kozlowski , Conor Dooley , Paul Walmsley , Palmer Dabbelt , Albert Ou , Alexandre Ghiti , Marek Szyprowski , Benno Lossin , Michael Turquette , Stephen Boyd , Benno Lossin 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, linux-clk@vger.kernel.org X-Mailer: b4 0.15-dev X-CMS-MailID: 20250617140846eucas1p1af47d138896b71aabb8ad36245b0466a X-Msg-Generator: CA Content-Type: text/plain; charset="utf-8" X-RootMTR: 20250617140846eucas1p1af47d138896b71aabb8ad36245b0466a X-EPHeader: CA X-CMS-RootMailID: 20250617140846eucas1p1af47d138896b71aabb8ad36245b0466a References: <20250617-rust-next-pwm-working-fan-for-sending-v3-0-1cca847c6f9f@samsung.com> Add Device Tree nodes to enable a PWM controlled fan and it's associated thermal management for the Lichee Pi 4A board. This enables temperature-controlled active cooling for the Lichee Pi 4A board based on SoC temperature. Signed-off-by: Michal Wilczynski --- arch/riscv/boot/dts/thead/th1520-lichee-pi-4a.dts | 67 +++++++++++++++++++= ++++ 1 file changed, 67 insertions(+) diff --git a/arch/riscv/boot/dts/thead/th1520-lichee-pi-4a.dts b/arch/riscv= /boot/dts/thead/th1520-lichee-pi-4a.dts index 4020c727f09e8e2286fdc7fecd79dbd8eba69556..c58c2085ca92a3234f1350500ce= dae4157f0c35f 100644 --- a/arch/riscv/boot/dts/thead/th1520-lichee-pi-4a.dts +++ b/arch/riscv/boot/dts/thead/th1520-lichee-pi-4a.dts @@ -28,9 +28,76 @@ aliases { chosen { stdout-path =3D "serial0:115200n8"; }; + + thermal-zones { + cpu-thermal { + polling-delay =3D <1000>; + polling-delay-passive =3D <1000>; + thermal-sensors =3D <&pvt 0>; + + trips { + fan_config0: fan-trip0 { + temperature =3D <39000>; + hysteresis =3D <5000>; + type =3D "active"; + }; + + fan_config1: fan-trip1 { + temperature =3D <50000>; + hysteresis =3D <5000>; + type =3D "active"; + }; + + fan_config2: fan-trip2 { + temperature =3D <60000>; + hysteresis =3D <5000>; + type =3D "active"; + }; + }; + + cooling-maps { + map-active-0 { + cooling-device =3D <&fan 1 1>; + trip =3D <&fan_config0>; + }; + + map-active-1 { + cooling-device =3D <&fan 2 2>; + trip =3D <&fan_config1>; + }; + + map-active-2 { + cooling-device =3D <&fan 3 3>; + trip =3D <&fan_config2>; + }; + }; + }; + }; + + fan: pwm-fan { + pinctrl-names =3D "default"; + pinctrl-0 =3D <&fan_pins>; + compatible =3D "pwm-fan"; + #cooling-cells =3D <2>; + pwms =3D <&pwm 1 10000000 0>; + cooling-levels =3D <0 66 196 255>; + }; + }; =20 &padctrl0_apsys { + fan_pins: fan-0 { + pwm1-pins { + pins =3D "GPIO3_3"; /* PWM1 */ + function =3D "pwm"; + bias-disable; + drive-strength =3D <25>; + input-disable; + input-schmitt-disable; + slew-rate =3D <0>; + }; + }; + uart0_pins: uart0-0 { tx-pins { pins =3D "UART0_TXD"; --=20 2.34.1