xref: /linux/rust/kernel/clk.rs (revision 37a93dd5c49b5fda807fd204edf2547c3493319c)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Clock abstractions.
4 //!
5 //! C header: [`include/linux/clk.h`](srctree/include/linux/clk.h)
6 //!
7 //! Reference: <https://docs.kernel.org/driver-api/clk.html>
8 
9 use crate::ffi::c_ulong;
10 
11 /// The frequency unit.
12 ///
13 /// Represents a frequency in hertz, wrapping a [`c_ulong`] value.
14 ///
15 /// # Examples
16 ///
17 /// ```
18 /// use kernel::clk::Hertz;
19 ///
20 /// let hz = 1_000_000_000;
21 /// let rate = Hertz(hz);
22 ///
23 /// assert_eq!(rate.as_hz(), hz);
24 /// assert_eq!(rate, Hertz(hz));
25 /// assert_eq!(rate, Hertz::from_khz(hz / 1_000));
26 /// assert_eq!(rate, Hertz::from_mhz(hz / 1_000_000));
27 /// assert_eq!(rate, Hertz::from_ghz(hz / 1_000_000_000));
28 /// ```
29 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
30 pub struct Hertz(pub c_ulong);
31 
32 impl Hertz {
33     const KHZ_TO_HZ: c_ulong = 1_000;
34     const MHZ_TO_HZ: c_ulong = 1_000_000;
35     const GHZ_TO_HZ: c_ulong = 1_000_000_000;
36 
37     /// Create a new instance from kilohertz (kHz)
38     pub const fn from_khz(khz: c_ulong) -> Self {
39         Self(khz * Self::KHZ_TO_HZ)
40     }
41 
42     /// Create a new instance from megahertz (MHz)
43     pub const fn from_mhz(mhz: c_ulong) -> Self {
44         Self(mhz * Self::MHZ_TO_HZ)
45     }
46 
47     /// Create a new instance from gigahertz (GHz)
48     pub const fn from_ghz(ghz: c_ulong) -> Self {
49         Self(ghz * Self::GHZ_TO_HZ)
50     }
51 
52     /// Get the frequency in hertz
53     pub const fn as_hz(&self) -> c_ulong {
54         self.0
55     }
56 
57     /// Get the frequency in kilohertz
58     pub const fn as_khz(&self) -> c_ulong {
59         self.0 / Self::KHZ_TO_HZ
60     }
61 
62     /// Get the frequency in megahertz
63     pub const fn as_mhz(&self) -> c_ulong {
64         self.0 / Self::MHZ_TO_HZ
65     }
66 
67     /// Get the frequency in gigahertz
68     pub const fn as_ghz(&self) -> c_ulong {
69         self.0 / Self::GHZ_TO_HZ
70     }
71 }
72 
73 impl From<Hertz> for c_ulong {
74     fn from(freq: Hertz) -> Self {
75         freq.0
76     }
77 }
78 
79 #[cfg(CONFIG_COMMON_CLK)]
80 mod common_clk {
81     use super::Hertz;
82     use crate::{
83         device::Device,
84         error::{from_err_ptr, to_result, Result},
85         prelude::*,
86     };
87 
88     use core::{ops::Deref, ptr};
89 
90     /// A reference-counted clock.
91     ///
92     /// Rust abstraction for the C [`struct clk`].
93     ///
94     /// # Invariants
95     ///
96     /// A [`Clk`] instance holds either a pointer to a valid [`struct clk`] created by the C
97     /// portion of the kernel or a `NULL` pointer.
98     ///
99     /// Instances of this type are reference-counted. Calling [`Clk::get`] ensures that the
100     /// allocation remains valid for the lifetime of the [`Clk`].
101     ///
102     /// # Examples
103     ///
104     /// The following example demonstrates how to obtain and configure a clock for a device.
105     ///
106     /// ```
107     /// use kernel::clk::{Clk, Hertz};
108     /// use kernel::device::Device;
109     /// use kernel::error::Result;
110     ///
111     /// fn configure_clk(dev: &Device) -> Result {
112     ///     let clk = Clk::get(dev, Some(c"apb_clk"))?;
113     ///
114     ///     clk.prepare_enable()?;
115     ///
116     ///     let expected_rate = Hertz::from_ghz(1);
117     ///
118     ///     if clk.rate() != expected_rate {
119     ///         clk.set_rate(expected_rate)?;
120     ///     }
121     ///
122     ///     clk.disable_unprepare();
123     ///     Ok(())
124     /// }
125     /// ```
126     ///
127     /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
128     #[repr(transparent)]
129     pub struct Clk(*mut bindings::clk);
130 
131     impl Clk {
132         /// Gets [`Clk`] corresponding to a [`Device`] and a connection id.
133         ///
134         /// Equivalent to the kernel's [`clk_get`] API.
135         ///
136         /// [`clk_get`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get
137         pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
138             let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
139 
140             // SAFETY: It is safe to call [`clk_get`] for a valid device pointer.
141             //
142             // INVARIANT: The reference-count is decremented when [`Clk`] goes out of scope.
143             Ok(Self(from_err_ptr(unsafe {
144                 bindings::clk_get(dev.as_raw(), con_id)
145             })?))
146         }
147 
148         /// Obtain the raw [`struct clk`] pointer.
149         #[inline]
150         pub fn as_raw(&self) -> *mut bindings::clk {
151             self.0
152         }
153 
154         /// Enable the clock.
155         ///
156         /// Equivalent to the kernel's [`clk_enable`] API.
157         ///
158         /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_enable
159         #[inline]
160         pub fn enable(&self) -> Result {
161             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
162             // [`clk_enable`].
163             to_result(unsafe { bindings::clk_enable(self.as_raw()) })
164         }
165 
166         /// Disable the clock.
167         ///
168         /// Equivalent to the kernel's [`clk_disable`] API.
169         ///
170         /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_disable
171         #[inline]
172         pub fn disable(&self) {
173             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
174             // [`clk_disable`].
175             unsafe { bindings::clk_disable(self.as_raw()) };
176         }
177 
178         /// Prepare the clock.
179         ///
180         /// Equivalent to the kernel's [`clk_prepare`] API.
181         ///
182         /// [`clk_prepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_prepare
183         #[inline]
184         pub fn prepare(&self) -> Result {
185             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
186             // [`clk_prepare`].
187             to_result(unsafe { bindings::clk_prepare(self.as_raw()) })
188         }
189 
190         /// Unprepare the clock.
191         ///
192         /// Equivalent to the kernel's [`clk_unprepare`] API.
193         ///
194         /// [`clk_unprepare`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_unprepare
195         #[inline]
196         pub fn unprepare(&self) {
197             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
198             // [`clk_unprepare`].
199             unsafe { bindings::clk_unprepare(self.as_raw()) };
200         }
201 
202         /// Prepare and enable the clock.
203         ///
204         /// Equivalent to calling [`Clk::prepare`] followed by [`Clk::enable`].
205         #[inline]
206         pub fn prepare_enable(&self) -> Result {
207             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
208             // [`clk_prepare_enable`].
209             to_result(unsafe { bindings::clk_prepare_enable(self.as_raw()) })
210         }
211 
212         /// Disable and unprepare the clock.
213         ///
214         /// Equivalent to calling [`Clk::disable`] followed by [`Clk::unprepare`].
215         #[inline]
216         pub fn disable_unprepare(&self) {
217             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
218             // [`clk_disable_unprepare`].
219             unsafe { bindings::clk_disable_unprepare(self.as_raw()) };
220         }
221 
222         /// Get clock's rate.
223         ///
224         /// Equivalent to the kernel's [`clk_get_rate`] API.
225         ///
226         /// [`clk_get_rate`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_rate
227         #[inline]
228         pub fn rate(&self) -> Hertz {
229             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
230             // [`clk_get_rate`].
231             Hertz(unsafe { bindings::clk_get_rate(self.as_raw()) })
232         }
233 
234         /// Set clock's rate.
235         ///
236         /// Equivalent to the kernel's [`clk_set_rate`] API.
237         ///
238         /// [`clk_set_rate`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_set_rate
239         #[inline]
240         pub fn set_rate(&self, rate: Hertz) -> Result {
241             // SAFETY: By the type invariants, self.as_raw() is a valid argument for
242             // [`clk_set_rate`].
243             to_result(unsafe { bindings::clk_set_rate(self.as_raw(), rate.as_hz()) })
244         }
245     }
246 
247     impl Drop for Clk {
248         fn drop(&mut self) {
249             // SAFETY: By the type invariants, self.as_raw() is a valid argument for [`clk_put`].
250             unsafe { bindings::clk_put(self.as_raw()) };
251         }
252     }
253 
254     /// A reference-counted optional clock.
255     ///
256     /// A lightweight wrapper around an optional [`Clk`]. An [`OptionalClk`] represents a [`Clk`]
257     /// that a driver can function without but may improve performance or enable additional
258     /// features when available.
259     ///
260     /// # Invariants
261     ///
262     /// An [`OptionalClk`] instance encapsulates a [`Clk`] with either a valid [`struct clk`] or
263     /// `NULL` pointer.
264     ///
265     /// Instances of this type are reference-counted. Calling [`OptionalClk::get`] ensures that the
266     /// allocation remains valid for the lifetime of the [`OptionalClk`].
267     ///
268     /// # Examples
269     ///
270     /// The following example demonstrates how to obtain and configure an optional clock for a
271     /// device. The code functions correctly whether or not the clock is available.
272     ///
273     /// ```
274     /// use kernel::clk::{OptionalClk, Hertz};
275     /// use kernel::device::Device;
276     /// use kernel::error::Result;
277     ///
278     /// fn configure_clk(dev: &Device) -> Result {
279     ///     let clk = OptionalClk::get(dev, Some(c"apb_clk"))?;
280     ///
281     ///     clk.prepare_enable()?;
282     ///
283     ///     let expected_rate = Hertz::from_ghz(1);
284     ///
285     ///     if clk.rate() != expected_rate {
286     ///         clk.set_rate(expected_rate)?;
287     ///     }
288     ///
289     ///     clk.disable_unprepare();
290     ///     Ok(())
291     /// }
292     /// ```
293     ///
294     /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html
295     pub struct OptionalClk(Clk);
296 
297     impl OptionalClk {
298         /// Gets [`OptionalClk`] corresponding to a [`Device`] and a connection id.
299         ///
300         /// Equivalent to the kernel's [`clk_get_optional`] API.
301         ///
302         /// [`clk_get_optional`]:
303         /// https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_optional
304         pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
305             let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
306 
307             // SAFETY: It is safe to call [`clk_get_optional`] for a valid device pointer.
308             //
309             // INVARIANT: The reference-count is decremented when [`OptionalClk`] goes out of
310             // scope.
311             Ok(Self(Clk(from_err_ptr(unsafe {
312                 bindings::clk_get_optional(dev.as_raw(), con_id)
313             })?)))
314         }
315     }
316 
317     // Make [`OptionalClk`] behave like [`Clk`].
318     impl Deref for OptionalClk {
319         type Target = Clk;
320 
321         fn deref(&self) -> &Clk {
322             &self.0
323         }
324     }
325 }
326 
327 #[cfg(CONFIG_COMMON_CLK)]
328 pub use common_clk::*;
329