xref: /linux/drivers/pwm/pwm-stm32.c (revision ecd5d67ad602c2c12e8709762717112ef0958767)
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 
23 struct stm32_breakinput {
24 	u32 index;
25 	u32 level;
26 	u32 filter;
27 };
28 
29 struct stm32_pwm {
30 	struct mutex lock; /* protect pwm config/enable */
31 	struct clk *clk;
32 	struct regmap *regmap;
33 	u32 max_arr;
34 	bool have_complementary_output;
35 	struct stm32_breakinput breakinputs[MAX_BREAKINPUT];
36 	unsigned int num_breakinputs;
37 	u32 capture[4] ____cacheline_aligned; /* DMA'able buffer */
38 };
39 
to_stm32_pwm_dev(struct pwm_chip * chip)40 static inline struct stm32_pwm *to_stm32_pwm_dev(struct pwm_chip *chip)
41 {
42 	return pwmchip_get_drvdata(chip);
43 }
44 
active_channels(struct stm32_pwm * dev)45 static u32 active_channels(struct stm32_pwm *dev)
46 {
47 	u32 ccer;
48 
49 	regmap_read(dev->regmap, TIM_CCER, &ccer);
50 
51 	return ccer & TIM_CCER_CCXE;
52 }
53 
54 struct stm32_pwm_waveform {
55 	u32 ccer;
56 	u32 psc;
57 	u32 arr;
58 	u32 ccr;
59 };
60 
stm32_pwm_round_waveform_tohw(struct pwm_chip * chip,struct pwm_device * pwm,const struct pwm_waveform * wf,void * _wfhw)61 static int stm32_pwm_round_waveform_tohw(struct pwm_chip *chip,
62 					 struct pwm_device *pwm,
63 					 const struct pwm_waveform *wf,
64 					 void *_wfhw)
65 {
66 	struct stm32_pwm_waveform *wfhw = _wfhw;
67 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
68 	unsigned int ch = pwm->hwpwm;
69 	unsigned long rate;
70 	u64 ccr, duty;
71 	int ret;
72 
73 	if (wf->period_length_ns == 0) {
74 		*wfhw = (struct stm32_pwm_waveform){
75 			.ccer = 0,
76 		};
77 
78 		return 0;
79 	}
80 
81 	ret = clk_enable(priv->clk);
82 	if (ret)
83 		return ret;
84 
85 	wfhw->ccer = TIM_CCER_CCxE(ch + 1);
86 	if (priv->have_complementary_output)
87 		wfhw->ccer |= TIM_CCER_CCxNE(ch + 1);
88 
89 	rate = clk_get_rate(priv->clk);
90 
91 	if (active_channels(priv) & ~(1 << ch * 4)) {
92 		u64 arr;
93 
94 		/*
95 		 * Other channels are already enabled, so the configured PSC and
96 		 * ARR must be used for this channel, too.
97 		 */
98 		ret = regmap_read(priv->regmap, TIM_PSC, &wfhw->psc);
99 		if (ret)
100 			goto out;
101 
102 		ret = regmap_read(priv->regmap, TIM_ARR, &wfhw->arr);
103 		if (ret)
104 			goto out;
105 
106 		arr = mul_u64_u64_div_u64(wf->period_length_ns, rate,
107 					  (u64)NSEC_PER_SEC * (wfhw->psc + 1));
108 		if (arr <= wfhw->arr) {
109 			/*
110 			 * requested period is smaller than the currently
111 			 * configured and unchangable period, report back the smallest
112 			 * possible period, i.e. the current state and return 1
113 			 * to indicate the wrong rounding direction.
114 			 */
115 			ret = 1;
116 		}
117 
118 	} else {
119 		/*
120 		 * .probe() asserted that clk_get_rate() is not bigger than 1 GHz, so
121 		 * the calculations here won't overflow.
122 		 * First we need to find the minimal value for prescaler such that
123 		 *
124 		 *        period_ns * clkrate
125 		 *   ------------------------------ < max_arr + 1
126 		 *   NSEC_PER_SEC * (prescaler + 1)
127 		 *
128 		 * This equation is equivalent to
129 		 *
130 		 *        period_ns * clkrate
131 		 *   ---------------------------- < prescaler + 1
132 		 *   NSEC_PER_SEC * (max_arr + 1)
133 		 *
134 		 * Using integer division and knowing that the right hand side is
135 		 * integer, this is further equivalent to
136 		 *
137 		 *   (period_ns * clkrate) // (NSEC_PER_SEC * (max_arr + 1)) ≤ prescaler
138 		 */
139 		u64 psc = mul_u64_u64_div_u64(wf->period_length_ns, rate,
140 					      (u64)NSEC_PER_SEC * ((u64)priv->max_arr + 1));
141 		u64 arr;
142 
143 		wfhw->psc = min_t(u64, psc, MAX_TIM_PSC);
144 
145 		arr = mul_u64_u64_div_u64(wf->period_length_ns, rate,
146 					  (u64)NSEC_PER_SEC * (wfhw->psc + 1));
147 		if (!arr) {
148 			/*
149 			 * requested period is too small, report back the smallest
150 			 * possible period, i.e. ARR = 0. The only valid CCR
151 			 * value is then zero, too.
152 			 */
153 			wfhw->arr = 0;
154 			wfhw->ccr = 0;
155 			ret = 1;
156 			goto out;
157 		}
158 
159 		/*
160 		 * ARR is limited intentionally to values less than
161 		 * priv->max_arr to allow 100% duty cycle.
162 		 */
163 		wfhw->arr = min_t(u64, arr, priv->max_arr) - 1;
164 	}
165 
166 	duty = mul_u64_u64_div_u64(wf->duty_length_ns, rate,
167 				   (u64)NSEC_PER_SEC * (wfhw->psc + 1));
168 	duty = min_t(u64, duty, wfhw->arr + 1);
169 
170 	if (wf->duty_length_ns && wf->duty_offset_ns &&
171 	    wf->duty_length_ns + wf->duty_offset_ns >= wf->period_length_ns) {
172 		wfhw->ccer |= TIM_CCER_CCxP(ch + 1);
173 		if (priv->have_complementary_output)
174 			wfhw->ccer |= TIM_CCER_CCxNP(ch + 1);
175 
176 		ccr = wfhw->arr + 1 - duty;
177 	} else {
178 		ccr = duty;
179 	}
180 
181 	wfhw->ccr = min_t(u64, ccr, wfhw->arr + 1);
182 
183 	dev_dbg(&chip->dev, "pwm#%u: %lld/%lld [+%lld] @%lu -> CCER: %08x, PSC: %08x, ARR: %08x, CCR: %08x\n",
184 		pwm->hwpwm, wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns,
185 		rate, wfhw->ccer, wfhw->psc, wfhw->arr, wfhw->ccr);
186 
187 out:
188 	clk_disable(priv->clk);
189 
190 	return ret;
191 }
192 
193 /*
194  * This should be moved to lib/math/div64.c. Currently there are some changes
195  * pending to mul_u64_u64_div_u64. Uwe will care for that when the dust settles.
196  */
stm32_pwm_mul_u64_u64_div_u64_roundup(u64 a,u64 b,u64 c)197 static u64 stm32_pwm_mul_u64_u64_div_u64_roundup(u64 a, u64 b, u64 c)
198 {
199 	u64 res = mul_u64_u64_div_u64(a, b, c);
200 	/* Those multiplications might overflow but it doesn't matter */
201 	u64 rem = a * b - c * res;
202 
203 	if (rem)
204 		res += 1;
205 
206 	return res;
207 }
208 
stm32_pwm_round_waveform_fromhw(struct pwm_chip * chip,struct pwm_device * pwm,const void * _wfhw,struct pwm_waveform * wf)209 static int stm32_pwm_round_waveform_fromhw(struct pwm_chip *chip,
210 					   struct pwm_device *pwm,
211 					   const void *_wfhw,
212 					   struct pwm_waveform *wf)
213 {
214 	const struct stm32_pwm_waveform *wfhw = _wfhw;
215 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
216 	unsigned int ch = pwm->hwpwm;
217 
218 	if (wfhw->ccer & TIM_CCER_CCxE(ch + 1)) {
219 		unsigned long rate = clk_get_rate(priv->clk);
220 		u64 ccr_ns;
221 
222 		/* The result doesn't overflow for rate >= 15259 */
223 		wf->period_length_ns = stm32_pwm_mul_u64_u64_div_u64_roundup(((u64)wfhw->psc + 1) * (wfhw->arr + 1),
224 									     NSEC_PER_SEC, rate);
225 
226 		ccr_ns = stm32_pwm_mul_u64_u64_div_u64_roundup(((u64)wfhw->psc + 1) * wfhw->ccr,
227 							       NSEC_PER_SEC, rate);
228 
229 		if (wfhw->ccer & TIM_CCER_CCxP(ch + 1)) {
230 			wf->duty_length_ns =
231 				stm32_pwm_mul_u64_u64_div_u64_roundup(((u64)wfhw->psc + 1) * (wfhw->arr + 1 - wfhw->ccr),
232 								      NSEC_PER_SEC, rate);
233 
234 			wf->duty_offset_ns = ccr_ns;
235 		} else {
236 			wf->duty_length_ns = ccr_ns;
237 			wf->duty_offset_ns = 0;
238 		}
239 
240 		dev_dbg(&chip->dev, "pwm#%u: CCER: %08x, PSC: %08x, ARR: %08x, CCR: %08x @%lu -> %lld/%lld [+%lld]\n",
241 			pwm->hwpwm, wfhw->ccer, wfhw->psc, wfhw->arr, wfhw->ccr, rate,
242 			wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns);
243 
244 	} else {
245 		*wf = (struct pwm_waveform){
246 			.period_length_ns = 0,
247 		};
248 	}
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)772 static void stm32_pwm_detect_complementary(struct stm32_pwm *priv)
773 {
774 	u32 ccer;
775 
776 	/*
777 	 * If complementary bit doesn't exist writing 1 will have no
778 	 * effect so we can detect it.
779 	 */
780 	regmap_set_bits(priv->regmap, TIM_CCER, TIM_CCER_CC1NE);
781 	regmap_read(priv->regmap, TIM_CCER, &ccer);
782 	regmap_clear_bits(priv->regmap, TIM_CCER, TIM_CCER_CC1NE);
783 
784 	priv->have_complementary_output = (ccer != 0);
785 }
786 
stm32_pwm_detect_channels(struct regmap * regmap,unsigned int * num_enabled)787 static unsigned int stm32_pwm_detect_channels(struct regmap *regmap,
788 					      unsigned int *num_enabled)
789 {
790 	u32 ccer, ccer_backup;
791 
792 	/*
793 	 * If channels enable bits don't exist writing 1 will have no
794 	 * effect so we can detect and count them.
795 	 */
796 	regmap_read(regmap, TIM_CCER, &ccer_backup);
797 	regmap_set_bits(regmap, TIM_CCER, TIM_CCER_CCXE);
798 	regmap_read(regmap, TIM_CCER, &ccer);
799 	regmap_write(regmap, TIM_CCER, ccer_backup);
800 
801 	*num_enabled = hweight32(ccer_backup & TIM_CCER_CCXE);
802 
803 	return hweight32(ccer & TIM_CCER_CCXE);
804 }
805 
stm32_pwm_probe(struct platform_device * pdev)806 static int stm32_pwm_probe(struct platform_device *pdev)
807 {
808 	struct device *dev = &pdev->dev;
809 	struct device_node *np = dev->of_node;
810 	struct stm32_timers *ddata = dev_get_drvdata(pdev->dev.parent);
811 	struct pwm_chip *chip;
812 	struct stm32_pwm *priv;
813 	unsigned int npwm, num_enabled;
814 	unsigned int i;
815 	int ret;
816 
817 	npwm = stm32_pwm_detect_channels(ddata->regmap, &num_enabled);
818 
819 	chip = devm_pwmchip_alloc(dev, npwm, sizeof(*priv));
820 	if (IS_ERR(chip))
821 		return PTR_ERR(chip);
822 	priv = to_stm32_pwm_dev(chip);
823 
824 	mutex_init(&priv->lock);
825 	priv->regmap = ddata->regmap;
826 	priv->clk = ddata->clk;
827 	priv->max_arr = ddata->max_arr;
828 
829 	if (!priv->regmap || !priv->clk)
830 		return dev_err_probe(dev, -EINVAL, "Failed to get %s\n",
831 				     priv->regmap ? "clk" : "regmap");
832 
833 	ret = stm32_pwm_probe_breakinputs(priv, np);
834 	if (ret)
835 		return dev_err_probe(dev, ret,
836 				     "Failed to configure breakinputs\n");
837 
838 	stm32_pwm_detect_complementary(priv);
839 
840 	ret = devm_clk_rate_exclusive_get(dev, priv->clk);
841 	if (ret)
842 		return dev_err_probe(dev, ret, "Failed to lock clock\n");
843 
844 	/*
845 	 * With the clk running with not more than 1 GHz the calculations in
846 	 * .apply() won't overflow.
847 	 */
848 	if (clk_get_rate(priv->clk) > 1000000000)
849 		return dev_err_probe(dev, -EINVAL, "Clock freq too high (%lu)\n",
850 				     clk_get_rate(priv->clk));
851 
852 	chip->ops = &stm32pwm_ops;
853 
854 	/* Initialize clock refcount to number of enabled PWM channels. */
855 	for (i = 0; i < num_enabled; i++) {
856 		ret = clk_enable(priv->clk);
857 		if (ret)
858 			return ret;
859 	}
860 
861 	ret = devm_pwmchip_add(dev, chip);
862 	if (ret < 0)
863 		return dev_err_probe(dev, ret,
864 				     "Failed to register pwmchip\n");
865 
866 	platform_set_drvdata(pdev, chip);
867 
868 	return 0;
869 }
870 
stm32_pwm_suspend(struct device * dev)871 static int stm32_pwm_suspend(struct device *dev)
872 {
873 	struct pwm_chip *chip = dev_get_drvdata(dev);
874 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
875 	unsigned int i;
876 	u32 ccer, mask;
877 
878 	/* Look for active channels */
879 	ccer = active_channels(priv);
880 
881 	for (i = 0; i < chip->npwm; i++) {
882 		mask = TIM_CCER_CCxE(i + 1);
883 		if (ccer & mask) {
884 			dev_err(dev, "PWM %u still in use by consumer %s\n",
885 				i, chip->pwms[i].label);
886 			return -EBUSY;
887 		}
888 	}
889 
890 	return pinctrl_pm_select_sleep_state(dev);
891 }
892 
stm32_pwm_resume(struct device * dev)893 static int stm32_pwm_resume(struct device *dev)
894 {
895 	struct pwm_chip *chip = dev_get_drvdata(dev);
896 	struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
897 	int ret;
898 
899 	ret = pinctrl_pm_select_default_state(dev);
900 	if (ret)
901 		return ret;
902 
903 	/* restore breakinput registers that may have been lost in low power */
904 	return stm32_pwm_apply_breakinputs(priv);
905 }
906 
907 static DEFINE_SIMPLE_DEV_PM_OPS(stm32_pwm_pm_ops, stm32_pwm_suspend, stm32_pwm_resume);
908 
909 static const struct of_device_id stm32_pwm_of_match[] = {
910 	{ .compatible = "st,stm32-pwm",	},
911 	{ /* end node */ },
912 };
913 MODULE_DEVICE_TABLE(of, stm32_pwm_of_match);
914 
915 static struct platform_driver stm32_pwm_driver = {
916 	.probe	= stm32_pwm_probe,
917 	.driver	= {
918 		.name = "stm32-pwm",
919 		.of_match_table = stm32_pwm_of_match,
920 		.pm = pm_ptr(&stm32_pwm_pm_ops),
921 	},
922 };
923 module_platform_driver(stm32_pwm_driver);
924 
925 MODULE_ALIAS("platform:stm32-pwm");
926 MODULE_DESCRIPTION("STMicroelectronics STM32 PWM driver");
927 MODULE_LICENSE("GPL v2");
928