xref: /linux/drivers/pwm/pwm-stm32.c (revision ab93e0dd72c37d378dd936f031ffb83ff2bd87ce)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STMicroelectronics 2016
4  *
5  * Author: Gerald Baeza <gerald.baeza@st.com>
6  *
7  * Inspired by timer-stm32.c from Maxime Coquelin
8  *             pwm-atmel.c from Bo Shen
9  */
10 
11 #include <linux/bitfield.h>
12 #include <linux/mfd/stm32-timers.h>
13 #include <linux/module.h>
14 #include <linux/of.h>
15 #include <linux/pinctrl/consumer.h>
16 #include <linux/platform_device.h>
17 #include <linux/pwm.h>
18 
19 #define CCMR_CHANNEL_SHIFT 8
20 #define CCMR_CHANNEL_MASK  0xFF
21 #define MAX_BREAKINPUT 2
22 #define STM32_MAX_PWM_OUTPUT 4
23 
24 struct stm32_breakinput {
25 	u32 index;
26 	u32 level;
27 	u32 filter;
28 };
29 
30 struct stm32_pwm {
31 	struct mutex lock; /* protect pwm config/enable */
32 	struct clk *clk;
33 	struct regmap *regmap;
34 	u32 max_arr;
35 	bool have_complementary_output;
36 	struct stm32_breakinput breakinputs[MAX_BREAKINPUT];
37 	unsigned int num_breakinputs;
38 	u32 capture[4] ____cacheline_aligned; /* DMA'able buffer */
39 };
40 
to_stm32_pwm_dev(struct pwm_chip * chip)41 static inline struct stm32_pwm *to_stm32_pwm_dev(struct pwm_chip *chip)
42 {
43 	return pwmchip_get_drvdata(chip);
44 }
45 
active_channels(struct stm32_pwm * dev)46 static u32 active_channels(struct stm32_pwm *dev)
47 {
48 	u32 ccer;
49 
50 	regmap_read(dev->regmap, TIM_CCER, &ccer);
51 
52 	return ccer & TIM_CCER_CCXE;
53 }
54 
55 struct stm32_pwm_waveform {
56 	u32 ccer;
57 	u32 psc;
58 	u32 arr;
59 	u32 ccr;
60 };
61 
stm32_pwm_round_waveform_tohw(struct pwm_chip * chip,struct pwm_device * pwm,const struct pwm_waveform * wf,void * _wfhw)62 static int stm32_pwm_round_waveform_tohw(struct pwm_chip *chip,
63 					 struct pwm_device *pwm,
64 					 const struct pwm_waveform *wf,
65 					 void *_wfhw)
66 {
67 	struct stm32_pwm_waveform *wfhw = _wfhw;
68 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
69 	unsigned int ch = pwm->hwpwm;
70 	unsigned long rate;
71 	u64 ccr, duty;
72 	int ret;
73 
74 	if (wf->period_length_ns == 0) {
75 		*wfhw = (struct stm32_pwm_waveform){
76 			.ccer = 0,
77 		};
78 
79 		return 0;
80 	}
81 
82 	ret = clk_enable(priv->clk);
83 	if (ret)
84 		return ret;
85 
86 	wfhw->ccer = TIM_CCER_CCxE(ch + 1);
87 	if (priv->have_complementary_output)
88 		wfhw->ccer |= TIM_CCER_CCxNE(ch + 1);
89 
90 	rate = clk_get_rate(priv->clk);
91 
92 	if (active_channels(priv) & ~TIM_CCER_CCxE(ch + 1)) {
93 		u64 arr;
94 
95 		/*
96 		 * Other channels are already enabled, so the configured PSC and
97 		 * ARR must be used for this channel, too.
98 		 */
99 		ret = regmap_read(priv->regmap, TIM_PSC, &wfhw->psc);
100 		if (ret)
101 			goto out;
102 
103 		ret = regmap_read(priv->regmap, TIM_ARR, &wfhw->arr);
104 		if (ret)
105 			goto out;
106 
107 		arr = mul_u64_u64_div_u64(wf->period_length_ns, rate,
108 					  (u64)NSEC_PER_SEC * (wfhw->psc + 1));
109 		if (arr <= wfhw->arr) {
110 			/*
111 			 * requested period is smaller than the currently
112 			 * configured and unchangable period, report back the smallest
113 			 * possible period, i.e. the current state and return 1
114 			 * to indicate the wrong rounding direction.
115 			 */
116 			ret = 1;
117 		}
118 
119 	} else {
120 		/*
121 		 * .probe() asserted that clk_get_rate() is not bigger than 1 GHz, so
122 		 * the calculations here won't overflow.
123 		 * First we need to find the minimal value for prescaler such that
124 		 *
125 		 *        period_ns * clkrate
126 		 *   ------------------------------ < max_arr + 1
127 		 *   NSEC_PER_SEC * (prescaler + 1)
128 		 *
129 		 * This equation is equivalent to
130 		 *
131 		 *        period_ns * clkrate
132 		 *   ---------------------------- < prescaler + 1
133 		 *   NSEC_PER_SEC * (max_arr + 1)
134 		 *
135 		 * Using integer division and knowing that the right hand side is
136 		 * integer, this is further equivalent to
137 		 *
138 		 *   (period_ns * clkrate) // (NSEC_PER_SEC * (max_arr + 1)) ≤ prescaler
139 		 */
140 		u64 psc = mul_u64_u64_div_u64(wf->period_length_ns, rate,
141 					      (u64)NSEC_PER_SEC * ((u64)priv->max_arr + 1));
142 		u64 arr;
143 
144 		wfhw->psc = min_t(u64, psc, MAX_TIM_PSC);
145 
146 		arr = mul_u64_u64_div_u64(wf->period_length_ns, rate,
147 					  (u64)NSEC_PER_SEC * (wfhw->psc + 1));
148 		if (!arr) {
149 			/*
150 			 * requested period is too small, report back the smallest
151 			 * possible period, i.e. ARR = 0. The only valid CCR
152 			 * value is then zero, too.
153 			 */
154 			wfhw->arr = 0;
155 			wfhw->ccr = 0;
156 			ret = 1;
157 			goto out;
158 		}
159 
160 		/*
161 		 * ARR is limited intentionally to values less than
162 		 * priv->max_arr to allow 100% duty cycle.
163 		 */
164 		wfhw->arr = min_t(u64, arr, priv->max_arr) - 1;
165 	}
166 
167 	duty = mul_u64_u64_div_u64(wf->duty_length_ns, rate,
168 				   (u64)NSEC_PER_SEC * (wfhw->psc + 1));
169 	duty = min_t(u64, duty, wfhw->arr + 1);
170 
171 	if (wf->duty_length_ns && wf->duty_offset_ns &&
172 	    wf->duty_length_ns + wf->duty_offset_ns >= wf->period_length_ns) {
173 		wfhw->ccer |= TIM_CCER_CCxP(ch + 1);
174 		if (priv->have_complementary_output)
175 			wfhw->ccer |= TIM_CCER_CCxNP(ch + 1);
176 
177 		ccr = wfhw->arr + 1 - duty;
178 	} else {
179 		ccr = duty;
180 	}
181 
182 	wfhw->ccr = min_t(u64, ccr, wfhw->arr + 1);
183 
184 out:
185 	dev_dbg(&chip->dev, "pwm#%u: %lld/%lld [+%lld] @%lu -> CCER: %08x, PSC: %08x, ARR: %08x, CCR: %08x\n",
186 		pwm->hwpwm, wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns,
187 		rate, wfhw->ccer, wfhw->psc, wfhw->arr, wfhw->ccr);
188 
189 	clk_disable(priv->clk);
190 
191 	return ret;
192 }
193 
194 /*
195  * This should be moved to lib/math/div64.c. Currently there are some changes
196  * pending to mul_u64_u64_div_u64. Uwe will care for that when the dust settles.
197  */
stm32_pwm_mul_u64_u64_div_u64_roundup(u64 a,u64 b,u64 c)198 static u64 stm32_pwm_mul_u64_u64_div_u64_roundup(u64 a, u64 b, u64 c)
199 {
200 	u64 res = mul_u64_u64_div_u64(a, b, c);
201 	/* Those multiplications might overflow but it doesn't matter */
202 	u64 rem = a * b - c * res;
203 
204 	if (rem)
205 		res += 1;
206 
207 	return res;
208 }
209 
stm32_pwm_round_waveform_fromhw(struct pwm_chip * chip,struct pwm_device * pwm,const void * _wfhw,struct pwm_waveform * wf)210 static int stm32_pwm_round_waveform_fromhw(struct pwm_chip *chip,
211 					   struct pwm_device *pwm,
212 					   const void *_wfhw,
213 					   struct pwm_waveform *wf)
214 {
215 	const struct stm32_pwm_waveform *wfhw = _wfhw;
216 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
217 	unsigned long rate = clk_get_rate(priv->clk);
218 	unsigned int ch = pwm->hwpwm;
219 
220 	if (wfhw->ccer & TIM_CCER_CCxE(ch + 1)) {
221 		u64 ccr_ns;
222 
223 		/* The result doesn't overflow for rate >= 15259 */
224 		wf->period_length_ns = stm32_pwm_mul_u64_u64_div_u64_roundup(((u64)wfhw->psc + 1) * (wfhw->arr + 1),
225 									     NSEC_PER_SEC, rate);
226 
227 		ccr_ns = stm32_pwm_mul_u64_u64_div_u64_roundup(((u64)wfhw->psc + 1) * wfhw->ccr,
228 							       NSEC_PER_SEC, rate);
229 
230 		if (wfhw->ccer & TIM_CCER_CCxP(ch + 1)) {
231 			wf->duty_length_ns =
232 				stm32_pwm_mul_u64_u64_div_u64_roundup(((u64)wfhw->psc + 1) * (wfhw->arr + 1 - wfhw->ccr),
233 								      NSEC_PER_SEC, rate);
234 
235 			wf->duty_offset_ns = ccr_ns;
236 		} else {
237 			wf->duty_length_ns = ccr_ns;
238 			wf->duty_offset_ns = 0;
239 		}
240 	} else {
241 		*wf = (struct pwm_waveform){
242 			.period_length_ns = 0,
243 		};
244 	}
245 
246 	dev_dbg(&chip->dev, "pwm#%u: CCER: %08x, PSC: %08x, ARR: %08x, CCR: %08x @%lu -> %lld/%lld [+%lld]\n",
247 		pwm->hwpwm, wfhw->ccer, wfhw->psc, wfhw->arr, wfhw->ccr, rate,
248 		wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns);
249 
250 	return 0;
251 }
252 
stm32_pwm_read_waveform(struct pwm_chip * chip,struct pwm_device * pwm,void * _wfhw)253 static int stm32_pwm_read_waveform(struct pwm_chip *chip,
254 				     struct pwm_device *pwm,
255 				     void *_wfhw)
256 {
257 	struct stm32_pwm_waveform *wfhw = _wfhw;
258 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
259 	unsigned int ch = pwm->hwpwm;
260 	int ret;
261 
262 	ret = clk_enable(priv->clk);
263 	if (ret)
264 		return ret;
265 
266 	ret = regmap_read(priv->regmap, TIM_CCER, &wfhw->ccer);
267 	if (ret)
268 		goto out;
269 
270 	if (wfhw->ccer & TIM_CCER_CCxE(ch + 1)) {
271 		ret = regmap_read(priv->regmap, TIM_PSC, &wfhw->psc);
272 		if (ret)
273 			goto out;
274 
275 		ret = regmap_read(priv->regmap, TIM_ARR, &wfhw->arr);
276 		if (ret)
277 			goto out;
278 
279 		if (wfhw->arr == U32_MAX)
280 			wfhw->arr -= 1;
281 
282 		ret = regmap_read(priv->regmap, TIM_CCRx(ch + 1), &wfhw->ccr);
283 		if (ret)
284 			goto out;
285 
286 		if (wfhw->ccr > wfhw->arr + 1)
287 			wfhw->ccr = wfhw->arr + 1;
288 	}
289 
290 out:
291 	clk_disable(priv->clk);
292 
293 	return ret;
294 }
295 
stm32_pwm_write_waveform(struct pwm_chip * chip,struct pwm_device * pwm,const void * _wfhw)296 static int stm32_pwm_write_waveform(struct pwm_chip *chip,
297 				      struct pwm_device *pwm,
298 				      const void *_wfhw)
299 {
300 	const struct stm32_pwm_waveform *wfhw = _wfhw;
301 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
302 	unsigned int ch = pwm->hwpwm;
303 	int ret;
304 
305 	ret = clk_enable(priv->clk);
306 	if (ret)
307 		return ret;
308 
309 	if (wfhw->ccer & TIM_CCER_CCxE(ch + 1)) {
310 		u32 ccer, mask;
311 		unsigned int shift;
312 		u32 ccmr;
313 
314 		ret = regmap_read(priv->regmap, TIM_CCER, &ccer);
315 		if (ret)
316 			goto out;
317 
318 		/* If there are other channels enabled, don't update PSC and ARR */
319 		if (ccer & ~TIM_CCER_CCxE(ch + 1) & TIM_CCER_CCXE) {
320 			u32 psc, arr;
321 
322 			ret = regmap_read(priv->regmap, TIM_PSC, &psc);
323 			if (ret)
324 				goto out;
325 
326 			if (psc != wfhw->psc) {
327 				ret = -EBUSY;
328 				goto out;
329 			}
330 
331 			ret = regmap_read(priv->regmap, TIM_ARR, &arr);
332 			if (ret)
333 				goto out;
334 
335 			if (arr != wfhw->arr) {
336 				ret = -EBUSY;
337 				goto out;
338 			}
339 		} else {
340 			ret = regmap_write(priv->regmap, TIM_PSC, wfhw->psc);
341 			if (ret)
342 				goto out;
343 
344 			ret = regmap_write(priv->regmap, TIM_ARR, wfhw->arr);
345 			if (ret)
346 				goto out;
347 
348 			ret = regmap_set_bits(priv->regmap, TIM_CR1, TIM_CR1_ARPE);
349 			if (ret)
350 				goto out;
351 
352 		}
353 
354 		/* set polarity */
355 		mask = TIM_CCER_CCxP(ch + 1) | TIM_CCER_CCxNP(ch + 1);
356 		ret = regmap_update_bits(priv->regmap, TIM_CCER, mask, wfhw->ccer);
357 		if (ret)
358 			goto out;
359 
360 		ret = regmap_write(priv->regmap, TIM_CCRx(ch + 1), wfhw->ccr);
361 		if (ret)
362 			goto out;
363 
364 		/* Configure output mode */
365 		shift = (ch & 0x1) * CCMR_CHANNEL_SHIFT;
366 		ccmr = (TIM_CCMR_PE | TIM_CCMR_M1) << shift;
367 		mask = CCMR_CHANNEL_MASK << shift;
368 
369 		if (ch < 2)
370 			ret = regmap_update_bits(priv->regmap, TIM_CCMR1, mask, ccmr);
371 		else
372 			ret = regmap_update_bits(priv->regmap, TIM_CCMR2, mask, ccmr);
373 		if (ret)
374 			goto out;
375 
376 		ret = regmap_set_bits(priv->regmap, TIM_BDTR, TIM_BDTR_MOE);
377 		if (ret)
378 			goto out;
379 
380 		if (!(ccer & TIM_CCER_CCxE(ch + 1))) {
381 			mask = TIM_CCER_CCxE(ch + 1) | TIM_CCER_CCxNE(ch + 1);
382 
383 			ret = clk_enable(priv->clk);
384 			if (ret)
385 				goto out;
386 
387 			ccer = (ccer & ~mask) | (wfhw->ccer & mask);
388 			regmap_write(priv->regmap, TIM_CCER, ccer);
389 
390 			/* Make sure that registers are updated */
391 			regmap_set_bits(priv->regmap, TIM_EGR, TIM_EGR_UG);
392 
393 			/* Enable controller */
394 			regmap_set_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN);
395 		}
396 
397 	} else {
398 		/* disable channel */
399 		u32 mask, ccer;
400 
401 		mask = TIM_CCER_CCxE(ch + 1);
402 		if (priv->have_complementary_output)
403 			mask |= TIM_CCER_CCxNE(ch + 1);
404 
405 		ret = regmap_read(priv->regmap, TIM_CCER, &ccer);
406 		if (ret)
407 			goto out;
408 
409 		if (ccer & mask) {
410 			ccer = ccer & ~mask;
411 
412 			ret = regmap_write(priv->regmap, TIM_CCER, ccer);
413 			if (ret)
414 				goto out;
415 
416 			if (!(ccer & TIM_CCER_CCXE)) {
417 				/* When all channels are disabled, we can disable the controller */
418 				ret = regmap_clear_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN);
419 				if (ret)
420 					goto out;
421 			}
422 
423 			clk_disable(priv->clk);
424 		}
425 	}
426 
427 out:
428 	clk_disable(priv->clk);
429 
430 	return ret;
431 }
432 
433 #define TIM_CCER_CC12P (TIM_CCER_CC1P | TIM_CCER_CC2P)
434 #define TIM_CCER_CC12E (TIM_CCER_CC1E | TIM_CCER_CC2E)
435 #define TIM_CCER_CC34P (TIM_CCER_CC3P | TIM_CCER_CC4P)
436 #define TIM_CCER_CC34E (TIM_CCER_CC3E | TIM_CCER_CC4E)
437 
438 /*
439  * Capture using PWM input mode:
440  *                              ___          ___
441  * TI[1, 2, 3 or 4]: ........._|   |________|
442  *                             ^0  ^1       ^2
443  *                              .   .        .
444  *                              .   .        XXXXX
445  *                              .   .   XXXXX     |
446  *                              .  XXXXX     .    |
447  *                            XXXXX .        .    |
448  * COUNTER:        ______XXXXX  .   .        .    |_XXX
449  *                 start^       .   .        .        ^stop
450  *                      .       .   .        .
451  *                      v       v   .        v
452  *                                  v
453  * CCR1/CCR3:       tx..........t0...........t2
454  * CCR2/CCR4:       tx..............t1.........
455  *
456  * DMA burst transfer:          |            |
457  *                              v            v
458  * DMA buffer:                  { t0, tx }   { t2, t1 }
459  * DMA done:                                 ^
460  *
461  * 0: IC1/3 snapchot on rising edge: counter value -> CCR1/CCR3
462  *    + DMA transfer CCR[1/3] & CCR[2/4] values (t0, tx: doesn't care)
463  * 1: IC2/4 snapchot on falling edge: counter value -> CCR2/CCR4
464  * 2: IC1/3 snapchot on rising edge: counter value -> CCR1/CCR3
465  *    + DMA transfer CCR[1/3] & CCR[2/4] values (t2, t1)
466  *
467  * DMA done, compute:
468  * - Period     = t2 - t0
469  * - Duty cycle = t1 - t0
470  */
stm32_pwm_raw_capture(struct pwm_chip * chip,struct pwm_device * pwm,unsigned long tmo_ms,u32 * raw_prd,u32 * raw_dty)471 static int stm32_pwm_raw_capture(struct pwm_chip *chip, struct pwm_device *pwm,
472 				 unsigned long tmo_ms, u32 *raw_prd,
473 				 u32 *raw_dty)
474 {
475 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
476 	struct device *parent = pwmchip_parent(chip)->parent;
477 	enum stm32_timers_dmas dma_id;
478 	u32 ccen, ccr;
479 	int ret;
480 
481 	/* Ensure registers have been updated, enable counter and capture */
482 	regmap_set_bits(priv->regmap, TIM_EGR, TIM_EGR_UG);
483 	regmap_set_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN);
484 
485 	/* Use cc1 or cc3 DMA resp for PWM input channels 1 & 2 or 3 & 4 */
486 	dma_id = pwm->hwpwm < 2 ? STM32_TIMERS_DMA_CH1 : STM32_TIMERS_DMA_CH3;
487 	ccen = pwm->hwpwm < 2 ? TIM_CCER_CC12E : TIM_CCER_CC34E;
488 	ccr = pwm->hwpwm < 2 ? TIM_CCR1 : TIM_CCR3;
489 	regmap_set_bits(priv->regmap, TIM_CCER, ccen);
490 
491 	/*
492 	 * Timer DMA burst mode. Request 2 registers, 2 bursts, to get both
493 	 * CCR1 & CCR2 (or CCR3 & CCR4) on each capture event.
494 	 * We'll get two capture snapchots: { CCR1, CCR2 }, { CCR1, CCR2 }
495 	 * or { CCR3, CCR4 }, { CCR3, CCR4 }
496 	 */
497 	ret = stm32_timers_dma_burst_read(parent, priv->capture, dma_id, ccr, 2,
498 					  2, tmo_ms);
499 	if (ret)
500 		goto stop;
501 
502 	/* Period: t2 - t0 (take care of counter overflow) */
503 	if (priv->capture[0] <= priv->capture[2])
504 		*raw_prd = priv->capture[2] - priv->capture[0];
505 	else
506 		*raw_prd = priv->max_arr - priv->capture[0] + priv->capture[2];
507 
508 	/* Duty cycle capture requires at least two capture units */
509 	if (pwm->chip->npwm < 2)
510 		*raw_dty = 0;
511 	else if (priv->capture[0] <= priv->capture[3])
512 		*raw_dty = priv->capture[3] - priv->capture[0];
513 	else
514 		*raw_dty = priv->max_arr - priv->capture[0] + priv->capture[3];
515 
516 	if (*raw_dty > *raw_prd) {
517 		/*
518 		 * Race beetween PWM input and DMA: it may happen
519 		 * falling edge triggers new capture on TI2/4 before DMA
520 		 * had a chance to read CCR2/4. It means capture[1]
521 		 * contains period + duty_cycle. So, subtract period.
522 		 */
523 		*raw_dty -= *raw_prd;
524 	}
525 
526 stop:
527 	regmap_clear_bits(priv->regmap, TIM_CCER, ccen);
528 	regmap_clear_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN);
529 
530 	return ret;
531 }
532 
stm32_pwm_capture(struct pwm_chip * chip,struct pwm_device * pwm,struct pwm_capture * result,unsigned long tmo_ms)533 static int stm32_pwm_capture(struct pwm_chip *chip, struct pwm_device *pwm,
534 			     struct pwm_capture *result, unsigned long tmo_ms)
535 {
536 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
537 	unsigned long long prd, div, dty;
538 	unsigned long rate;
539 	unsigned int psc = 0, icpsc, scale;
540 	u32 raw_prd = 0, raw_dty = 0;
541 	int ret = 0;
542 
543 	mutex_lock(&priv->lock);
544 
545 	if (active_channels(priv)) {
546 		ret = -EBUSY;
547 		goto unlock;
548 	}
549 
550 	ret = clk_enable(priv->clk);
551 	if (ret) {
552 		dev_err(pwmchip_parent(chip), "failed to enable counter clock\n");
553 		goto unlock;
554 	}
555 
556 	rate = clk_get_rate(priv->clk);
557 	if (!rate) {
558 		ret = -EINVAL;
559 		goto clk_dis;
560 	}
561 
562 	/* prescaler: fit timeout window provided by upper layer */
563 	div = (unsigned long long)rate * (unsigned long long)tmo_ms;
564 	do_div(div, MSEC_PER_SEC);
565 	prd = div;
566 	while ((div > priv->max_arr) && (psc < MAX_TIM_PSC)) {
567 		psc++;
568 		div = prd;
569 		do_div(div, psc + 1);
570 	}
571 	regmap_write(priv->regmap, TIM_ARR, priv->max_arr);
572 	regmap_write(priv->regmap, TIM_PSC, psc);
573 
574 	/* Reset input selector to its default input and disable slave mode */
575 	regmap_write(priv->regmap, TIM_TISEL, 0x0);
576 	regmap_write(priv->regmap, TIM_SMCR, 0x0);
577 
578 	/* Map TI1 or TI2 PWM input to IC1 & IC2 (or TI3/4 to IC3 & IC4) */
579 	regmap_update_bits(priv->regmap,
580 			   pwm->hwpwm < 2 ? TIM_CCMR1 : TIM_CCMR2,
581 			   TIM_CCMR_CC1S | TIM_CCMR_CC2S, pwm->hwpwm & 0x1 ?
582 			   TIM_CCMR_CC1S_TI2 | TIM_CCMR_CC2S_TI2 :
583 			   TIM_CCMR_CC1S_TI1 | TIM_CCMR_CC2S_TI1);
584 
585 	/* Capture period on IC1/3 rising edge, duty cycle on IC2/4 falling. */
586 	regmap_update_bits(priv->regmap, TIM_CCER, pwm->hwpwm < 2 ?
587 			   TIM_CCER_CC12P : TIM_CCER_CC34P, pwm->hwpwm < 2 ?
588 			   TIM_CCER_CC2P : TIM_CCER_CC4P);
589 
590 	ret = stm32_pwm_raw_capture(chip, pwm, tmo_ms, &raw_prd, &raw_dty);
591 	if (ret)
592 		goto stop;
593 
594 	/*
595 	 * Got a capture. Try to improve accuracy at high rates:
596 	 * - decrease counter clock prescaler, scale up to max rate.
597 	 * - use input prescaler, capture once every /2 /4 or /8 edges.
598 	 */
599 	if (raw_prd) {
600 		u32 max_arr = priv->max_arr - 0x1000; /* arbitrary margin */
601 
602 		scale = max_arr / min(max_arr, raw_prd);
603 	} else {
604 		scale = priv->max_arr; /* below resolution, use max scale */
605 	}
606 
607 	if (psc && scale > 1) {
608 		/* 2nd measure with new scale */
609 		psc /= scale;
610 		regmap_write(priv->regmap, TIM_PSC, psc);
611 		ret = stm32_pwm_raw_capture(chip, pwm, tmo_ms, &raw_prd,
612 					    &raw_dty);
613 		if (ret)
614 			goto stop;
615 	}
616 
617 	/* Compute intermediate period not to exceed timeout at low rates */
618 	prd = (unsigned long long)raw_prd * (psc + 1) * NSEC_PER_SEC;
619 	do_div(prd, rate);
620 
621 	for (icpsc = 0; icpsc < MAX_TIM_ICPSC ; icpsc++) {
622 		/* input prescaler: also keep arbitrary margin */
623 		if (raw_prd >= (priv->max_arr - 0x1000) >> (icpsc + 1))
624 			break;
625 		if (prd >= (tmo_ms * NSEC_PER_MSEC) >> (icpsc + 2))
626 			break;
627 	}
628 
629 	if (!icpsc)
630 		goto done;
631 
632 	/* Last chance to improve period accuracy, using input prescaler */
633 	regmap_update_bits(priv->regmap,
634 			   pwm->hwpwm < 2 ? TIM_CCMR1 : TIM_CCMR2,
635 			   TIM_CCMR_IC1PSC | TIM_CCMR_IC2PSC,
636 			   FIELD_PREP(TIM_CCMR_IC1PSC, icpsc) |
637 			   FIELD_PREP(TIM_CCMR_IC2PSC, icpsc));
638 
639 	ret = stm32_pwm_raw_capture(chip, pwm, tmo_ms, &raw_prd, &raw_dty);
640 	if (ret)
641 		goto stop;
642 
643 	if (raw_dty >= (raw_prd >> icpsc)) {
644 		/*
645 		 * We may fall here using input prescaler, when input
646 		 * capture starts on high side (before falling edge).
647 		 * Example with icpsc to capture on each 4 events:
648 		 *
649 		 *       start   1st capture                     2nd capture
650 		 *         v     v                               v
651 		 *         ___   _____   _____   _____   _____   ____
652 		 * TI1..4     |__|    |__|    |__|    |__|    |__|
653 		 *            v  v    .  .    .  .    .       v  v
654 		 * icpsc1/3:  .  0    .  1    .  2    .  3    .  0
655 		 * icpsc2/4:  0       1       2       3       0
656 		 *            v  v                            v  v
657 		 * CCR1/3  ......t0..............................t2
658 		 * CCR2/4  ..t1..............................t1'...
659 		 *               .                            .  .
660 		 * Capture0:     .<----------------------------->.
661 		 * Capture1:     .<-------------------------->.  .
662 		 *               .                            .  .
663 		 * Period:       .<------>                    .  .
664 		 * Low side:                                  .<>.
665 		 *
666 		 * Result:
667 		 * - Period = Capture0 / icpsc
668 		 * - Duty = Period - Low side = Period - (Capture0 - Capture1)
669 		 */
670 		raw_dty = (raw_prd >> icpsc) - (raw_prd - raw_dty);
671 	}
672 
673 done:
674 	prd = (unsigned long long)raw_prd * (psc + 1) * NSEC_PER_SEC;
675 	result->period = DIV_ROUND_UP_ULL(prd, rate << icpsc);
676 	dty = (unsigned long long)raw_dty * (psc + 1) * NSEC_PER_SEC;
677 	result->duty_cycle = DIV_ROUND_UP_ULL(dty, rate);
678 stop:
679 	regmap_write(priv->regmap, TIM_CCER, 0);
680 	regmap_write(priv->regmap, pwm->hwpwm < 2 ? TIM_CCMR1 : TIM_CCMR2, 0);
681 	regmap_write(priv->regmap, TIM_PSC, 0);
682 clk_dis:
683 	clk_disable(priv->clk);
684 unlock:
685 	mutex_unlock(&priv->lock);
686 
687 	return ret;
688 }
689 
690 static const struct pwm_ops stm32pwm_ops = {
691 	.sizeof_wfhw = sizeof(struct stm32_pwm_waveform),
692 	.round_waveform_tohw = stm32_pwm_round_waveform_tohw,
693 	.round_waveform_fromhw = stm32_pwm_round_waveform_fromhw,
694 	.read_waveform = stm32_pwm_read_waveform,
695 	.write_waveform = stm32_pwm_write_waveform,
696 
697 	.capture = IS_ENABLED(CONFIG_DMA_ENGINE) ? stm32_pwm_capture : NULL,
698 };
699 
stm32_pwm_set_breakinput(struct stm32_pwm * priv,const struct stm32_breakinput * bi)700 static int stm32_pwm_set_breakinput(struct stm32_pwm *priv,
701 				    const struct stm32_breakinput *bi)
702 {
703 	u32 shift = TIM_BDTR_BKF_SHIFT(bi->index);
704 	u32 bke = TIM_BDTR_BKE(bi->index);
705 	u32 bkp = TIM_BDTR_BKP(bi->index);
706 	u32 bkf = TIM_BDTR_BKF(bi->index);
707 	u32 mask = bkf | bkp | bke;
708 	u32 bdtr;
709 
710 	bdtr = (bi->filter & TIM_BDTR_BKF_MASK) << shift | bke;
711 
712 	if (bi->level)
713 		bdtr |= bkp;
714 
715 	regmap_update_bits(priv->regmap, TIM_BDTR, mask, bdtr);
716 
717 	regmap_read(priv->regmap, TIM_BDTR, &bdtr);
718 
719 	return (bdtr & bke) ? 0 : -EINVAL;
720 }
721 
stm32_pwm_apply_breakinputs(struct stm32_pwm * priv)722 static int stm32_pwm_apply_breakinputs(struct stm32_pwm *priv)
723 {
724 	unsigned int i;
725 	int ret;
726 
727 	for (i = 0; i < priv->num_breakinputs; i++) {
728 		ret = stm32_pwm_set_breakinput(priv, &priv->breakinputs[i]);
729 		if (ret < 0)
730 			return ret;
731 	}
732 
733 	return 0;
734 }
735 
stm32_pwm_probe_breakinputs(struct stm32_pwm * priv,struct device_node * np)736 static int stm32_pwm_probe_breakinputs(struct stm32_pwm *priv,
737 				       struct device_node *np)
738 {
739 	int nb, ret, array_size;
740 	unsigned int i;
741 
742 	nb = of_property_count_elems_of_size(np, "st,breakinput",
743 					     sizeof(struct stm32_breakinput));
744 
745 	/*
746 	 * Because "st,breakinput" parameter is optional do not make probe
747 	 * failed if it doesn't exist.
748 	 */
749 	if (nb <= 0)
750 		return 0;
751 
752 	if (nb > MAX_BREAKINPUT)
753 		return -EINVAL;
754 
755 	priv->num_breakinputs = nb;
756 	array_size = nb * sizeof(struct stm32_breakinput) / sizeof(u32);
757 	ret = of_property_read_u32_array(np, "st,breakinput",
758 					 (u32 *)priv->breakinputs, array_size);
759 	if (ret)
760 		return ret;
761 
762 	for (i = 0; i < priv->num_breakinputs; i++) {
763 		if (priv->breakinputs[i].index > 1 ||
764 		    priv->breakinputs[i].level > 1 ||
765 		    priv->breakinputs[i].filter > 15)
766 			return -EINVAL;
767 	}
768 
769 	return stm32_pwm_apply_breakinputs(priv);
770 }
771 
stm32_pwm_detect_complementary(struct stm32_pwm * priv,struct stm32_timers * ddata)772 static void stm32_pwm_detect_complementary(struct stm32_pwm *priv, struct stm32_timers *ddata)
773 {
774 	u32 ccer;
775 
776 	if (ddata->ipidr) {
777 		u32 val;
778 
779 		/* Simply read from HWCFGR the number of complementary outputs (MP25). */
780 		regmap_read(priv->regmap, TIM_HWCFGR1, &val);
781 		priv->have_complementary_output = !!FIELD_GET(TIM_HWCFGR1_NB_OF_DT, val);
782 		return;
783 	}
784 
785 	/*
786 	 * If complementary bit doesn't exist writing 1 will have no
787 	 * effect so we can detect it.
788 	 */
789 	regmap_set_bits(priv->regmap, TIM_CCER, TIM_CCER_CC1NE);
790 	regmap_read(priv->regmap, TIM_CCER, &ccer);
791 	regmap_clear_bits(priv->regmap, TIM_CCER, TIM_CCER_CC1NE);
792 
793 	priv->have_complementary_output = (ccer != 0);
794 }
795 
stm32_pwm_detect_channels(struct stm32_timers * ddata,unsigned int * num_enabled)796 static unsigned int stm32_pwm_detect_channels(struct stm32_timers *ddata,
797 					      unsigned int *num_enabled)
798 {
799 	struct regmap *regmap = ddata->regmap;
800 	u32 ccer, ccer_backup;
801 
802 	regmap_read(regmap, TIM_CCER, &ccer_backup);
803 	*num_enabled = hweight32(ccer_backup & TIM_CCER_CCXE);
804 
805 	if (ddata->ipidr) {
806 		u32 hwcfgr;
807 		unsigned int npwm;
808 
809 		/* Deduce from HWCFGR the number of outputs (MP25). */
810 		regmap_read(regmap, TIM_HWCFGR1, &hwcfgr);
811 
812 		/*
813 		 * Timers may have more capture/compare channels than the
814 		 * actual number of PWM channel outputs (e.g. TIM_CH[1..4]).
815 		 */
816 		npwm = FIELD_GET(TIM_HWCFGR1_NB_OF_CC, hwcfgr);
817 
818 		return npwm < STM32_MAX_PWM_OUTPUT ? npwm : STM32_MAX_PWM_OUTPUT;
819 	}
820 
821 	/*
822 	 * If channels enable bits don't exist writing 1 will have no
823 	 * effect so we can detect and count them.
824 	 */
825 	regmap_set_bits(regmap, TIM_CCER, TIM_CCER_CCXE);
826 	regmap_read(regmap, TIM_CCER, &ccer);
827 	regmap_write(regmap, TIM_CCER, ccer_backup);
828 
829 	return hweight32(ccer & TIM_CCER_CCXE);
830 }
831 
stm32_pwm_probe(struct platform_device * pdev)832 static int stm32_pwm_probe(struct platform_device *pdev)
833 {
834 	struct device *dev = &pdev->dev;
835 	struct device_node *np = dev->of_node;
836 	struct stm32_timers *ddata = dev_get_drvdata(pdev->dev.parent);
837 	struct pwm_chip *chip;
838 	struct stm32_pwm *priv;
839 	unsigned int npwm, num_enabled;
840 	unsigned int i;
841 	int ret;
842 
843 	npwm = stm32_pwm_detect_channels(ddata, &num_enabled);
844 
845 	chip = devm_pwmchip_alloc(dev, npwm, sizeof(*priv));
846 	if (IS_ERR(chip))
847 		return PTR_ERR(chip);
848 	priv = to_stm32_pwm_dev(chip);
849 
850 	mutex_init(&priv->lock);
851 	priv->regmap = ddata->regmap;
852 	priv->clk = ddata->clk;
853 	priv->max_arr = ddata->max_arr;
854 
855 	if (!priv->regmap || !priv->clk)
856 		return dev_err_probe(dev, -EINVAL, "Failed to get %s\n",
857 				     priv->regmap ? "clk" : "regmap");
858 
859 	ret = stm32_pwm_probe_breakinputs(priv, np);
860 	if (ret)
861 		return dev_err_probe(dev, ret,
862 				     "Failed to configure breakinputs\n");
863 
864 	stm32_pwm_detect_complementary(priv, ddata);
865 
866 	ret = devm_clk_rate_exclusive_get(dev, priv->clk);
867 	if (ret)
868 		return dev_err_probe(dev, ret, "Failed to lock clock\n");
869 
870 	/*
871 	 * With the clk running with not more than 1 GHz the calculations in
872 	 * .apply() won't overflow.
873 	 */
874 	if (clk_get_rate(priv->clk) > 1000000000)
875 		return dev_err_probe(dev, -EINVAL, "Clock freq too high (%lu)\n",
876 				     clk_get_rate(priv->clk));
877 
878 	chip->ops = &stm32pwm_ops;
879 
880 	/* Initialize clock refcount to number of enabled PWM channels. */
881 	for (i = 0; i < num_enabled; i++) {
882 		ret = clk_enable(priv->clk);
883 		if (ret)
884 			return ret;
885 	}
886 
887 	ret = devm_pwmchip_add(dev, chip);
888 	if (ret < 0)
889 		return dev_err_probe(dev, ret,
890 				     "Failed to register pwmchip\n");
891 
892 	platform_set_drvdata(pdev, chip);
893 
894 	return 0;
895 }
896 
stm32_pwm_suspend(struct device * dev)897 static int stm32_pwm_suspend(struct device *dev)
898 {
899 	struct pwm_chip *chip = dev_get_drvdata(dev);
900 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
901 	unsigned int i;
902 	u32 ccer, mask;
903 
904 	/* Look for active channels */
905 	ccer = active_channels(priv);
906 
907 	for (i = 0; i < chip->npwm; i++) {
908 		mask = TIM_CCER_CCxE(i + 1);
909 		if (ccer & mask) {
910 			dev_err(dev, "PWM %u still in use by consumer %s\n",
911 				i, chip->pwms[i].label);
912 			return -EBUSY;
913 		}
914 	}
915 
916 	return pinctrl_pm_select_sleep_state(dev);
917 }
918 
stm32_pwm_resume(struct device * dev)919 static int stm32_pwm_resume(struct device *dev)
920 {
921 	struct pwm_chip *chip = dev_get_drvdata(dev);
922 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
923 	int ret;
924 
925 	ret = pinctrl_pm_select_default_state(dev);
926 	if (ret)
927 		return ret;
928 
929 	/* restore breakinput registers that may have been lost in low power */
930 	return stm32_pwm_apply_breakinputs(priv);
931 }
932 
933 static DEFINE_SIMPLE_DEV_PM_OPS(stm32_pwm_pm_ops, stm32_pwm_suspend, stm32_pwm_resume);
934 
935 static const struct of_device_id stm32_pwm_of_match[] = {
936 	{ .compatible = "st,stm32-pwm",	},
937 	{ .compatible = "st,stm32mp25-pwm", },
938 	{ /* end node */ },
939 };
940 MODULE_DEVICE_TABLE(of, stm32_pwm_of_match);
941 
942 static struct platform_driver stm32_pwm_driver = {
943 	.probe	= stm32_pwm_probe,
944 	.driver	= {
945 		.name = "stm32-pwm",
946 		.of_match_table = stm32_pwm_of_match,
947 		.pm = pm_ptr(&stm32_pwm_pm_ops),
948 	},
949 };
950 module_platform_driver(stm32_pwm_driver);
951 
952 MODULE_ALIAS("platform:stm32-pwm");
953 MODULE_DESCRIPTION("STMicroelectronics STM32 PWM driver");
954 MODULE_LICENSE("GPL v2");
955