|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! Common clock framework. |
| 4 | +//! |
| 5 | +//! C header: [`include/linux/clk.h`](../../../../include/linux/clk.h) |
| 6 | +
|
| 7 | +use crate::{bindings, error::Result, to_result}; |
| 8 | +use core::mem::ManuallyDrop; |
| 9 | + |
| 10 | +/// Represents `struct clk *`. |
| 11 | +/// |
| 12 | +/// # Invariants |
| 13 | +/// |
| 14 | +/// The pointer is valid. |
| 15 | +pub struct Clk(*mut bindings::clk); |
| 16 | + |
| 17 | +impl Clk { |
| 18 | + /// Creates new clock structure from a raw pointer. |
| 19 | + /// |
| 20 | + /// # Safety |
| 21 | + /// |
| 22 | + /// The pointer must be valid. |
| 23 | + pub unsafe fn new(clk: *mut bindings::clk) -> Self { |
| 24 | + Self(clk) |
| 25 | + } |
| 26 | + |
| 27 | + /// Returns value of the rate field of `struct clk`. |
| 28 | + pub fn get_rate(&self) -> usize { |
| 29 | + // SAFETY: the pointer is valid by the type invariant. |
| 30 | + unsafe { bindings::clk_get_rate(self.0) as usize } |
| 31 | + } |
| 32 | + |
| 33 | + /// Prepares and enables the underlying hardware clock. |
| 34 | + /// |
| 35 | + /// This function should not be called in atomic context. |
| 36 | + pub fn prepare_enable(self) -> Result<EnabledClk> { |
| 37 | + // SAFETY: the pointer is valid by the type invariant. |
| 38 | + to_result(|| unsafe { bindings::clk_prepare_enable(self.0) })?; |
| 39 | + Ok(EnabledClk(self)) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl Drop for Clk { |
| 44 | + fn drop(&mut self) { |
| 45 | + // SAFETY: the pointer is valid by the type invariant. |
| 46 | + unsafe { bindings::clk_put(self.0) }; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// A clock variant that is prepared and enabled. |
| 51 | +pub struct EnabledClk(Clk); |
| 52 | + |
| 53 | +impl EnabledClk { |
| 54 | + /// Returns value of the rate field of `struct clk`. |
| 55 | + pub fn get_rate(&self) -> usize { |
| 56 | + self.0.get_rate() |
| 57 | + } |
| 58 | + |
| 59 | + /// Disables and later unprepares the underlying hardware clock prematurely. |
| 60 | + /// |
| 61 | + /// This function should not be called in atomic context. |
| 62 | + pub fn disable_unprepare(self) -> Clk { |
| 63 | + let mut clk = ManuallyDrop::new(self); |
| 64 | + // SAFETY: the pointer is valid by the type invariant. |
| 65 | + unsafe { bindings::clk_disable_unprepare(clk.0 .0) }; |
| 66 | + core::mem::replace(&mut clk.0, Clk(core::ptr::null_mut())) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +impl Drop for EnabledClk { |
| 71 | + fn drop(&mut self) { |
| 72 | + // SAFETY: the pointer is valid by the type invariant. |
| 73 | + unsafe { bindings::clk_disable_unprepare(self.0 .0) }; |
| 74 | + } |
| 75 | +} |
0 commit comments