* [PATCH v5 0/4] Clk improvements
@ 2026-07-06 14:37 Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 1/4] rust: clk: use the type-state pattern Daniel Almeida
` (4 more replies)
0 siblings, 5 replies; 9+ messages in thread
From: Daniel Almeida @ 2026-07-06 14:37 UTC (permalink / raw)
To: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Daniel Almeida, Michal Wilczynski,
Boqun Feng, Boqun Feng
Cc: linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Onur Özkan,
Maurice
This series contains a few improvements that simplifies clock handling for
drivers.
Patch 1 implements the same typestate pattern that has been used
successfully for Regulators. This is needed because otherwise drivers
will be responsible for unpreparing and disabling clocks themselves and
ultimately handling the reference counts on their own. This is
undesirable. The patch automatically encodes this information using the
type system so that no misuse can occur.
Patch 2 implements Clone for Clk<T>, so that a driver can hold a
long-lived clock in one state while temporarily moving an independent
clone of it through the other states. This is the outcome of the
discussion in v3 with Boris Brezillon and Gary Guo.
Patch 3 makes things more convenient by offering devres-managed APIs. This
lets drivers set clock parameters once and forget about lifetime
management.
Patch 4 converts clk.rs to the newer kernel-vertical style in order to make
future changes easier.
The pre-existing error-path imbalance in the C function
devm_clk_get_optional_enabled_with_rate() that was noted during the v4
review is a C-side issue and will be addressed by a separate patch.
---
Changes in v5:
- Rebased onto the latest clk-next.
- New patch: "rust: clk: implement Clone for Clk<T>". Each clone is an
independent view of the same underlying clock, owning its own
prepare/enable counts; the raw pointer is shared through an Arc so
clk_get()/clk_put() stay balanced. Follows the v3 discussion with
Boris Brezillon and Gary Guo.
- Moved rate() and set_rate() from Clk<Enabled> to all states; the C API
does not restrict these to enabled clocks, and some clocks can only
change rate before being prepared.
- Made Clk::<Enabled>::disable() infallible, matching unprepare() and
the void C API (Onur).
- Fixed a typo in the "# Invariants" section, fixed SAFETY comments
that referred to the non-existent `self.0` field, and added missing
INVARIANT comments on the state transitions.
- Added the missing rustdoc link definitions for clk_unprepare and
clk_put (Maurice).
- Dropped the redundant `Result` import and the `use
kernel::error::Result;` lines from the doctests; the prelude already
provides it (Miguel).
- Added #[inline] to the devm_* helpers.
- Link to v4: https://patch.msgid.link/20260618-clk-type-state-v4-0-8be082786080@collabora.com
Changes in v4:
- Rebased onto clk-next. Alice Ryhl's "rust: clk: implement Send and Sync"
series is now merged upstream, so it is no longer carried as a dependency.
- Fixed the build with CONFIG_CPUFREQ_DT_RUST=y. The generic DT cpufreq
driver only has the (unbound) per-CPU device, so it cannot hand a
&Device<Bound> to Policy::set_clk(). Added a pub(crate) Clk::get_unbound()
for the few in-tree abstractions that operate on a device outside a bind
scope; set_clk() now takes &Device and uses it. Clk::get()/get_optional()
and the devm_* helpers still require &Device<Bound>.
- Added impl From<Error<State>> for kernel::error::Error, so the fallible
state transitions can be used with `?` (and chained) instead of
.map_err(|e| e.error).
- Added Clk::<Prepared>::with_enabled(), which runs a closure with the clock
temporarily enabled, scoping the Enabled state without giving up the
prepared clock.
- Documented how to change a clock's state at runtime via an enum, for
drivers that enable/disable across resume/suspend.
- Link to v3: https://lore.kernel.org/r/20260107-clk-type-state-v3-0-77d3e3ee59c2@collabora.com
Changes in v3:
- Rebased on top of 6.19-rc4
- Dropped patch 1 (from Alice), added her series as a dependency instead
- Fixed Tyr, PWM_TH1520 drivers
- Changed clk.rs imports to kernel-vertical style
- Added support get_optional shortcut for Prepared and Enabled (i.e.:
Clk::<Enabled>::get_optional())
- Fixed misplaced #[inline] tag
Thanks, Danilo {
- Moved the devres changes into its own patch
- Require &Device<Bound> for all functions where a &Device is used
- Account for con_in in SAFETY comments where applicable
- Added backticks
}
- Link to v2: https://lore.kernel.org/r/20250910-clk-type-state-v2-0-1b97c11bb631@collabora.com
Changes in v2:
- Added Alice's patch as patch 1, since it is a dependency.
- Added devm helpers (like we did for Regulator<T>)
- Fixed missing clk_put() call in Drop (Danilo)
- Fixed missing parenthesis and wrong docs (Viresh)
- Removed extra "dev" parameter from "shutdown" example (Danilo)
- Removed useless type annotation from example (Danilo)
- Link to v1: https://lore.kernel.org/rust-for-linux/20250729-clk-type-state-v1-1-896b53816f7b@collabora.com/#r
To: "Rafael J. Wysocki" <rafael@kernel.org>
To: Viresh Kumar <viresh.kumar@linaro.org>
To: Danilo Krummrich <dakr@kernel.org>
To: Alice Ryhl <aliceryhl@google.com>
To: Daniel Almeida <daniel.almeida@collabora.com>
To: David Airlie <airlied@gmail.com>
To: Simona Vetter <simona@ffwll.ch>
To: Michal Wilczynski <m.wilczynski@samsung.com>
To: Drew Fustini <fustini@kernel.org>
To: Guo Ren <guoren@kernel.org>
To: Fu Wei <wefu@redhat.com>
To: Uwe Kleine-König <ukleinek@kernel.org>
To: Michael Turquette <mturquette@baylibre.com>
To: Stephen Boyd <sboyd@kernel.org>
To: Miguel Ojeda <ojeda@kernel.org>
To: Boqun Feng <boqun@kernel.org>
To: Gary Guo <gary@garyguo.net>
To: Björn Roy Baron <bjorn3_gh@protonmail.com>
To: Benno Lossin <lossin@kernel.org>
To: Andreas Hindborg <a.hindborg@kernel.org>
To: Trevor Gross <tmgross@umich.edu>
Cc: linux-pm@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: dri-devel@lists.freedesktop.org
Cc: linux-riscv@lists.infradead.org
Cc: linux-pwm@vger.kernel.org
Cc: linux-clk@vger.kernel.org
Cc: rust-for-linux@vger.kernel.org
---
Daniel Almeida (4):
rust: clk: use the type-state pattern
rust: clk: implement Clone for Clk<T>
rust: clk: add devres-managed clks
rust: clk: use 'kernel vertical style' for imports
drivers/cpufreq/rcpufreq_dt.rs | 2 +-
drivers/gpu/drm/tyr/driver.rs | 37 +--
drivers/pwm/pwm_th1520.rs | 17 +-
rust/kernel/clk.rs | 722 +++++++++++++++++++++++++++++++++--------
rust/kernel/cpufreq.rs | 8 +-
5 files changed, 602 insertions(+), 184 deletions(-)
---
base-commit: 92010229c4b38897f1319d260162d2f96925ed17
change-id: 20250909-clk-type-state-c01aa7dd551d
Best regards,
--
Daniel Almeida <daniel.almeida@collabora.com>
^ permalink raw reply [flat|nested] 9+ messages in thread
* [PATCH v5 1/4] rust: clk: use the type-state pattern
2026-07-06 14:37 [PATCH v5 0/4] Clk improvements Daniel Almeida
@ 2026-07-06 14:37 ` Daniel Almeida
2026-08-01 14:33 ` Alexandre Courbot
2026-07-06 14:37 ` [PATCH v5 2/4] rust: clk: implement Clone for Clk<T> Daniel Almeida
` (3 subsequent siblings)
4 siblings, 1 reply; 9+ messages in thread
From: Daniel Almeida @ 2026-07-06 14:37 UTC (permalink / raw)
To: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Daniel Almeida, Michal Wilczynski,
Boqun Feng, Boqun Feng
Cc: linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Onur Özkan,
Maurice
The current Clk abstraction can still be improved on the following issues:
a) It only keeps track of a count to clk_get(), which means that users have
to manually call disable() and unprepare(), or a variation of those, like
disable_unprepare().
b) It allows repeated calls to prepare() or enable(), but it keeps no track
of how often these were called, i.e., it's currently legal to write the
following:
clk.prepare();
clk.prepare();
clk.enable();
clk.enable();
And nothing gets undone on drop().
c) It adds a OptionalClk type that is probably not needed. There is no
"struct optional_clk" in C and we should probably not add one.
d) It does not let a user express the state of the clk through the
type system. For example, there is currently no way to encode that a Clk is
enabled via the type system alone.
In light of the Regulator abstraction that was recently merged, switch this
abstraction to use the type-state pattern instead. It solves both a) and b)
by establishing a number of states and the valid ways to transition between
them. It also automatically undoes any call to clk_get(), clk_prepare() and
clk_enable() as applicable on drop(), so users do not have to do anything
special before Clk goes out of scope.
It solves c) by removing the OptionalClk type, which is now simply encoded
as a Clk whose inner pointer is NULL.
It solves d) by directly encoding the state of the Clk into the type, e.g.:
Clk<Enabled> is now known to be a Clk that is enabled.
The INVARIANTS section for Clk is expanded to highlight the relationship
between the states and the respective reference counts that are owned by
each of them.
The examples are expanded to highlight how a user can transition between
states, as well as highlight some of the shortcuts built into the API.
The current implementation is also more flexible, in the sense that it
allows for more states to be added in the future. This lets us implement
different strategies for handling clocks, including one that mimics the
current API, allowing for multiple calls to prepare() and enable().
The users (cpufreq.rs/ rcpufreq_dt.rs) were updated by this patch (and not
a separate one) to reflect the new changes. This is needed, because
otherwise this patch would break the build.
Link: https://crates.io/crates/sealed [1]
Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
---
drivers/cpufreq/rcpufreq_dt.rs | 2 +-
drivers/gpu/drm/tyr/driver.rs | 37 +--
drivers/pwm/pwm_th1520.rs | 17 +-
rust/kernel/clk.rs | 541 ++++++++++++++++++++++++++++++-----------
rust/kernel/cpufreq.rs | 8 +-
5 files changed, 423 insertions(+), 182 deletions(-)
diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs
index f17bf64c22e2..9d2ec7df4bac 100644
--- a/drivers/cpufreq/rcpufreq_dt.rs
+++ b/drivers/cpufreq/rcpufreq_dt.rs
@@ -40,7 +40,7 @@ struct CPUFreqDTDevice {
freq_table: opp::FreqTable,
_mask: CpumaskVar,
_token: Option<opp::ConfigToken>,
- _clk: Clk,
+ _clk: Clk<kernel::clk::Unprepared>,
}
#[derive(Default)]
diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs
index 279710b36a10..7a85c86d26c2 100644
--- a/drivers/gpu/drm/tyr/driver.rs
+++ b/drivers/gpu/drm/tyr/driver.rs
@@ -3,7 +3,7 @@
use kernel::{
clk::{
Clk,
- OptionalClk, //
+ Enabled, //
},
device::{
Bound,
@@ -49,7 +49,7 @@ pub(crate) struct TyrPlatformDriverData {
_device: ARef<TyrDrmDevice>,
}
-#[pin_data(PinnedDrop)]
+#[pin_data]
pub(crate) struct TyrDrmDeviceData {
pub(crate) pdev: ARef<platform::Device>,
@@ -97,13 +97,9 @@ fn probe(
pdev: &platform::Device<Core>,
_info: Option<&Self::IdInfo>,
) -> impl PinInit<Self, Error> {
- let core_clk = Clk::get(pdev.as_ref(), Some(c"core"))?;
- let stacks_clk = OptionalClk::get(pdev.as_ref(), Some(c"stacks"))?;
- let coregroup_clk = OptionalClk::get(pdev.as_ref(), Some(c"coregroup"))?;
-
- core_clk.prepare_enable()?;
- stacks_clk.prepare_enable()?;
- coregroup_clk.prepare_enable()?;
+ let core_clk = Clk::<Enabled>::get(pdev.as_ref(), Some(c"core"))?;
+ let stacks_clk = Clk::<Enabled>::get_optional(pdev.as_ref(), Some(c"stacks"))?;
+ let coregroup_clk = Clk::<Enabled>::get_optional(pdev.as_ref(), Some(c"coregroup"))?;
let mali_regulator = Regulator::<regulator::Enabled>::get(pdev.as_ref(), c"mali")?;
let sram_regulator = Regulator::<regulator::Enabled>::get(pdev.as_ref(), c"sram")?;
@@ -122,9 +118,9 @@ fn probe(
let data = try_pin_init!(TyrDrmDeviceData {
pdev: platform.clone(),
clks <- new_mutex!(Clocks {
- core: core_clk,
- stacks: stacks_clk,
- coregroup: coregroup_clk,
+ _core: core_clk,
+ _stacks: stacks_clk,
+ _coregroup: coregroup_clk,
}),
regulators <- new_mutex!(Regulators {
_mali: mali_regulator,
@@ -150,17 +146,6 @@ impl PinnedDrop for TyrPlatformDriverData {
fn drop(self: Pin<&mut Self>) {}
}
-#[pinned_drop]
-impl PinnedDrop for TyrDrmDeviceData {
- fn drop(self: Pin<&mut Self>) {
- // TODO: the type-state pattern for Clks will fix this.
- let clks = self.clks.lock();
- clks.core.disable_unprepare();
- clks.stacks.disable_unprepare();
- clks.coregroup.disable_unprepare();
- }
-}
-
// We need to retain the name "panthor" to achieve drop-in compatibility with
// the C driver in the userspace stack.
const INFO: drm::DriverInfo = drm::DriverInfo {
@@ -186,9 +171,9 @@ impl drm::Driver for TyrDrmDriver {
#[pin_data]
struct Clocks {
- core: Clk,
- stacks: OptionalClk,
- coregroup: OptionalClk,
+ _core: Clk<Enabled>,
+ _stacks: Clk<Enabled>,
+ _coregroup: Clk<Enabled>,
}
#[pin_data]
diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs
index ddd44a5ce497..343a1178c5e7 100644
--- a/drivers/pwm/pwm_th1520.rs
+++ b/drivers/pwm/pwm_th1520.rs
@@ -22,7 +22,7 @@
use core::ops::Deref;
use kernel::{
- clk::Clk,
+ clk::{Clk, Enabled},
device::{Bound, Core, Device},
devres,
io::{
@@ -89,11 +89,11 @@ struct Th1520WfHw {
}
/// The driver's private data struct. It holds all necessary devres managed resources.
-#[pin_data(PinnedDrop)]
+#[pin_data]
struct Th1520PwmDriverData {
#[pin]
iomem: devres::Devres<IoMem<TH1520_PWM_REG_SIZE>>,
- clk: Clk,
+ clk: Clk<Enabled>,
}
impl pwm::PwmOps for Th1520PwmDriverData {
@@ -298,13 +298,6 @@ fn write_waveform(
}
}
-#[pinned_drop]
-impl PinnedDrop for Th1520PwmDriverData {
- fn drop(self: Pin<&mut Self>) {
- self.clk.disable_unprepare();
- }
-}
-
struct Th1520PwmPlatformDriver;
kernel::of_device_table!(
@@ -325,9 +318,7 @@ fn probe(
let dev = pdev.as_ref();
let request = pdev.io_request_by_index(0).ok_or(ENODEV)?;
- let clk = Clk::get(dev, None)?;
-
- clk.prepare_enable()?;
+ let clk = Clk::<Enabled>::get(dev, None)?;
// TODO: Get exclusive ownership of the clock to prevent rate changes.
// The Rust equivalent of `clk_rate_exclusive_get()` is not yet available.
diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs
index 7abbd0767d8c..a9edfdf9db68 100644
--- a/rust/kernel/clk.rs
+++ b/rust/kernel/clk.rs
@@ -80,17 +80,103 @@ fn from(freq: Hertz) -> Self {
mod common_clk {
use super::Hertz;
use crate::{
- device::Device,
+ device::{Bound, Device},
error::{from_err_ptr, to_result, Result},
prelude::*,
};
- use core::{ops::Deref, ptr};
+ use core::{marker::PhantomData, mem::ManuallyDrop, ptr};
+
+ mod private {
+ pub trait Sealed {}
+
+ impl Sealed for super::Unprepared {}
+ impl Sealed for super::Prepared {}
+ impl Sealed for super::Enabled {}
+ }
+
+ /// A trait representing the different states that a [`Clk`] can be in.
+ pub trait ClkState: private::Sealed {
+ /// Whether the clock should be disabled when dropped.
+ const DISABLE_ON_DROP: bool;
+
+ /// Whether the clock should be unprepared when dropped.
+ const UNPREPARE_ON_DROP: bool;
+ }
+
+ /// A state where the [`Clk`] is not prepared and not enabled.
+ pub struct Unprepared;
+
+ /// A state where the [`Clk`] is prepared but not enabled.
+ pub struct Prepared;
+
+ /// A state where the [`Clk`] is both prepared and enabled.
+ pub struct Enabled;
+
+ impl ClkState for Unprepared {
+ const DISABLE_ON_DROP: bool = false;
+ const UNPREPARE_ON_DROP: bool = false;
+ }
+
+ impl ClkState for Prepared {
+ const DISABLE_ON_DROP: bool = false;
+ const UNPREPARE_ON_DROP: bool = true;
+ }
+
+ impl ClkState for Enabled {
+ const DISABLE_ON_DROP: bool = true;
+ const UNPREPARE_ON_DROP: bool = true;
+ }
+
+ /// An error that can occur when trying to convert a [`Clk`] between states.
+ pub struct Error<State: ClkState> {
+ /// The error that occurred.
+ pub error: kernel::error::Error,
+
+ /// The [`Clk`] that caused the error, so that the operation may be
+ /// retried.
+ pub clk: Clk<State>,
+ }
+
+ impl<State: ClkState> From<Error<State>> for kernel::error::Error {
+ /// Discards the [`Clk`] and keeps only the error code.
+ ///
+ /// This makes the fallible state transitions usable with the `?`
+ /// operator when the caller does not need to retry the operation on the
+ /// original [`Clk`], e.g.:
+ ///
+ /// ```
+ /// use kernel::clk::{Clk, Enabled, Unprepared};
+ /// use kernel::device::{Bound, Device};
+ /// use kernel::error::Result;
+ ///
+ /// fn get_enabled(dev: &Device<Bound>) -> Result<Clk<Enabled>> {
+ /// let clk = Clk::<Unprepared>::get(dev, Some(c"apb_clk"))?
+ /// .prepare()?
+ /// .enable()?;
+ /// Ok(clk)
+ /// }
+ /// ```
+ #[inline]
+ fn from(err: Error<State>) -> Self {
+ err.error
+ }
+ }
/// A reference-counted clock.
///
/// Rust abstraction for the C [`struct clk`].
///
+ /// A [`Clk`] instance represents a clock that can be in one of several
+ /// states: [`Unprepared`], [`Prepared`], or [`Enabled`].
+ ///
+ /// No action needs to be taken when a [`Clk`] is dropped. The calls to
+ /// `clk_unprepare()` and `clk_disable()` will be placed as applicable.
+ ///
+ /// An optional [`Clk`] is treated just like a regular [`Clk`], but its
+ /// inner `struct clk` pointer is `NULL`. This interfaces correctly with the
+ /// C API and also exposes all the methods of a regular [`Clk`] to users.
+ ///
/// # Invariants
///
/// A [`Clk`] instance holds either a pointer to a valid [`struct clk`] created by the C
@@ -99,19 +185,36 @@ mod common_clk {
/// Instances of this type are reference-counted. Calling [`Clk::get`] ensures that the
/// allocation remains valid for the lifetime of the [`Clk`].
///
+ /// The [`Prepared`] state is associated with a single count of
+ /// `clk_prepare()`, and the [`Enabled`] state is associated with a single
+ /// count of both `clk_prepare()` and `clk_enable()`.
+ ///
+ /// All states are associated with a single count of `clk_get()`.
+ ///
/// # Examples
///
/// The following example demonstrates how to obtain and configure a clock for a device.
///
/// ```
- /// use kernel::clk::{Clk, Hertz};
- /// use kernel::device::Device;
+ /// use kernel::clk::{Clk, Enabled, Hertz, Unprepared, Prepared};
+ /// use kernel::device::{Bound, Device};
/// use kernel::error::Result;
///
- /// fn configure_clk(dev: &Device) -> Result {
- /// let clk = Clk::get(dev, Some(c"apb_clk"))?;
+ /// fn configure_clk(dev: &Device<Bound>) -> Result {
+ /// // The fastest way is to use a version of `Clk::get` for the desired
+ /// // state, i.e.:
+ /// let clk: Clk<Enabled> = Clk::<Enabled>::get(dev, Some(c"apb_clk"))?;
+ ///
+ /// // Any other state is also possible, e.g.:
+ /// let clk: Clk<Prepared> = Clk::<Prepared>::get(dev, Some(c"apb_clk"))?;
///
- /// clk.prepare_enable()?;
+ /// // Later:
+ /// //
+ /// // `?` works directly thanks to `From<Error<State>>`; the failed
+ /// // `Clk` is dropped on error. Match on the returned `Error<State>`
+ /// // instead (its `clk` field is the original `Clk`) if you want to
+ /// // retry the operation.
+ /// let clk: Clk<Enabled> = clk.enable()?;
///
/// let expected_rate = Hertz::from_ghz(1);
///
@@ -119,122 +222,339 @@ mod common_clk {
/// clk.set_rate(expected_rate)?;
/// }
///
- /// clk.disable_unprepare();
+ /// // Nothing is needed here. The drop implementation will undo any
+ /// // operations as appropriate.
+ /// Ok(())
+ /// }
+ ///
+ /// fn shutdown(clk: Clk<Enabled>) -> Result {
+ /// // The states can be traversed "in the reverse order" as well:
+ /// let clk: Clk<Prepared> = clk.disable();
+ ///
+ /// // This is of type `Clk<Unprepared>`.
+ /// let clk = clk.unprepare();
+ ///
/// Ok(())
/// }
/// ```
///
+ /// Drivers that need to change a clock's state at runtime (for example to
+ /// enable it on resume and disable it on suspend) can keep it in an enum
+ /// and move between the variants:
+ ///
+ /// ```
+ /// use kernel::clk::{Clk, Enabled, Prepared};
+ /// use kernel::error::Result;
+ ///
+ /// enum DeviceClk {
+ /// Suspended(Clk<Prepared>),
+ /// Resumed(Clk<Enabled>),
+ /// }
+ ///
+ /// impl DeviceClk {
+ /// fn resume(self) -> Result<Self> {
+ /// Ok(match self {
+ /// DeviceClk::Suspended(clk) => DeviceClk::Resumed(clk.enable()?),
+ /// resumed => resumed,
+ /// })
+ /// }
+ ///
+ /// fn suspend(self) -> Result<Self> {
+ /// Ok(match self {
+ /// DeviceClk::Resumed(clk) => DeviceClk::Suspended(clk.disable()),
+ /// suspended => suspended,
+ /// })
+ /// }
+ /// }
+ /// ```
+ ///
/// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
#[repr(transparent)]
- pub struct Clk(*mut bindings::clk);
+ pub struct Clk<T: ClkState> {
+ inner: *mut bindings::clk,
+ _phantom: core::marker::PhantomData<T>,
+ }
// SAFETY: It is safe to call `clk_put` on another thread than where `clk_get` was called.
- unsafe impl Send for Clk {}
+ unsafe impl<T: ClkState> Send for Clk<T> {}
// SAFETY: It is safe to call any combination of the `&self` methods in parallel, as the
// methods are synchronized internally.
- unsafe impl Sync for Clk {}
+ unsafe impl<T: ClkState> Sync for Clk<T> {}
- impl Clk {
- /// Gets [`Clk`] corresponding to a [`Device`] and a connection id.
+ impl Clk<Unprepared> {
+ /// Gets [`Clk`] corresponding to a bound [`Device`] and a connection
+ /// id.
///
/// Equivalent to the kernel's [`clk_get`] API.
///
/// [`clk_get`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get
- pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
+ #[inline]
+ pub fn get(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Unprepared>> {
+ Self::get_unbound(dev, name)
+ }
+
+ /// Gets [`Clk`] corresponding to a [`Device`] and a connection id,
+ /// without requiring the device to be bound.
+ ///
+ /// This is sound because [`clk_get`] and [`clk_put`] do not depend on the
+ /// device being bound to a driver. It is `pub(crate)` because a driver
+ /// should obtain its clocks through a bound device (see [`Clk::get`]); it
+ /// is meant for the few in-tree abstractions that operate on a device
+ /// outside a bind scope, such as the generic DT cpufreq driver.
+ ///
+ /// [`clk_get`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get
+ /// [`clk_put`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_put
+ #[inline]
+ pub(crate) fn get_unbound(dev: &Device, name: Option<&CStr>) -> Result<Clk<Unprepared>> {
let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
- // SAFETY: It is safe to call [`clk_get`] for a valid device pointer.
- //
+ // SAFETY: It is safe to call [`clk_get`] for a valid device pointer
+ // and any `con_id`, including NULL.
+ let inner = from_err_ptr(unsafe { bindings::clk_get(dev.as_raw(), con_id) })?;
+
// INVARIANT: The reference-count is decremented when [`Clk`] goes out of scope.
- Ok(Self(from_err_ptr(unsafe {
- bindings::clk_get(dev.as_raw(), con_id)
- })?))
+ Ok(Self {
+ inner,
+ _phantom: PhantomData,
+ })
}
- /// Obtain the raw [`struct clk`] pointer.
+ /// Behaves the same as [`Self::get`], except when there is no clock
+ /// producer. In this case, instead of returning [`ENOENT`], it returns
+ /// a dummy [`Clk`].
#[inline]
- pub fn as_raw(&self) -> *mut bindings::clk {
- self.0
+ pub fn get_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Unprepared>> {
+ let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
+
+ // SAFETY: It is safe to call [`clk_get`] for a valid device pointer
+ // and any `con_id`, including NULL.
+ let inner = from_err_ptr(unsafe { bindings::clk_get_optional(dev.as_raw(), con_id) })?;
+
+ // INVARIANT: The reference-count is decremented when [`Clk`] goes out of scope.
+ Ok(Self {
+ inner,
+ _phantom: PhantomData,
+ })
}
- /// Enable the clock.
+ /// Attempts to convert the [`Clk`] to a [`Prepared`] state.
///
- /// Equivalent to the kernel's [`clk_enable`] API.
+ /// Equivalent to the kernel's [`clk_prepare`] API.
///
- /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_enable
+ /// [`clk_prepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_prepare
#[inline]
- pub fn enable(&self) -> Result {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_enable`].
- to_result(unsafe { bindings::clk_enable(self.as_raw()) })
+ pub fn prepare(self) -> Result<Clk<Prepared>, Error<Unprepared>> {
+ // We will be transferring the ownership of our `clk_get()` count to
+ // `Clk<Prepared>`.
+ let clk = ManuallyDrop::new(self);
+
+ // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
+ // for [`clk_prepare`].
+ to_result(unsafe { bindings::clk_prepare(clk.as_raw()) })
+ // INVARIANT: `clk_prepare()` succeeded, so the returned
+ // `Clk<Prepared>` owns a single count of it, which is released
+ // when it leaves the [`Prepared`] state.
+ .map(|()| Clk {
+ inner: clk.inner,
+ _phantom: PhantomData,
+ })
+ .map_err(|error| Error {
+ error,
+ clk: ManuallyDrop::into_inner(clk),
+ })
+ }
+ }
+
+ impl Clk<Prepared> {
+ /// Obtains a [`Clk`] from a bound [`Device`] and a connection id and
+ /// prepares it.
+ ///
+ /// Equivalent to calling [`Clk::get`], followed by [`Clk::prepare`],
+ #[inline]
+ pub fn get(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Prepared>> {
+ Clk::<Unprepared>::get(dev, name)?
+ .prepare()
+ .map_err(|error| error.error)
+ }
+
+ /// Behaves the same as [`Self::get`], except when there is no clock
+ /// producer. In this case, instead of returning [`ENOENT`], it returns
+ /// a dummy [`Clk`].
+ #[inline]
+ pub fn get_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Prepared>> {
+ Clk::<Unprepared>::get_optional(dev, name)?
+ .prepare()
+ .map_err(|error| error.error)
}
- /// Disable the clock.
+ /// Converts the [`Clk`] to an [`Unprepared`] state.
///
- /// Equivalent to the kernel's [`clk_disable`] API.
+ /// Equivalent to the kernel's [`clk_unprepare`] API.
///
- /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_disable
+ /// [`clk_unprepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_unprepare
#[inline]
- pub fn disable(&self) {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_disable`].
- unsafe { bindings::clk_disable(self.as_raw()) };
+ pub fn unprepare(self) -> Clk<Unprepared> {
+ // We will be transferring the ownership of our `clk_get()` count to
+ // `Clk<Unprepared>`.
+ let clk = ManuallyDrop::new(self);
+
+ // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
+ // for [`clk_unprepare`].
+ unsafe { bindings::clk_unprepare(clk.as_raw()) }
+
+ // INVARIANT: The `clk_prepare()` count was released above, so the
+ // returned `Clk<Unprepared>` owns only the `clk_get()` count.
+ Clk {
+ inner: clk.inner,
+ _phantom: PhantomData,
+ }
}
- /// Prepare the clock.
+ /// Attempts to convert the [`Clk`] to an [`Enabled`] state.
///
- /// Equivalent to the kernel's [`clk_prepare`] API.
+ /// Equivalent to the kernel's [`clk_enable`] API.
///
- /// [`clk_prepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_prepare
+ /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_enable
#[inline]
- pub fn prepare(&self) -> Result {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_prepare`].
- to_result(unsafe { bindings::clk_prepare(self.as_raw()) })
+ pub fn enable(self) -> Result<Clk<Enabled>, Error<Prepared>> {
+ // We will be transferring the ownership of our `clk_get()` and
+ // `clk_prepare()` counts to `Clk<Enabled>`.
+ let clk = ManuallyDrop::new(self);
+
+ // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
+ // for [`clk_enable`].
+ to_result(unsafe { bindings::clk_enable(clk.as_raw()) })
+ // INVARIANT: `clk_enable()` succeeded, so the returned
+ // `Clk<Enabled>` owns a single count of it, which is released
+ // when it leaves the [`Enabled`] state.
+ .map(|()| Clk {
+ inner: clk.inner,
+ _phantom: PhantomData,
+ })
+ .map_err(|error| Error {
+ error,
+ clk: ManuallyDrop::into_inner(clk),
+ })
}
- /// Unprepare the clock.
+ /// Runs `cb` with the clock temporarily enabled.
///
- /// Equivalent to the kernel's [`clk_unprepare`] API.
+ /// The clock is enabled before `cb` runs and disabled again afterwards,
+ /// so the [`Enabled`] state is scoped to the closure and the [`Clk`]
+ /// remains [`Prepared`]. This is convenient for drivers that only need
+ /// the clock running for a short, well-defined section (e.g. while
+ /// touching registers) without giving up ownership of the prepared
+ /// clock or threading it through an intermediate state, e.g.:
///
- /// [`clk_unprepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_unprepare
+ /// ```
+ /// use kernel::clk::{Clk, Enabled, Hertz, Prepared};
+ /// use kernel::error::Result;
+ ///
+ /// fn read_rate(clk: &Clk<Prepared>) -> Result<Hertz> {
+ /// clk.with_enabled(|clk: &Clk<Enabled>| clk.rate())
+ /// }
+ /// ```
+ ///
+ /// Equivalent to a balanced [`clk_enable`]/[`clk_disable`] pair around
+ /// `cb`.
+ ///
+ /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_enable
+ /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_disable
#[inline]
- pub fn unprepare(&self) {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_unprepare`].
- unsafe { bindings::clk_unprepare(self.as_raw()) };
+ pub fn with_enabled<R>(&self, cb: impl FnOnce(&Clk<Enabled>) -> R) -> Result<R> {
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid argument for
+ // [`clk_enable`].
+ to_result(unsafe { bindings::clk_enable(self.as_raw()) })?;
+
+ // Borrow the same clock as `Clk<Enabled>` for the duration of `cb`.
+ // It must not be dropped, as that would run `clk_disable`/`clk_put`
+ // against counts owned by `self`; the matching `clk_disable` below
+ // balances the `clk_enable` above instead.
+ //
+ // INVARIANT: The clock is enabled for the lifetime of `enabled`.
+ let enabled = ManuallyDrop::new(Clk::<Enabled> {
+ inner: self.inner,
+ _phantom: PhantomData,
+ });
+
+ let ret = cb(&enabled);
+
+ // SAFETY: The `clk_enable` above succeeded, so this balances it.
+ // `cb` only had a shared reference, so the enable count is unchanged.
+ unsafe { bindings::clk_disable(self.as_raw()) };
+
+ Ok(ret)
}
+ }
- /// Prepare and enable the clock.
+ impl Clk<Enabled> {
+ /// Gets [`Clk`] corresponding to a bound [`Device`] and a connection id
+ /// and then prepares and enables it.
///
- /// Equivalent to calling [`Clk::prepare`] followed by [`Clk::enable`].
+ /// Equivalent to calling [`Clk::get`], followed by [`Clk::prepare`],
+ /// followed by [`Clk::enable`].
#[inline]
- pub fn prepare_enable(&self) -> Result {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_prepare_enable`].
- to_result(unsafe { bindings::clk_prepare_enable(self.as_raw()) })
+ pub fn get(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Enabled>> {
+ Clk::<Prepared>::get(dev, name)?
+ .enable()
+ .map_err(|error| error.error)
+ }
+
+ /// Behaves the same as [`Self::get`], except when there is no clock
+ /// producer. In this case, instead of returning [`ENOENT`], it returns
+ /// a dummy [`Clk`].
+ #[inline]
+ pub fn get_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Enabled>> {
+ Clk::<Prepared>::get_optional(dev, name)?
+ .enable()
+ .map_err(|error| error.error)
}
- /// Disable and unprepare the clock.
+ /// Disables the [`Clk`] and converts it to the [`Prepared`] state.
///
- /// Equivalent to calling [`Clk::disable`] followed by [`Clk::unprepare`].
+ /// Equivalent to the kernel's [`clk_disable`] API.
+ ///
+ /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_disable
#[inline]
- pub fn disable_unprepare(&self) {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_disable_unprepare`].
- unsafe { bindings::clk_disable_unprepare(self.as_raw()) };
+ pub fn disable(self) -> Clk<Prepared> {
+ // We will be transferring the ownership of our `clk_get()` and
+ // `clk_prepare()` counts to `Clk<Prepared>`.
+ let clk = ManuallyDrop::new(self);
+
+ // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
+ // for [`clk_disable`].
+ unsafe { bindings::clk_disable(clk.as_raw()) };
+
+ // INVARIANT: The `clk_enable()` count was released above, so the
+ // returned `Clk<Prepared>` owns the `clk_get()` and `clk_prepare()`
+ // counts.
+ Clk {
+ inner: clk.inner,
+ _phantom: PhantomData,
+ }
+ }
+ }
+
+ impl<T: ClkState> Clk<T> {
+ /// Obtain the raw [`struct clk`] pointer.
+ #[inline]
+ pub fn as_raw(&self) -> *mut bindings::clk {
+ self.inner
}
/// Get clock's rate.
///
/// Equivalent to the kernel's [`clk_get_rate`] API.
///
+ /// Note that the returned rate is only guaranteed to reflect what the
+ /// hardware is doing once the clock is [`Enabled`].
+ ///
/// [`clk_get_rate`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_rate
#[inline]
pub fn rate(&self) -> Hertz {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_get_rate`].
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid argument
+ // for [`clk_get_rate`].
Hertz(unsafe { bindings::clk_get_rate(self.as_raw()) })
}
@@ -245,88 +565,29 @@ pub fn rate(&self) -> Hertz {
/// [`clk_set_rate`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_set_rate
#[inline]
pub fn set_rate(&self, rate: Hertz) -> Result {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_set_rate`].
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid argument
+ // for [`clk_set_rate`].
to_result(unsafe { bindings::clk_set_rate(self.as_raw(), rate.as_hz()) })
}
}
- impl Drop for Clk {
+ impl<T: ClkState> Drop for Clk<T> {
fn drop(&mut self) {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for [`clk_put`].
- unsafe { bindings::clk_put(self.as_raw()) };
- }
- }
-
- /// A reference-counted optional clock.
- ///
- /// A lightweight wrapper around an optional [`Clk`]. An [`OptionalClk`] represents a [`Clk`]
- /// that a driver can function without but may improve performance or enable additional
- /// features when available.
- ///
- /// # Invariants
- ///
- /// An [`OptionalClk`] instance encapsulates a [`Clk`] with either a valid [`struct clk`] or
- /// `NULL` pointer.
- ///
- /// Instances of this type are reference-counted. Calling [`OptionalClk::get`] ensures that the
- /// allocation remains valid for the lifetime of the [`OptionalClk`].
- ///
- /// # Examples
- ///
- /// The following example demonstrates how to obtain and configure an optional clock for a
- /// device. The code functions correctly whether or not the clock is available.
- ///
- /// ```
- /// use kernel::clk::{OptionalClk, Hertz};
- /// use kernel::device::Device;
- /// use kernel::error::Result;
- ///
- /// fn configure_clk(dev: &Device) -> Result {
- /// let clk = OptionalClk::get(dev, Some(c"apb_clk"))?;
- ///
- /// clk.prepare_enable()?;
- ///
- /// let expected_rate = Hertz::from_ghz(1);
- ///
- /// if clk.rate() != expected_rate {
- /// clk.set_rate(expected_rate)?;
- /// }
- ///
- /// clk.disable_unprepare();
- /// Ok(())
- /// }
- /// ```
- ///
- /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
- pub struct OptionalClk(Clk);
-
- impl OptionalClk {
- /// Gets [`OptionalClk`] corresponding to a [`Device`] and a connection id.
- ///
- /// Equivalent to the kernel's [`clk_get_optional`] API.
- ///
- /// [`clk_get_optional`]:
- /// https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_optional
- pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
- let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
-
- // SAFETY: It is safe to call [`clk_get_optional`] for a valid device pointer.
- //
- // INVARIANT: The reference-count is decremented when [`OptionalClk`] goes out of
- // scope.
- Ok(Self(Clk(from_err_ptr(unsafe {
- bindings::clk_get_optional(dev.as_raw(), con_id)
- })?)))
- }
- }
-
- // Make [`OptionalClk`] behave like [`Clk`].
- impl Deref for OptionalClk {
- type Target = Clk;
+ if T::DISABLE_ON_DROP {
+ // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+ // [`clk_disable`].
+ unsafe { bindings::clk_disable(self.as_raw()) };
+ }
+
+ if T::UNPREPARE_ON_DROP {
+ // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+ // [`clk_unprepare`].
+ unsafe { bindings::clk_unprepare(self.as_raw()) };
+ }
- fn deref(&self) -> &Clk {
- &self.0
+ // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+ // [`clk_put`].
+ unsafe { bindings::clk_put(self.as_raw()) };
}
}
}
diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs
index d8d26870bea2..e837bb1010e0 100644
--- a/rust/kernel/cpufreq.rs
+++ b/rust/kernel/cpufreq.rs
@@ -553,8 +553,12 @@ pub fn cpus(&mut self) -> &mut cpumask::Cpumask {
/// The caller must guarantee that the returned [`Clk`] is not dropped while it is getting used
/// by the C code.
#[cfg(CONFIG_COMMON_CLK)]
- pub unsafe fn set_clk(&mut self, dev: &Device, name: Option<&CStr>) -> Result<Clk> {
- let clk = Clk::get(dev, name)?;
+ pub unsafe fn set_clk(
+ &mut self,
+ dev: &Device,
+ name: Option<&CStr>,
+ ) -> Result<Clk<crate::clk::Unprepared>> {
+ let clk = Clk::<crate::clk::Unprepared>::get_unbound(dev, name)?;
self.as_mut_ref().clk = clk.as_raw();
Ok(clk)
}
--
2.54.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [PATCH v5 2/4] rust: clk: implement Clone for Clk<T>
2026-07-06 14:37 [PATCH v5 0/4] Clk improvements Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 1/4] rust: clk: use the type-state pattern Daniel Almeida
@ 2026-07-06 14:37 ` Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 3/4] rust: clk: add devres-managed clks Daniel Almeida
` (2 subsequent siblings)
4 siblings, 0 replies; 9+ messages in thread
From: Daniel Almeida @ 2026-07-06 14:37 UTC (permalink / raw)
To: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Daniel Almeida, Michal Wilczynski,
Boqun Feng, Boqun Feng
Cc: linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Onur Özkan,
Maurice
The type-state pattern makes state transitions consume the Clk value,
which means a single Clk cannot be shared between users that need to
hold the clock in different states, nor can a driver keep a long-lived
Clk<Prepared> around while temporarily enabling it for scoped sections.
Implement Clone for Clk<T>: each clone is an independent view of the
same underlying clock, in the same state, owning its own
clk_prepare()/clk_enable() counts, e.g.:
let enabled_clk = prepared_clk.clone().enable()?;
// Do stuff that requires the clock to be enabled.
// enabled_clk goes out of scope and releases the counts it
// owns; the clock remains prepared through prepared_clk.
Since struct clk is not refcounted on the C side, share it between
clones by wrapping the pointer in an Arc'd RawClk, whose drop
implementation calls clk_put() exactly once, when the last clone goes
out of scope. This costs one small allocation per clk_get(), which was
deemed negligible when compared against the pre-existing indirections
in the clk framework.
Cloning a prepared (or enabled) Clk calls clk_prepare() (and
clk_enable()) on the underlying clock. These calls cannot fail here:
the value being cloned already holds a count of each, so the C side
only increments the respective counts. This is what makes an infallible
Clone implementation possible.
The DISABLE_ON_DROP and UNPREPARE_ON_DROP constants are renamed to
ENABLED and PREPARED respectively, since they now describe the state
for both Drop and Clone. #[repr(transparent)] is removed from Clk<T>,
as the layout is no longer transparent over the raw clk pointer.
This was proposed and discussed on the list in response to v3 [1], with
a prototype by Boris Brezillon [2].
Link: https://lore.kernel.org/r/20260203113902.501e5803@fedora [1]
Link: https://gitlab.freedesktop.org/bbrezillon/linux/-/commit/d5d04da4f4f6192b6e6760d5f861c69596c7d837 [2]
Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
---
rust/kernel/clk.rs | 181 ++++++++++++++++++++++++++++++++++++++++-------------
1 file changed, 139 insertions(+), 42 deletions(-)
diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs
index a9edfdf9db68..dd5fd656271e 100644
--- a/rust/kernel/clk.rs
+++ b/rust/kernel/clk.rs
@@ -83,6 +83,7 @@ mod common_clk {
device::{Bound, Device},
error::{from_err_ptr, to_result, Result},
prelude::*,
+ sync::Arc,
};
use core::{marker::PhantomData, mem::ManuallyDrop, ptr};
@@ -97,11 +98,11 @@ impl Sealed for super::Enabled {}
/// A trait representing the different states that a [`Clk`] can be in.
pub trait ClkState: private::Sealed {
- /// Whether the clock should be disabled when dropped.
- const DISABLE_ON_DROP: bool;
+ /// Whether the clock is enabled in this state.
+ const ENABLED: bool;
- /// Whether the clock should be unprepared when dropped.
- const UNPREPARE_ON_DROP: bool;
+ /// Whether the clock is prepared in this state.
+ const PREPARED: bool;
}
/// A state where the [`Clk`] is not prepared and not enabled.
@@ -114,18 +115,18 @@ pub trait ClkState: private::Sealed {
pub struct Enabled;
impl ClkState for Unprepared {
- const DISABLE_ON_DROP: bool = false;
- const UNPREPARE_ON_DROP: bool = false;
+ const ENABLED: bool = false;
+ const PREPARED: bool = false;
}
impl ClkState for Prepared {
- const DISABLE_ON_DROP: bool = false;
- const UNPREPARE_ON_DROP: bool = true;
+ const ENABLED: bool = false;
+ const PREPARED: bool = true;
}
impl ClkState for Enabled {
- const DISABLE_ON_DROP: bool = true;
- const UNPREPARE_ON_DROP: bool = true;
+ const ENABLED: bool = true;
+ const PREPARED: bool = true;
}
/// An error that can occur when trying to convert a [`Clk`] between states.
@@ -183,13 +184,15 @@ fn from(err: Error<State>) -> Self {
/// portion of the kernel or a `NULL` pointer.
///
/// Instances of this type are reference-counted. Calling [`Clk::get`] ensures that the
- /// allocation remains valid for the lifetime of the [`Clk`].
+ /// allocation remains valid for the lifetime of the [`Clk`] and of all its clones: the
+ /// underlying [`struct clk`] is obtained through a single call to `clk_get()`, which is
+ /// balanced by a single call to `clk_put()` when the last clone is dropped.
///
- /// The [`Prepared`] state is associated with a single count of
- /// `clk_prepare()`, and the [`Enabled`] state is associated with a single
- /// count of both `clk_prepare()` and `clk_enable()`.
- ///
- /// All states are associated with a single count of `clk_get()`.
+ /// Each [`Clk`] value owns its own state counts: the [`Prepared`] state is
+ /// associated with a single count of `clk_prepare()`, and the [`Enabled`]
+ /// state is associated with a single count of both `clk_prepare()` and
+ /// `clk_enable()`. These counts are released when the value transitions to
+ /// a lower state or is dropped.
///
/// # Examples
///
@@ -268,13 +271,57 @@ fn from(err: Error<State>) -> Self {
/// }
/// ```
///
+ /// Cloning a [`Clk`] yields an independent view of the same underlying
+ /// clock, in the same state, owning its own state counts. This lets a
+ /// driver keep e.g. a long-lived [`Clk<Prepared>`] around and temporarily
+ /// enable a clone of it:
+ ///
+ /// ```
+ /// use kernel::clk::{Clk, Enabled, Prepared};
+ /// use kernel::error::Result;
+ ///
+ /// fn use_clk(prepared_clk: &Clk<Prepared>) -> Result {
+ /// let enabled_clk: Clk<Enabled> = prepared_clk.clone().enable()?;
+ ///
+ /// // Do something that requires the clock to be enabled.
+ ///
+ /// // `enabled_clk` is dropped here and releases its own counts; the
+ /// // clock remains prepared through `prepared_clk`.
+ /// Ok(())
+ /// }
+ /// ```
+ ///
+ /// Note that cloning a [`Clk<Prepared>`] or a [`Clk<Enabled>`] may sleep.
+ ///
/// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
- #[repr(transparent)]
pub struct Clk<T: ClkState> {
- inner: *mut bindings::clk,
+ inner: Arc<RawClk>,
_phantom: core::marker::PhantomData<T>,
}
+ /// Owns a single `clk_get()` reference to a [`struct clk`].
+ ///
+ /// This is shared by every clone of a [`Clk`], so that `clk_put()` is
+ /// called exactly once, when the last clone is dropped.
+ ///
+ /// # Invariants
+ ///
+ /// The wrapped pointer is either a pointer to a valid [`struct clk`]
+ /// obtained through `clk_get()` or one of its variants, or `NULL`.
+ ///
+ /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
+ #[repr(transparent)]
+ struct RawClk(*mut bindings::clk);
+
+ impl Drop for RawClk {
+ #[inline]
+ fn drop(&mut self) {
+ // SAFETY: By the type invariants, `self.0` is a valid argument for
+ // [`clk_put`], which also accepts a `NULL` pointer.
+ unsafe { bindings::clk_put(self.0) };
+ }
+ }
+
// SAFETY: It is safe to call `clk_put` on another thread than where `clk_get` was called.
unsafe impl<T: ClkState> Send for Clk<T> {}
@@ -311,11 +358,14 @@ pub(crate) fn get_unbound(dev: &Device, name: Option<&CStr>) -> Result<Clk<Unpre
// SAFETY: It is safe to call [`clk_get`] for a valid device pointer
// and any `con_id`, including NULL.
- let inner = from_err_ptr(unsafe { bindings::clk_get(dev.as_raw(), con_id) })?;
+ let clk = from_err_ptr(unsafe { bindings::clk_get(dev.as_raw(), con_id) })?;
- // INVARIANT: The reference-count is decremented when [`Clk`] goes out of scope.
+ // INVARIANT: The single `clk_get()` reference is owned by `RawClk`,
+ // which releases it when the last clone of this [`Clk`] goes out of
+ // scope. If the allocation fails, `Arc::new` drops the `RawClk`,
+ // releasing the reference.
Ok(Self {
- inner,
+ inner: Arc::new(RawClk(clk), GFP_KERNEL)?,
_phantom: PhantomData,
})
}
@@ -329,11 +379,14 @@ pub fn get_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Unpr
// SAFETY: It is safe to call [`clk_get`] for a valid device pointer
// and any `con_id`, including NULL.
- let inner = from_err_ptr(unsafe { bindings::clk_get_optional(dev.as_raw(), con_id) })?;
+ let clk = from_err_ptr(unsafe { bindings::clk_get_optional(dev.as_raw(), con_id) })?;
- // INVARIANT: The reference-count is decremented when [`Clk`] goes out of scope.
+ // INVARIANT: The single `clk_get()` reference is owned by `RawClk`,
+ // which releases it when the last clone of this [`Clk`] goes out of
+ // scope. If the allocation fails, `Arc::new` drops the `RawClk`,
+ // releasing the reference.
Ok(Self {
- inner,
+ inner: Arc::new(RawClk(clk), GFP_KERNEL)?,
_phantom: PhantomData,
})
}
@@ -356,7 +409,10 @@ pub fn prepare(self) -> Result<Clk<Prepared>, Error<Unprepared>> {
// `Clk<Prepared>` owns a single count of it, which is released
// when it leaves the [`Prepared`] state.
.map(|()| Clk {
- inner: clk.inner,
+ // SAFETY: `clk` is wrapped in `ManuallyDrop`, so its `Arc`
+ // reference is never released; moving it out here keeps the
+ // reference count balanced.
+ inner: unsafe { ptr::read(&clk.inner) },
_phantom: PhantomData,
})
.map_err(|error| Error {
@@ -404,9 +460,12 @@ pub fn unprepare(self) -> Clk<Unprepared> {
unsafe { bindings::clk_unprepare(clk.as_raw()) }
// INVARIANT: The `clk_prepare()` count was released above, so the
- // returned `Clk<Unprepared>` owns only the `clk_get()` count.
+ // returned `Clk<Unprepared>` owns only the `clk_get()` reference.
Clk {
- inner: clk.inner,
+ // SAFETY: `clk` is wrapped in `ManuallyDrop`, so its `Arc`
+ // reference is never released; moving it out here keeps the
+ // reference count balanced.
+ inner: unsafe { ptr::read(&clk.inner) },
_phantom: PhantomData,
}
}
@@ -429,7 +488,10 @@ pub fn enable(self) -> Result<Clk<Enabled>, Error<Prepared>> {
// `Clk<Enabled>` owns a single count of it, which is released
// when it leaves the [`Enabled`] state.
.map(|()| Clk {
- inner: clk.inner,
+ // SAFETY: `clk` is wrapped in `ManuallyDrop`, so its `Arc`
+ // reference is never released; moving it out here keeps the
+ // reference count balanced.
+ inner: unsafe { ptr::read(&clk.inner) },
_phantom: PhantomData,
})
.map_err(|error| Error {
@@ -474,7 +536,10 @@ pub fn with_enabled<R>(&self, cb: impl FnOnce(&Clk<Enabled>) -> R) -> Result<R>
//
// INVARIANT: The clock is enabled for the lifetime of `enabled`.
let enabled = ManuallyDrop::new(Clk::<Enabled> {
- inner: self.inner,
+ // SAFETY: The duplicate `Arc` reference is wrapped in
+ // `ManuallyDrop` and thus never released, keeping the reference
+ // count balanced.
+ inner: unsafe { ptr::read(&self.inner) },
_phantom: PhantomData,
});
@@ -527,10 +592,13 @@ pub fn disable(self) -> Clk<Prepared> {
unsafe { bindings::clk_disable(clk.as_raw()) };
// INVARIANT: The `clk_enable()` count was released above, so the
- // returned `Clk<Prepared>` owns the `clk_get()` and `clk_prepare()`
- // counts.
+ // returned `Clk<Prepared>` owns the `clk_get()` reference and the
+ // `clk_prepare()` count.
Clk {
- inner: clk.inner,
+ // SAFETY: `clk` is wrapped in `ManuallyDrop`, so its `Arc`
+ // reference is never released; moving it out here keeps the
+ // reference count balanced.
+ inner: unsafe { ptr::read(&clk.inner) },
_phantom: PhantomData,
}
}
@@ -540,7 +608,7 @@ impl<T: ClkState> Clk<T> {
/// Obtain the raw [`struct clk`] pointer.
#[inline]
pub fn as_raw(&self) -> *mut bindings::clk {
- self.inner
+ self.inner.0
}
/// Get clock's rate.
@@ -573,21 +641,50 @@ pub fn set_rate(&self, rate: Hertz) -> Result {
impl<T: ClkState> Drop for Clk<T> {
fn drop(&mut self) {
- if T::DISABLE_ON_DROP {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_disable`].
+ if T::ENABLED {
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid
+ // argument for [`clk_disable`].
unsafe { bindings::clk_disable(self.as_raw()) };
}
- if T::UNPREPARE_ON_DROP {
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_unprepare`].
+ if T::PREPARED {
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid
+ // argument for [`clk_unprepare`].
unsafe { bindings::clk_unprepare(self.as_raw()) };
}
- // SAFETY: By the type invariants, self.as_raw() is a valid argument for
- // [`clk_put`].
- unsafe { bindings::clk_put(self.as_raw()) };
+ // The `clk_get()` reference is owned by `RawClk`: it is released
+ // by its drop implementation when the last clone goes out of scope.
+ }
+ }
+
+ impl<T: ClkState> Clone for Clk<T> {
+ #[inline]
+ fn clone(&self) -> Self {
+ if T::PREPARED {
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid
+ // argument for [`clk_prepare`]. `self` already holds a
+ // `clk_prepare()` count, so the underlying clock is already
+ // prepared and this call only increments the prepare count:
+ // it cannot fail.
+ unsafe { bindings::clk_prepare(self.as_raw()) };
+ }
+
+ if T::ENABLED {
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid
+ // argument for [`clk_enable`]. `self` already holds a
+ // `clk_enable()` count, so the underlying clock is already
+ // enabled and this call only increments the enable count: it
+ // cannot fail.
+ unsafe { bindings::clk_enable(self.as_raw()) };
+ }
+
+ // INVARIANT: The new value owns the state counts acquired above
+ // and shares the `clk_get()` reference through the `Arc`.
+ Self {
+ inner: self.inner.clone(),
+ _phantom: PhantomData,
+ }
}
}
}
--
2.54.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [PATCH v5 3/4] rust: clk: add devres-managed clks
2026-07-06 14:37 [PATCH v5 0/4] Clk improvements Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 1/4] rust: clk: use the type-state pattern Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 2/4] rust: clk: implement Clone for Clk<T> Daniel Almeida
@ 2026-07-06 14:37 ` Daniel Almeida
2026-08-01 11:22 ` Onur Özkan
2026-07-06 14:37 ` [PATCH v5 4/4] rust: clk: use 'kernel vertical style' for imports Daniel Almeida
2026-07-31 18:37 ` [PATCH v5 0/4] Clk improvements Maurice Hieronymus
4 siblings, 1 reply; 9+ messages in thread
From: Daniel Almeida @ 2026-07-06 14:37 UTC (permalink / raw)
To: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Daniel Almeida, Michal Wilczynski,
Boqun Feng, Boqun Feng
Cc: linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Onur Özkan,
Maurice
The clk API allows fine-grained control, but some drivers might be
more interested in a "set and forget" API.
Expand the current API to support this. The clock will automatically be
disabled, unprepared and freed when the device is unbound from the bus
without further intervention by the driver.
Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
---
rust/kernel/clk.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 46 insertions(+)
diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs
index dd5fd656271e..b9a44f83843a 100644
--- a/rust/kernel/clk.rs
+++ b/rust/kernel/clk.rs
@@ -96,6 +96,52 @@ impl Sealed for super::Prepared {}
impl Sealed for super::Enabled {}
}
+ /// Obtains and enables a [`devres`]-managed [`Clk`] for a bound device.
+ ///
+ /// [`devres`]: crate::devres::Devres
+ #[inline]
+ pub fn devm_enable(dev: &Device<Bound>, name: Option<&CStr>) -> Result {
+ let name = name.map_or(ptr::null(), |n| n.as_char_ptr());
+
+ // SAFETY: It is safe to call [`devm_clk_get_enabled`] with a valid
+ // device pointer.
+ from_err_ptr(unsafe { bindings::devm_clk_get_enabled(dev.as_raw(), name) })?;
+ Ok(())
+ }
+
+ /// Obtains and enables a [`devres`]-managed [`Clk`] for a bound device.
+ ///
+ /// This does not print any error messages if the clock is not found.
+ ///
+ /// [`devres`]: crate::devres::Devres
+ #[inline]
+ pub fn devm_enable_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result {
+ let name = name.map_or(ptr::null(), |n| n.as_char_ptr());
+
+ // SAFETY: It is safe to call [`devm_clk_get_optional_enabled`] with a
+ // valid device pointer.
+ from_err_ptr(unsafe { bindings::devm_clk_get_optional_enabled(dev.as_raw(), name) })?;
+ Ok(())
+ }
+
+ /// Same as [`devm_enable_optional`], but also sets the rate.
+ #[inline]
+ pub fn devm_enable_optional_with_rate(
+ dev: &Device<Bound>,
+ name: Option<&CStr>,
+ rate: Hertz,
+ ) -> Result {
+ let name = name.map_or(ptr::null(), |n| n.as_char_ptr());
+
+ // SAFETY: It is safe to call
+ // [`devm_clk_get_optional_enabled_with_rate`] with a valid device
+ // pointer.
+ from_err_ptr(unsafe {
+ bindings::devm_clk_get_optional_enabled_with_rate(dev.as_raw(), name, rate.as_hz())
+ })?;
+ Ok(())
+ }
+
/// A trait representing the different states that a [`Clk`] can be in.
pub trait ClkState: private::Sealed {
/// Whether the clock is enabled in this state.
--
2.54.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [PATCH v5 4/4] rust: clk: use 'kernel vertical style' for imports
2026-07-06 14:37 [PATCH v5 0/4] Clk improvements Daniel Almeida
` (2 preceding siblings ...)
2026-07-06 14:37 ` [PATCH v5 3/4] rust: clk: add devres-managed clks Daniel Almeida
@ 2026-07-06 14:37 ` Daniel Almeida
2026-07-31 18:37 ` [PATCH v5 0/4] Clk improvements Maurice Hieronymus
4 siblings, 0 replies; 9+ messages in thread
From: Daniel Almeida @ 2026-07-06 14:37 UTC (permalink / raw)
To: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Daniel Almeida, Michal Wilczynski,
Boqun Feng, Boqun Feng
Cc: linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Onur Özkan,
Maurice
Convert all imports to use the new import style. This will make it easier
to land new changes in the future.
No change of functionality implied.
Link: https://docs.kernel.org/rust/coding-guidelines.html#imports
Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
---
rust/kernel/clk.rs | 66 +++++++++++++++++++++++++++++++++++++++++-------------
1 file changed, 50 insertions(+), 16 deletions(-)
diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs
index b9a44f83843a..e677156ffd21 100644
--- a/rust/kernel/clk.rs
+++ b/rust/kernel/clk.rs
@@ -80,13 +80,23 @@ fn from(freq: Hertz) -> Self {
mod common_clk {
use super::Hertz;
use crate::{
- device::{Bound, Device},
- error::{from_err_ptr, to_result, Result},
+ device::{
+ Bound,
+ Device, //
+ },
+ error::{
+ from_err_ptr,
+ to_result, //
+ },
prelude::*,
- sync::Arc,
+ sync::Arc, //
};
- use core::{marker::PhantomData, mem::ManuallyDrop, ptr};
+ use core::{
+ marker::PhantomData,
+ mem::ManuallyDrop,
+ ptr, //
+ };
mod private {
pub trait Sealed {}
@@ -193,9 +203,15 @@ impl<State: ClkState> From<Error<State>> for kernel::error::Error {
/// original [`Clk`], e.g.:
///
/// ```
- /// use kernel::clk::{Clk, Enabled, Unprepared};
- /// use kernel::device::{Bound, Device};
- /// use kernel::error::Result;
+ /// use kernel::clk::{
+ /// Clk,
+ /// Enabled,
+ /// Unprepared, //
+ /// };
+ /// use kernel::device::{
+ /// Bound,
+ /// Device, //
+ /// };
///
/// fn get_enabled(dev: &Device<Bound>) -> Result<Clk<Enabled>> {
/// let clk = Clk::<Unprepared>::get(dev, Some(c"apb_clk"))?
@@ -245,9 +261,17 @@ fn from(err: Error<State>) -> Self {
/// The following example demonstrates how to obtain and configure a clock for a device.
///
/// ```
- /// use kernel::clk::{Clk, Enabled, Hertz, Unprepared, Prepared};
- /// use kernel::device::{Bound, Device};
- /// use kernel::error::Result;
+ /// use kernel::clk::{
+ /// Clk,
+ /// Enabled,
+ /// Hertz,
+ /// Prepared,
+ /// Unprepared, //
+ /// };
+ /// use kernel::device::{
+ /// Bound,
+ /// Device, //
+ /// };
///
/// fn configure_clk(dev: &Device<Bound>) -> Result {
/// // The fastest way is to use a version of `Clk::get` for the desired
@@ -292,8 +316,11 @@ fn from(err: Error<State>) -> Self {
/// and move between the variants:
///
/// ```
- /// use kernel::clk::{Clk, Enabled, Prepared};
- /// use kernel::error::Result;
+ /// use kernel::clk::{
+ /// Clk,
+ /// Enabled,
+ /// Prepared, //
+ /// };
///
/// enum DeviceClk {
/// Suspended(Clk<Prepared>),
@@ -323,8 +350,11 @@ fn from(err: Error<State>) -> Self {
/// enable a clone of it:
///
/// ```
- /// use kernel::clk::{Clk, Enabled, Prepared};
- /// use kernel::error::Result;
+ /// use kernel::clk::{
+ /// Clk,
+ /// Enabled,
+ /// Prepared, //
+ /// };
///
/// fn use_clk(prepared_clk: &Clk<Prepared>) -> Result {
/// let enabled_clk: Clk<Enabled> = prepared_clk.clone().enable()?;
@@ -556,8 +586,12 @@ pub fn enable(self) -> Result<Clk<Enabled>, Error<Prepared>> {
/// clock or threading it through an intermediate state, e.g.:
///
/// ```
- /// use kernel::clk::{Clk, Enabled, Hertz, Prepared};
- /// use kernel::error::Result;
+ /// use kernel::clk::{
+ /// Clk,
+ /// Enabled,
+ /// Hertz,
+ /// Prepared, //
+ /// };
///
/// fn read_rate(clk: &Clk<Prepared>) -> Result<Hertz> {
/// clk.with_enabled(|clk: &Clk<Enabled>| clk.rate())
--
2.54.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* Re: [PATCH v5 0/4] Clk improvements
2026-07-06 14:37 [PATCH v5 0/4] Clk improvements Daniel Almeida
` (3 preceding siblings ...)
2026-07-06 14:37 ` [PATCH v5 4/4] rust: clk: use 'kernel vertical style' for imports Daniel Almeida
@ 2026-07-31 18:37 ` Maurice Hieronymus
2026-07-31 21:32 ` Daniel Almeida
4 siblings, 1 reply; 9+ messages in thread
From: Maurice Hieronymus @ 2026-07-31 18:37 UTC (permalink / raw)
To: Daniel Almeida
Cc: Maurice Hieronymus, Rafael J. Wysocki, Viresh Kumar,
Danilo Krummrich, Alice Ryhl, Maarten Lankhorst, Maxime Ripard,
Thomas Zimmermann, David Airlie, Simona Vetter, Drew Fustini,
Guo Ren, Fu Wei, Uwe Kleine-König, Michael Turquette,
Stephen Boyd, Miguel Ojeda, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Trevor Gross, Michal Wilczynski,
Boqun Feng, Boris Brezillon, Onur Özkan, linux-pm,
linux-kernel, dri-devel, linux-riscv, linux-pwm, linux-clk,
rust-for-linux
Hi Daniel,
at your suggestion [0] I rebased my `clk_rate_exclusive_get()` binding for
pwm-th1520 on top of this series, so it is now waiting on it to land. As v5
has not seen any comments in the last few weeks, I wanted to ask what the
current status is.
If there are no blockers left and you expect it to be merged soon, I am
happy to keep waiting. Otherwise I would offer to send my series standalone
against the current `Clk` API and let you rebase on top of mine - it is the
much smaller of the two, touching only `Clk::rate_exclusive_get()` and
pwm_th1520.rs.
[0]: https://lore.kernel.org/rust-for-linux/140FE1B3-73CA-45EA-B978-648A1A48B577@collabora.com/
Thanks a lot,
Maurice
^ permalink raw reply [flat|nested] 9+ messages in thread
* Re: [PATCH v5 0/4] Clk improvements
2026-07-31 18:37 ` [PATCH v5 0/4] Clk improvements Maurice Hieronymus
@ 2026-07-31 21:32 ` Daniel Almeida
0 siblings, 0 replies; 9+ messages in thread
From: Daniel Almeida @ 2026-07-31 21:32 UTC (permalink / raw)
To: Maurice Hieronymus
Cc: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Michal Wilczynski, Boqun Feng,
Boris Brezillon, Onur Özkan, linux-pm, linux-kernel,
dri-devel, linux-riscv, linux-pwm, linux-clk, rust-for-linux
Hi Maurice,
> On 31 Jul 2026, at 15:37, Maurice Hieronymus <mhi@mailbox.org> wrote:
>
> Hi Daniel,
>
> at your suggestion [0] I rebased my `clk_rate_exclusive_get()` binding for
> pwm-th1520 on top of this series, so it is now waiting on it to land. As v5
> has not seen any comments in the last few weeks, I wanted to ask what the
> current status is.
Nobody has replied so far. I don’t think there are any further comments.
>
> If there are no blockers left and you expect it to be merged soon, I am
> happy to keep waiting. Otherwise I would offer to send my series standalone
> against the current `Clk` API and let you rebase on top of mine - it is the
> much smaller of the two, touching only `Clk::rate_exclusive_get()` and
> pwm_th1520.rs.
>
> [0]: https://lore.kernel.org/rust-for-linux/140FE1B3-73CA-45EA-B978-648A1A48B577@collabora.com/
>
> Thanks a lot,
>
> Maurice
Your series might hit the same blocker as this one. Perhaps we can try to get
both merged at the same time?
@Stephen gentle ping here :)
— Daniel
^ permalink raw reply [flat|nested] 9+ messages in thread
* Re: [PATCH v5 3/4] rust: clk: add devres-managed clks
2026-07-06 14:37 ` [PATCH v5 3/4] rust: clk: add devres-managed clks Daniel Almeida
@ 2026-08-01 11:22 ` Onur Özkan
0 siblings, 0 replies; 9+ messages in thread
From: Onur Özkan @ 2026-08-01 11:22 UTC (permalink / raw)
To: Daniel Almeida
Cc: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Michal Wilczynski, Boqun Feng,
linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Maurice
On Mon, 06 Jul 2026 11:37:14 -0300
Daniel Almeida <daniel.almeida@collabora.com> wrote:
> The clk API allows fine-grained control, but some drivers might be
> more interested in a "set and forget" API.
>
> Expand the current API to support this. The clock will automatically be
> disabled, unprepared and freed when the device is unbound from the bus
> without further intervention by the driver.
>
> Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
> ---
> rust/kernel/clk.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 46 insertions(+)
>
> diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs
> index dd5fd656271e..b9a44f83843a 100644
> --- a/rust/kernel/clk.rs
> +++ b/rust/kernel/clk.rs
> @@ -96,6 +96,52 @@ impl Sealed for super::Prepared {}
> impl Sealed for super::Enabled {}
> }
>
> + /// Obtains and enables a [`devres`]-managed [`Clk`] for a bound device.
> + ///
> + /// [`devres`]: crate::devres::Devres
> + #[inline]
> + pub fn devm_enable(dev: &Device<Bound>, name: Option<&CStr>) -> Result {
> + let name = name.map_or(ptr::null(), |n| n.as_char_ptr());
> +
> + // SAFETY: It is safe to call [`devm_clk_get_enabled`] with a valid
Intra-doc links won't work in regular comments.
> + // device pointer.
> + from_err_ptr(unsafe { bindings::devm_clk_get_enabled(dev.as_raw(), name) })?;
> + Ok(())
> + }
> +
> + /// Obtains and enables a [`devres`]-managed [`Clk`] for a bound device.
> + ///
> + /// This does not print any error messages if the clock is not found.
> + ///
> + /// [`devres`]: crate::devres::Devres
> + #[inline]
> + pub fn devm_enable_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result {
> + let name = name.map_or(ptr::null(), |n| n.as_char_ptr());
> +
> + // SAFETY: It is safe to call [`devm_clk_get_optional_enabled`] with a
> + // valid device pointer.
> + from_err_ptr(unsafe { bindings::devm_clk_get_optional_enabled(dev.as_raw(), name) })?;
> + Ok(())
> + }
> +
> + /// Same as [`devm_enable_optional`], but also sets the rate.
> + #[inline]
> + pub fn devm_enable_optional_with_rate(
> + dev: &Device<Bound>,
> + name: Option<&CStr>,
> + rate: Hertz,
> + ) -> Result {
> + let name = name.map_or(ptr::null(), |n| n.as_char_ptr());
> +
> + // SAFETY: It is safe to call
> + // [`devm_clk_get_optional_enabled_with_rate`] with a valid device
> + // pointer.
> + from_err_ptr(unsafe {
> + bindings::devm_clk_get_optional_enabled_with_rate(dev.as_raw(), name, rate.as_hz())
> + })?;
Just fyi, there's currently a bug in the C implementation of
devm_clk_get_optional_enabled_with_rate() which I caught while reviewing your
series. The fix patch is already on the list [1]. Other than that, this LGTM.
[1]: https://lore.kernel.org/all/20260801111637.304590-1-work@onurozkan.dev
Regards,
Onur
> + Ok(())
> + }
> +
> /// A trait representing the different states that a [`Clk`] can be in.
> pub trait ClkState: private::Sealed {
> /// Whether the clock is enabled in this state.
>
> --
> 2.54.0
>
^ permalink raw reply [flat|nested] 9+ messages in thread
* Re: [PATCH v5 1/4] rust: clk: use the type-state pattern
2026-07-06 14:37 ` [PATCH v5 1/4] rust: clk: use the type-state pattern Daniel Almeida
@ 2026-08-01 14:33 ` Alexandre Courbot
0 siblings, 0 replies; 9+ messages in thread
From: Alexandre Courbot @ 2026-08-01 14:33 UTC (permalink / raw)
To: Daniel Almeida
Cc: Rafael J. Wysocki, Viresh Kumar, Danilo Krummrich, Alice Ryhl,
Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, David Airlie,
Simona Vetter, Drew Fustini, Guo Ren, Fu Wei,
Uwe Kleine-König, Michael Turquette, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Trevor Gross, Michal Wilczynski, Boqun Feng,
linux-pm, linux-kernel, dri-devel, linux-riscv, linux-pwm,
linux-clk, rust-for-linux, Boris Brezillon, Onur Özkan,
Maurice
On Mon Jul 6, 2026 at 11:37 PM JST, Daniel Almeida wrote:
> The current Clk abstraction can still be improved on the following issues:
>
> a) It only keeps track of a count to clk_get(), which means that users have
> to manually call disable() and unprepare(), or a variation of those, like
> disable_unprepare().
>
> b) It allows repeated calls to prepare() or enable(), but it keeps no track
> of how often these were called, i.e., it's currently legal to write the
> following:
>
> clk.prepare();
> clk.prepare();
> clk.enable();
> clk.enable();
>
> And nothing gets undone on drop().
>
> c) It adds a OptionalClk type that is probably not needed. There is no
> "struct optional_clk" in C and we should probably not add one.
>
> d) It does not let a user express the state of the clk through the
> type system. For example, there is currently no way to encode that a Clk is
> enabled via the type system alone.
>
> In light of the Regulator abstraction that was recently merged, switch this
> abstraction to use the type-state pattern instead. It solves both a) and b)
> by establishing a number of states and the valid ways to transition between
> them. It also automatically undoes any call to clk_get(), clk_prepare() and
> clk_enable() as applicable on drop(), so users do not have to do anything
> special before Clk goes out of scope.
>
> It solves c) by removing the OptionalClk type, which is now simply encoded
> as a Clk whose inner pointer is NULL.
>
> It solves d) by directly encoding the state of the Clk into the type, e.g.:
> Clk<Enabled> is now known to be a Clk that is enabled.
>
> The INVARIANTS section for Clk is expanded to highlight the relationship
> between the states and the respective reference counts that are owned by
> each of them.
>
> The examples are expanded to highlight how a user can transition between
> states, as well as highlight some of the shortcuts built into the API.
>
> The current implementation is also more flexible, in the sense that it
> allows for more states to be added in the future. This lets us implement
> different strategies for handling clocks, including one that mimics the
> current API, allowing for multiple calls to prepare() and enable().
>
> The users (cpufreq.rs/ rcpufreq_dt.rs) were updated by this patch (and not
> a separate one) to reflect the new changes. This is needed, because
> otherwise this patch would break the build.
>
> Link: https://crates.io/crates/sealed [1]
> Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
The new API looks super nice; I really like it. A few nits/questions
inline, but regardless:
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
I will try to go through the rest of the series shortly.
> ---
> drivers/cpufreq/rcpufreq_dt.rs | 2 +-
> drivers/gpu/drm/tyr/driver.rs | 37 +--
> drivers/pwm/pwm_th1520.rs | 17 +-
> rust/kernel/clk.rs | 541 ++++++++++++++++++++++++++++++-----------
> rust/kernel/cpufreq.rs | 8 +-
> 5 files changed, 423 insertions(+), 182 deletions(-)
>
> diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs
> index f17bf64c22e2..9d2ec7df4bac 100644
> --- a/drivers/cpufreq/rcpufreq_dt.rs
> +++ b/drivers/cpufreq/rcpufreq_dt.rs
> @@ -40,7 +40,7 @@ struct CPUFreqDTDevice {
> freq_table: opp::FreqTable,
> _mask: CpumaskVar,
> _token: Option<opp::ConfigToken>,
> - _clk: Clk,
> + _clk: Clk<kernel::clk::Unprepared>,
Maybe import `kernel::clk` to shorten this a bit.
<...>
> + /// An error that can occur when trying to convert a [`Clk`] between states.
> + pub struct Error<State: ClkState> {
> + /// The error that occurred.
> + pub error: kernel::error::Error,
> +
> + /// The [`Clk`] that caused the error, so that the operation may be
> + /// retried.
> + pub clk: Clk<State>,
> + }
Can this have a `Debug` implementation? It can just forward to `error`.
> +
> + impl<State: ClkState> From<Error<State>> for kernel::error::Error {
> + /// Discards the [`Clk`] and keeps only the error code.
> + ///
> + /// This makes the fallible state transitions usable with the `?`
> + /// operator when the caller does not need to retry the operation on the
> + /// original [`Clk`], e.g.:
> + ///
> + /// ```
> + /// use kernel::clk::{Clk, Enabled, Unprepared};
> + /// use kernel::device::{Bound, Device};
> + /// use kernel::error::Result;
> + ///
> + /// fn get_enabled(dev: &Device<Bound>) -> Result<Clk<Enabled>> {
> + /// let clk = Clk::<Unprepared>::get(dev, Some(c"apb_clk"))?
> + /// .prepare()?
> + /// .enable()?;
> + /// Ok(clk)
> + /// }
> + /// ```
> + #[inline]
> + fn from(err: Error<State>) -> Self {
> + err.error
> + }
> + }
>
> /// A reference-counted clock.
> ///
> /// Rust abstraction for the C [`struct clk`].
> ///
> + /// A [`Clk`] instance represents a clock that can be in one of several
> + /// states: [`Unprepared`], [`Prepared`], or [`Enabled`].
> + ///
> + /// No action needs to be taken when a [`Clk`] is dropped. The calls to
> + /// `clk_unprepare()` and `clk_disable()` will be placed as applicable.
s/placed/made?
> + ///
> + /// An optional [`Clk`] is treated just like a regular [`Clk`], but its
> + /// inner `struct clk` pointer is `NULL`. This interfaces correctly with the
> + /// C API and also exposes all the methods of a regular [`Clk`] to users.
> + ///
> /// # Invariants
> ///
> /// A [`Clk`] instance holds either a pointer to a valid [`struct clk`] created by the C
> @@ -99,19 +185,36 @@ mod common_clk {
> /// Instances of this type are reference-counted. Calling [`Clk::get`] ensures that the
> /// allocation remains valid for the lifetime of the [`Clk`].
> ///
> + /// The [`Prepared`] state is associated with a single count of
> + /// `clk_prepare()`, and the [`Enabled`] state is associated with a single
> + /// count of both `clk_prepare()` and `clk_enable()`.
> + ///
> + /// All states are associated with a single count of `clk_get()`.
> + ///
> /// # Examples
> ///
> /// The following example demonstrates how to obtain and configure a clock for a device.
> ///
> /// ```
> - /// use kernel::clk::{Clk, Hertz};
> - /// use kernel::device::Device;
> + /// use kernel::clk::{Clk, Enabled, Hertz, Unprepared, Prepared};
> + /// use kernel::device::{Bound, Device};
> /// use kernel::error::Result;
> ///
> - /// fn configure_clk(dev: &Device) -> Result {
> - /// let clk = Clk::get(dev, Some(c"apb_clk"))?;
> + /// fn configure_clk(dev: &Device<Bound>) -> Result {
> + /// // The fastest way is to use a version of `Clk::get` for the desired
> + /// // state, i.e.:
> + /// let clk: Clk<Enabled> = Clk::<Enabled>::get(dev, Some(c"apb_clk"))?;
> + ///
> + /// // Any other state is also possible, e.g.:
> + /// let clk: Clk<Prepared> = Clk::<Prepared>::get(dev, Some(c"apb_clk"))?;
nit: maybe use a different name as this is otherwise obtaining the same
clock.
> ///
> - /// clk.prepare_enable()?;
> + /// // Later:
> + /// //
> + /// // `?` works directly thanks to `From<Error<State>>`; the failed
> + /// // `Clk` is dropped on error. Match on the returned `Error<State>`
> + /// // instead (its `clk` field is the original `Clk`) if you want to
> + /// // retry the operation.
> + /// let clk: Clk<Enabled> = clk.enable()?;
> ///
> /// let expected_rate = Hertz::from_ghz(1);
> ///
> @@ -119,122 +222,339 @@ mod common_clk {
> /// clk.set_rate(expected_rate)?;
> /// }
> ///
> - /// clk.disable_unprepare();
> + /// // Nothing is needed here. The drop implementation will undo any
> + /// // operations as appropriate.
> + /// Ok(())
> + /// }
> + ///
> + /// fn shutdown(clk: Clk<Enabled>) -> Result {
> + /// // The states can be traversed "in the reverse order" as well:
> + /// let clk: Clk<Prepared> = clk.disable();
> + ///
> + /// // This is of type `Clk<Unprepared>`.
> + /// let clk = clk.unprepare();
> + ///
> /// Ok(())
> /// }
> /// ```
> ///
> + /// Drivers that need to change a clock's state at runtime (for example to
> + /// enable it on resume and disable it on suspend) can keep it in an enum
> + /// and move between the variants:
> + ///
> + /// ```
> + /// use kernel::clk::{Clk, Enabled, Prepared};
I know patch 4 eventually fixes the imports, but a more logical ordering
would be to fix them first, as it would avoid a bit of churn. Not a big
deal though.
<...>
> + pub fn unprepare(self) -> Clk<Unprepared> {
> + // We will be transferring the ownership of our `clk_get()` count to
> + // `Clk<Unprepared>`.
> + let clk = ManuallyDrop::new(self);
> +
> + // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
> + // for [`clk_unprepare`].
> + unsafe { bindings::clk_unprepare(clk.as_raw()) }
> +
> + // INVARIANT: The `clk_prepare()` count was released above, so the
> + // returned `Clk<Unprepared>` owns only the `clk_get()` count.
> + Clk {
> + inner: clk.inner,
> + _phantom: PhantomData,
> + }
> }
>
> - /// Prepare the clock.
> + /// Attempts to convert the [`Clk`] to an [`Enabled`] state.
> ///
> - /// Equivalent to the kernel's [`clk_prepare`] API.
> + /// Equivalent to the kernel's [`clk_enable`] API.
> ///
> - /// [`clk_prepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_prepare
> + /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_enable
> #[inline]
> - pub fn prepare(&self) -> Result {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> - // [`clk_prepare`].
> - to_result(unsafe { bindings::clk_prepare(self.as_raw()) })
> + pub fn enable(self) -> Result<Clk<Enabled>, Error<Prepared>> {
Note that the `Regulator` API uses the `try_into_enabled` pattern for
state transitions that can fail. Now that these transitions are
consuming the clock, it might make sense to align?
> + // We will be transferring the ownership of our `clk_get()` and
> + // `clk_prepare()` counts to `Clk<Enabled>`.
> + let clk = ManuallyDrop::new(self);
> +
> + // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
> + // for [`clk_enable`].
> + to_result(unsafe { bindings::clk_enable(clk.as_raw()) })
> + // INVARIANT: `clk_enable()` succeeded, so the returned
> + // `Clk<Enabled>` owns a single count of it, which is released
> + // when it leaves the [`Enabled`] state.
> + .map(|()| Clk {
> + inner: clk.inner,
> + _phantom: PhantomData,
> + })
> + .map_err(|error| Error {
> + error,
> + clk: ManuallyDrop::into_inner(clk),
> + })
> }
>
> - /// Unprepare the clock.
> + /// Runs `cb` with the clock temporarily enabled.
> ///
> - /// Equivalent to the kernel's [`clk_unprepare`] API.
> + /// The clock is enabled before `cb` runs and disabled again afterwards,
> + /// so the [`Enabled`] state is scoped to the closure and the [`Clk`]
> + /// remains [`Prepared`]. This is convenient for drivers that only need
> + /// the clock running for a short, well-defined section (e.g. while
> + /// touching registers) without giving up ownership of the prepared
> + /// clock or threading it through an intermediate state, e.g.:
> ///
> - /// [`clk_unprepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_unprepare
> + /// ```
> + /// use kernel::clk::{Clk, Enabled, Hertz, Prepared};
> + /// use kernel::error::Result;
> + ///
> + /// fn read_rate(clk: &Clk<Prepared>) -> Result<Hertz> {
> + /// clk.with_enabled(|clk: &Clk<Enabled>| clk.rate())
> + /// }
> + /// ```
> + ///
> + /// Equivalent to a balanced [`clk_enable`]/[`clk_disable`] pair around
> + /// `cb`.
> + ///
> + /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_enable
> + /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_disable
> #[inline]
> - pub fn unprepare(&self) {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> - // [`clk_unprepare`].
> - unsafe { bindings::clk_unprepare(self.as_raw()) };
> + pub fn with_enabled<R>(&self, cb: impl FnOnce(&Clk<Enabled>) -> R) -> Result<R> {
> + // SAFETY: By the type invariants, `self.as_raw()` is a valid argument for
> + // [`clk_enable`].
> + to_result(unsafe { bindings::clk_enable(self.as_raw()) })?;
> +
> + // Borrow the same clock as `Clk<Enabled>` for the duration of `cb`.
> + // It must not be dropped, as that would run `clk_disable`/`clk_put`
> + // against counts owned by `self`; the matching `clk_disable` below
> + // balances the `clk_enable` above instead.
> + //
> + // INVARIANT: The clock is enabled for the lifetime of `enabled`.
> + let enabled = ManuallyDrop::new(Clk::<Enabled> {
> + inner: self.inner,
> + _phantom: PhantomData,
> + });
> +
> + let ret = cb(&enabled);
> +
> + // SAFETY: The `clk_enable` above succeeded, so this balances it.
> + // `cb` only had a shared reference, so the enable count is unchanged.
> + unsafe { bindings::clk_disable(self.as_raw()) };
> +
> + Ok(ret)
> }
> + }
>
> - /// Prepare and enable the clock.
> + impl Clk<Enabled> {
> + /// Gets [`Clk`] corresponding to a bound [`Device`] and a connection id
> + /// and then prepares and enables it.
> ///
> - /// Equivalent to calling [`Clk::prepare`] followed by [`Clk::enable`].
> + /// Equivalent to calling [`Clk::get`], followed by [`Clk::prepare`],
> + /// followed by [`Clk::enable`].
> #[inline]
> - pub fn prepare_enable(&self) -> Result {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> - // [`clk_prepare_enable`].
> - to_result(unsafe { bindings::clk_prepare_enable(self.as_raw()) })
> + pub fn get(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Enabled>> {
> + Clk::<Prepared>::get(dev, name)?
> + .enable()
> + .map_err(|error| error.error)
> + }
> +
> + /// Behaves the same as [`Self::get`], except when there is no clock
> + /// producer. In this case, instead of returning [`ENOENT`], it returns
> + /// a dummy [`Clk`].
> + #[inline]
> + pub fn get_optional(dev: &Device<Bound>, name: Option<&CStr>) -> Result<Clk<Enabled>> {
> + Clk::<Prepared>::get_optional(dev, name)?
> + .enable()
> + .map_err(|error| error.error)
> }
>
> - /// Disable and unprepare the clock.
> + /// Disables the [`Clk`] and converts it to the [`Prepared`] state.
> ///
> - /// Equivalent to calling [`Clk::disable`] followed by [`Clk::unprepare`].
> + /// Equivalent to the kernel's [`clk_disable`] API.
> + ///
> + /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_disable
> #[inline]
> - pub fn disable_unprepare(&self) {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> - // [`clk_disable_unprepare`].
> - unsafe { bindings::clk_disable_unprepare(self.as_raw()) };
> + pub fn disable(self) -> Clk<Prepared> {
> + // We will be transferring the ownership of our `clk_get()` and
> + // `clk_prepare()` counts to `Clk<Prepared>`.
> + let clk = ManuallyDrop::new(self);
> +
> + // SAFETY: By the type invariants, `clk.as_raw()` is a valid argument
> + // for [`clk_disable`].
> + unsafe { bindings::clk_disable(clk.as_raw()) };
> +
> + // INVARIANT: The `clk_enable()` count was released above, so the
> + // returned `Clk<Prepared>` owns the `clk_get()` and `clk_prepare()`
> + // counts.
> + Clk {
> + inner: clk.inner,
> + _phantom: PhantomData,
> + }
> + }
> + }
> +
> + impl<T: ClkState> Clk<T> {
> + /// Obtain the raw [`struct clk`] pointer.
> + #[inline]
> + pub fn as_raw(&self) -> *mut bindings::clk {
> + self.inner
> }
>
> /// Get clock's rate.
> ///
> /// Equivalent to the kernel's [`clk_get_rate`] API.
> ///
> + /// Note that the returned rate is only guaranteed to reflect what the
> + /// hardware is doing once the clock is [`Enabled`].
> + ///
> /// [`clk_get_rate`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_rate
> #[inline]
> pub fn rate(&self) -> Hertz {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> - // [`clk_get_rate`].
> + // SAFETY: By the type invariants, `self.as_raw()` is a valid argument
> + // for [`clk_get_rate`].
Ideally these cosmetic fixes would have been in their own patch to not
distract from the rest, but not a big deal.
> Hertz(unsafe { bindings::clk_get_rate(self.as_raw()) })
> }
>
> @@ -245,88 +565,29 @@ pub fn rate(&self) -> Hertz {
> /// [`clk_set_rate`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_set_rate
> #[inline]
> pub fn set_rate(&self, rate: Hertz) -> Result {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> - // [`clk_set_rate`].
> + // SAFETY: By the type invariants, `self.as_raw()` is a valid argument
> + // for [`clk_set_rate`].
> to_result(unsafe { bindings::clk_set_rate(self.as_raw(), rate.as_hz()) })
> }
> }
>
> - impl Drop for Clk {
> + impl<T: ClkState> Drop for Clk<T> {
> fn drop(&mut self) {
> - // SAFETY: By the type invariants, self.as_raw() is a valid argument for [`clk_put`].
> - unsafe { bindings::clk_put(self.as_raw()) };
> - }
> - }
> -
> - /// A reference-counted optional clock.
> - ///
> - /// A lightweight wrapper around an optional [`Clk`]. An [`OptionalClk`] represents a [`Clk`]
> - /// that a driver can function without but may improve performance or enable additional
> - /// features when available.
> - ///
> - /// # Invariants
> - ///
> - /// An [`OptionalClk`] instance encapsulates a [`Clk`] with either a valid [`struct clk`] or
> - /// `NULL` pointer.
> - ///
> - /// Instances of this type are reference-counted. Calling [`OptionalClk::get`] ensures that the
> - /// allocation remains valid for the lifetime of the [`OptionalClk`].
> - ///
> - /// # Examples
> - ///
> - /// The following example demonstrates how to obtain and configure an optional clock for a
> - /// device. The code functions correctly whether or not the clock is available.
> - ///
> - /// ```
> - /// use kernel::clk::{OptionalClk, Hertz};
> - /// use kernel::device::Device;
> - /// use kernel::error::Result;
> - ///
> - /// fn configure_clk(dev: &Device) -> Result {
> - /// let clk = OptionalClk::get(dev, Some(c"apb_clk"))?;
> - ///
> - /// clk.prepare_enable()?;
> - ///
> - /// let expected_rate = Hertz::from_ghz(1);
> - ///
> - /// if clk.rate() != expected_rate {
> - /// clk.set_rate(expected_rate)?;
> - /// }
> - ///
> - /// clk.disable_unprepare();
> - /// Ok(())
> - /// }
> - /// ```
> - ///
> - /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
> - pub struct OptionalClk(Clk);
> -
> - impl OptionalClk {
> - /// Gets [`OptionalClk`] corresponding to a [`Device`] and a connection id.
> - ///
> - /// Equivalent to the kernel's [`clk_get_optional`] API.
> - ///
> - /// [`clk_get_optional`]:
> - /// https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_optional
> - pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
> - let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
> -
> - // SAFETY: It is safe to call [`clk_get_optional`] for a valid device pointer.
> - //
> - // INVARIANT: The reference-count is decremented when [`OptionalClk`] goes out of
> - // scope.
> - Ok(Self(Clk(from_err_ptr(unsafe {
> - bindings::clk_get_optional(dev.as_raw(), con_id)
> - })?)))
> - }
> - }
> -
> - // Make [`OptionalClk`] behave like [`Clk`].
> - impl Deref for OptionalClk {
> - type Target = Clk;
> + if T::DISABLE_ON_DROP {
> + // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> + // [`clk_disable`].
> + unsafe { bindings::clk_disable(self.as_raw()) };
> + }
> +
> + if T::UNPREPARE_ON_DROP {
> + // SAFETY: By the type invariants, self.as_raw() is a valid argument for
> + // [`clk_unprepare`].
> + unsafe { bindings::clk_unprepare(self.as_raw()) };
With this `Drop` can sleep, this is probably worth mentioning in the
doccomment.
^ permalink raw reply [flat|nested] 9+ messages in thread
end of thread, other threads:[~2026-08-01 14:33 UTC | newest]
Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-07-06 14:37 [PATCH v5 0/4] Clk improvements Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 1/4] rust: clk: use the type-state pattern Daniel Almeida
2026-08-01 14:33 ` Alexandre Courbot
2026-07-06 14:37 ` [PATCH v5 2/4] rust: clk: implement Clone for Clk<T> Daniel Almeida
2026-07-06 14:37 ` [PATCH v5 3/4] rust: clk: add devres-managed clks Daniel Almeida
2026-08-01 11:22 ` Onur Özkan
2026-07-06 14:37 ` [PATCH v5 4/4] rust: clk: use 'kernel vertical style' for imports Daniel Almeida
2026-07-31 18:37 ` [PATCH v5 0/4] Clk improvements Maurice Hieronymus
2026-07-31 21:32 ` Daniel Almeida
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox