Debian Codegraph @

drivers/pwm/pwm_th1520.rs

raw
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2025 Samsung Electronics Co., Ltd.
3 // Author: Michal Wilczynski <[email protected]>
4
5 //! Rust T-HEAD TH1520 PWM driver
6 //!
7 //! Limitations:
8 //! - The period and duty cycle are controlled by 32-bit hardware registers,
9 //! limiting the maximum resolution.
10 //! - The driver supports continuous output mode only; one-shot mode is not
11 //! implemented.
12 //! - The controller hardware provides up to 6 PWM channels.
13 //! - Reconfiguration is glitch free - new period and duty cycle values are
14 //! latched and take effect at the start of the next period.
15 //! - Polarity is handled via a simple hardware inversion bit; arbitrary
16 //! duty cycle offsets are not supported.
17 //! - Disabling a channel is achieved by configuring its duty cycle to zero to
18 //! produce a static low output. Clearing the `start` does not reliably
19 //! force the static inactive level defined by the `INACTOUT` bit. Hence
20 //! this method is not used in this driver.
21 //!
22
23 use core::ops::Deref;
24 use kernel::{
25 clk::Clk,
26 device::{Bound, Core, Device},
27 devres,
28 io::{
29 mem::IoMem,
30 Io, //
31 },
32 of, platform,
33 prelude::*,
34 pwm, time,
35 };
36
37 const TH1520_MAX_PWM_NUM: u32 = 6;
38
39 // Register offsets
40 const fn th1520_pwm_chn_base(n: u32) -> usize {
41 (n * 0x20) as usize
42 }
43
44 const fn th1520_pwm_ctrl(n: u32) -> usize {
45 th1520_pwm_chn_base(n)
46 }
47
48 const fn th1520_pwm_per(n: u32) -> usize {
49 th1520_pwm_chn_base(n) + 0x08
50 }
51
52 const fn th1520_pwm_fp(n: u32) -> usize {
53 th1520_pwm_chn_base(n) + 0x0c
54 }
55
56 // Control register bits
57 const TH1520_PWM_START: u32 = 1 << 0;
58 const TH1520_PWM_CFG_UPDATE: u32 = 1 << 2;
59 const TH1520_PWM_CONTINUOUS_MODE: u32 = 1 << 5;
60 const TH1520_PWM_FPOUT: u32 = 1 << 8;
61
62 const TH1520_PWM_REG_SIZE: usize = 0xB0;
63
64 fn ns_to_cycles(ns: u64, rate_hz: u64) -> u64 {
65 const NSEC_PER_SEC_U64: u64 = time::NSEC_PER_SEC as u64;
66
67 ns.saturating_mul(rate_hz) / NSEC_PER_SEC_U64
68 }
69
70 fn cycles_to_ns(cycles: u64, rate_hz: u64) -> u64 {
71 const NSEC_PER_SEC_U64: u64 = time::NSEC_PER_SEC as u64;
72
73 // TODO: Replace with a kernel helper like `mul_u64_u64_div_u64_roundup`
74 // once available in Rust.
75 let numerator = cycles
76 .saturating_mul(NSEC_PER_SEC_U64)
77 .saturating_add(rate_hz - 1);
78
79 numerator / rate_hz
80 }
81
82 /// Hardware-specific waveform representation for TH1520.
83 #[derive(Copy, Clone, Debug, Default)]
84 struct Th1520WfHw {
85 period_cycles: u32,
86 duty_cycles: u32,
87 ctrl_val: u32,
88 enabled: bool,
89 }
90
91 /// The driver's private data struct. It holds all necessary devres managed resources.
92 #[pin_data(PinnedDrop)]
93 struct Th1520PwmDriverData {
94 #[pin]
95 iomem: devres::Devres<IoMem<TH1520_PWM_REG_SIZE>>,
96 clk: Clk,
97 }
98
99 // This `unsafe` implementation is a temporary necessity because the underlying `kernel::clk::Clk`
100 // type does not yet expose `Send` and `Sync` implementations. This block should be removed
101 // as soon as the clock abstraction provides these guarantees directly.
102 // TODO: Remove those unsafe impl's when Clk will support them itself.
103
104 // SAFETY: The `devres` framework requires the driver's private data to be `Send` and `Sync`.
105 // We can guarantee this because the PWM core synchronizes all callbacks, preventing concurrent
106 // access to the contained `iomem` and `clk` resources.
107 unsafe impl Send for Th1520PwmDriverData {}
108
109 // SAFETY: The same reasoning applies as for `Send`. The PWM core's synchronization
110 // guarantees that it is safe for multiple threads to have shared access (`&self`)
111 // to the driver data during callbacks.
112 unsafe impl Sync for Th1520PwmDriverData {}
113
114 impl pwm::PwmOps for Th1520PwmDriverData {
115 type WfHw = Th1520WfHw;
116
117 fn round_waveform_tohw(
118 chip: &pwm::Chip<Self>,
119 _pwm: &pwm::Device,
120 wf: &pwm::Waveform,
121 ) -> Result<pwm::RoundedWaveform<Self::WfHw>> {
122 let data = chip.drvdata();
123 let mut status = 0;
124
125 if wf.period_length_ns == 0 {
126 dev_dbg!(chip.device(), "Requested period is 0, disabling PWM.\n");
127
128 return Ok(pwm::RoundedWaveform {
129 status: 0,
130 hardware_waveform: Th1520WfHw {
131 enabled: false,
132 ..Default::default()
133 },
134 });
135 }
136
137 let rate_hz = data.clk.rate().as_hz() as u64;
138
139 let mut period_cycles = ns_to_cycles(wf.period_length_ns, rate_hz).min(u64::from(u32::MAX));
140
141 if period_cycles == 0 {
142 dev_dbg!(
143 chip.device(),
144 "Requested period {} ns is too small for clock rate {} Hz, rounding up.\n",
145 wf.period_length_ns,
146 rate_hz
147 );
148
149 period_cycles = 1;
150 status = 1;
151 }
152
153 let mut duty_cycles = ns_to_cycles(wf.duty_length_ns, rate_hz).min(u64::from(u32::MAX));
154
155 let mut ctrl_val = TH1520_PWM_CONTINUOUS_MODE;
156
157 let is_inversed = wf.duty_length_ns > 0
158 && wf.duty_offset_ns > 0
159 && wf.duty_offset_ns >= wf.period_length_ns.saturating_sub(wf.duty_length_ns);
160 if is_inversed {
161 duty_cycles = period_cycles - duty_cycles;
162 } else {
163 ctrl_val |= TH1520_PWM_FPOUT;
164 }
165
166 let wfhw = Th1520WfHw {
167 // The cast is safe because the value was clamped with `.min(u64::from(u32::MAX))`.
168 period_cycles: period_cycles as u32,
169 duty_cycles: duty_cycles as u32,
170 ctrl_val,
171 enabled: true,
172 };
173
174 dev_dbg!(
175 chip.device(),
176 "Requested: {}/{} ns [+{} ns] -> HW: {}/{} cycles, ctrl 0x{:x}, rate {} Hz\n",
177 wf.duty_length_ns,
178 wf.period_length_ns,
179 wf.duty_offset_ns,
180 wfhw.duty_cycles,
181 wfhw.period_cycles,
182 wfhw.ctrl_val,
183 rate_hz
184 );
185
186 Ok(pwm::RoundedWaveform {
187 status,
188 hardware_waveform: wfhw,
189 })
190 }
191
192 fn round_waveform_fromhw(
193 chip: &pwm::Chip<Self>,
194 _pwm: &pwm::Device,
195 wfhw: &Self::WfHw,
196 wf: &mut pwm::Waveform,
197 ) -> Result {
198 let data = chip.drvdata();
199 let rate_hz = data.clk.rate().as_hz() as u64;
200
201 if wfhw.period_cycles == 0 {
202 dev_dbg!(
203 chip.device(),
204 "HW state has zero period, reporting as disabled.\n"
205 );
206 *wf = pwm::Waveform::default();
207 return Ok(());
208 }
209
210 wf.period_length_ns = cycles_to_ns(u64::from(wfhw.period_cycles), rate_hz);
211
212 let duty_cycles = u64::from(wfhw.duty_cycles);
213
214 if (wfhw.ctrl_val & TH1520_PWM_FPOUT) != 0 {
215 wf.duty_length_ns = cycles_to_ns(duty_cycles, rate_hz);
216 wf.duty_offset_ns = 0;
217 } else {
218 let period_cycles = u64::from(wfhw.period_cycles);
219 let original_duty_cycles = period_cycles.saturating_sub(duty_cycles);
220
221 // For an inverted signal, `duty_length_ns` is the high time (period - low_time).
222 wf.duty_length_ns = cycles_to_ns(original_duty_cycles, rate_hz);
223 // The offset is the initial low time, which is what the hardware register provides.
224 wf.duty_offset_ns = cycles_to_ns(duty_cycles, rate_hz);
225 }
226
227 Ok(())
228 }
229
230 fn read_waveform(
231 chip: &pwm::Chip<Self>,
232 pwm: &pwm::Device,
233 parent_dev: &Device<Bound>,
234 ) -> Result<Self::WfHw> {
235 let data = chip.drvdata();
236 let hwpwm = pwm.hwpwm();
237 let iomem_accessor = data.iomem.access(parent_dev)?;
238 let iomap = iomem_accessor.deref();
239
240 let ctrl = iomap.try_read32(th1520_pwm_ctrl(hwpwm))?;
241 let period_cycles = iomap.try_read32(th1520_pwm_per(hwpwm))?;
242 let duty_cycles = iomap.try_read32(th1520_pwm_fp(hwpwm))?;
243
244 let wfhw = Th1520WfHw {
245 period_cycles,
246 duty_cycles,
247 ctrl_val: ctrl,
248 enabled: duty_cycles != 0,
249 };
250
251 dev_dbg!(
252 chip.device(),
253 "PWM-{}: read_waveform: Read hw state - period: {}, duty: {}, ctrl: 0x{:x}, enabled: {}",
254 hwpwm,
255 wfhw.period_cycles,
256 wfhw.duty_cycles,
257 wfhw.ctrl_val,
258 wfhw.enabled
259 );
260
261 Ok(wfhw)
262 }
263
264 fn write_waveform(
265 chip: &pwm::Chip<Self>,
266 pwm: &pwm::Device,
267 wfhw: &Self::WfHw,
268 parent_dev: &Device<Bound>,
269 ) -> Result {
270 let data = chip.drvdata();
271 let hwpwm = pwm.hwpwm();
272 let iomem_accessor = data.iomem.access(parent_dev)?;
273 let iomap = iomem_accessor.deref();
274 let duty_cycles = iomap.try_read32(th1520_pwm_fp(hwpwm))?;
275 let was_enabled = duty_cycles != 0;
276
277 if !wfhw.enabled {
278 dev_dbg!(chip.device(), "PWM-{}: Disabling channel.\n", hwpwm);
279 if was_enabled {
280 iomap.try_write32(wfhw.ctrl_val, th1520_pwm_ctrl(hwpwm))?;
281 iomap.try_write32(0, th1520_pwm_fp(hwpwm))?;
282 iomap.try_write32(
283 wfhw.ctrl_val | TH1520_PWM_CFG_UPDATE,
284 th1520_pwm_ctrl(hwpwm),
285 )?;
286 }
287 return Ok(());
288 }
289
290 iomap.try_write32(wfhw.ctrl_val, th1520_pwm_ctrl(hwpwm))?;
291 iomap.try_write32(wfhw.period_cycles, th1520_pwm_per(hwpwm))?;
292 iomap.try_write32(wfhw.duty_cycles, th1520_pwm_fp(hwpwm))?;
293 iomap.try_write32(
294 wfhw.ctrl_val | TH1520_PWM_CFG_UPDATE,
295 th1520_pwm_ctrl(hwpwm),
296 )?;
297
298 // The `TH1520_PWM_START` bit must be written in a separate, final transaction, and
299 // only when enabling the channel from a disabled state.
300 if !was_enabled {
301 iomap.try_write32(wfhw.ctrl_val | TH1520_PWM_START, th1520_pwm_ctrl(hwpwm))?;
302 }
303
304 dev_dbg!(
305 chip.device(),
306 "PWM-{}: Wrote {}/{} cycles",
307 hwpwm,
308 wfhw.duty_cycles,
309 wfhw.period_cycles,
310 );
311
312 Ok(())
313 }
314 }
315
316 #[pinned_drop]
317 impl PinnedDrop for Th1520PwmDriverData {
318 fn drop(self: Pin<&mut Self>) {
319 self.clk.disable_unprepare();
320 }
321 }
322
323 struct Th1520PwmPlatformDriver;
324
325 kernel::of_device_table!(
326 OF_TABLE,
327 MODULE_OF_TABLE,
328 <Th1520PwmPlatformDriver as platform::Driver>::IdInfo,
329 [(of::DeviceId::new(c"thead,th1520-pwm"), ())]
330 );
331
332 impl platform::Driver for Th1520PwmPlatformDriver {
333 type IdInfo = ();
334 const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
335
336 fn probe(
337 pdev: &platform::Device<Core>,
338 _id_info: Option<&Self::IdInfo>,
339 ) -> impl PinInit<Self, Error> {
340 let dev = pdev.as_ref();
341 let request = pdev.io_request_by_index(0).ok_or(ENODEV)?;
342
343 let clk = Clk::get(dev, None)?;
344
345 clk.prepare_enable()?;
346
347 // TODO: Get exclusive ownership of the clock to prevent rate changes.
348 // The Rust equivalent of `clk_rate_exclusive_get()` is not yet available.
349 // This should be updated once it is implemented.
350 let rate_hz = clk.rate().as_hz();
351 if rate_hz == 0 {
352 dev_err!(dev, "Clock rate is zero\n");
353 return Err(EINVAL);
354 }
355
356 if rate_hz > time::NSEC_PER_SEC as usize {
357 dev_err!(
358 dev,
359 "Clock rate {} Hz is too high, not supported.\n",
360 rate_hz
361 );
362 return Err(EINVAL);
363 }
364
365 let chip = pwm::Chip::new(
366 dev,
367 TH1520_MAX_PWM_NUM,
368 try_pin_init!(Th1520PwmDriverData {
369 iomem <- request.iomap_sized::<TH1520_PWM_REG_SIZE>(),
370 clk <- clk,
371 }),
372 )?;
373
374 chip.register()?;
375
376 Ok(Th1520PwmPlatformDriver)
377 }
378 }
379
380 kernel::module_pwm_platform_driver! {
381 type: Th1520PwmPlatformDriver,
382 name: "pwm-th1520",
383 authors: ["Michal Wilczynski <[email protected]>"],
384 description: "T-HEAD TH1520 PWM driver",
385 license: "GPL v2",
386 }