]> Git Repo - linux.git/blob - drivers/pwm/pwm-stm32.c
pwm: stm32: Improve capture by tuning counter prescaler
[linux.git] / drivers / pwm / pwm-stm32.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STMicroelectronics 2016
4  *
5  * Author: Gerald Baeza <[email protected]>
6  *
7  * Inspired by timer-stm32.c from Maxime Coquelin
8  *             pwm-atmel.c from Bo Shen
9  */
10
11 #include <linux/mfd/stm32-timers.h>
12 #include <linux/module.h>
13 #include <linux/of.h>
14 #include <linux/platform_device.h>
15 #include <linux/pwm.h>
16
17 #define CCMR_CHANNEL_SHIFT 8
18 #define CCMR_CHANNEL_MASK  0xFF
19 #define MAX_BREAKINPUT 2
20
21 struct stm32_pwm {
22         struct pwm_chip chip;
23         struct mutex lock; /* protect pwm config/enable */
24         struct clk *clk;
25         struct regmap *regmap;
26         u32 max_arr;
27         bool have_complementary_output;
28         u32 capture[4] ____cacheline_aligned; /* DMA'able buffer */
29 };
30
31 struct stm32_breakinput {
32         u32 index;
33         u32 level;
34         u32 filter;
35 };
36
37 static inline struct stm32_pwm *to_stm32_pwm_dev(struct pwm_chip *chip)
38 {
39         return container_of(chip, struct stm32_pwm, chip);
40 }
41
42 static u32 active_channels(struct stm32_pwm *dev)
43 {
44         u32 ccer;
45
46         regmap_read(dev->regmap, TIM_CCER, &ccer);
47
48         return ccer & TIM_CCER_CCXE;
49 }
50
51 static int write_ccrx(struct stm32_pwm *dev, int ch, u32 value)
52 {
53         switch (ch) {
54         case 0:
55                 return regmap_write(dev->regmap, TIM_CCR1, value);
56         case 1:
57                 return regmap_write(dev->regmap, TIM_CCR2, value);
58         case 2:
59                 return regmap_write(dev->regmap, TIM_CCR3, value);
60         case 3:
61                 return regmap_write(dev->regmap, TIM_CCR4, value);
62         }
63         return -EINVAL;
64 }
65
66 #define TIM_CCER_CC12P (TIM_CCER_CC1P | TIM_CCER_CC2P)
67 #define TIM_CCER_CC12E (TIM_CCER_CC1E | TIM_CCER_CC2E)
68 #define TIM_CCER_CC34P (TIM_CCER_CC3P | TIM_CCER_CC4P)
69 #define TIM_CCER_CC34E (TIM_CCER_CC3E | TIM_CCER_CC4E)
70
71 /*
72  * Capture using PWM input mode:
73  *                              ___          ___
74  * TI[1, 2, 3 or 4]: ........._|   |________|
75  *                             ^0  ^1       ^2
76  *                              .   .        .
77  *                              .   .        XXXXX
78  *                              .   .   XXXXX     |
79  *                              .  XXXXX     .    |
80  *                            XXXXX .        .    |
81  * COUNTER:        ______XXXXX  .   .        .    |_XXX
82  *                 start^       .   .        .        ^stop
83  *                      .       .   .        .
84  *                      v       v   .        v
85  *                                  v
86  * CCR1/CCR3:       tx..........t0...........t2
87  * CCR2/CCR4:       tx..............t1.........
88  *
89  * DMA burst transfer:          |            |
90  *                              v            v
91  * DMA buffer:                  { t0, tx }   { t2, t1 }
92  * DMA done:                                 ^
93  *
94  * 0: IC1/3 snapchot on rising edge: counter value -> CCR1/CCR3
95  *    + DMA transfer CCR[1/3] & CCR[2/4] values (t0, tx: doesn't care)
96  * 1: IC2/4 snapchot on falling edge: counter value -> CCR2/CCR4
97  * 2: IC1/3 snapchot on rising edge: counter value -> CCR1/CCR3
98  *    + DMA transfer CCR[1/3] & CCR[2/4] values (t2, t1)
99  *
100  * DMA done, compute:
101  * - Period     = t2 - t0
102  * - Duty cycle = t1 - t0
103  */
104 static int stm32_pwm_raw_capture(struct stm32_pwm *priv, struct pwm_device *pwm,
105                                  unsigned long tmo_ms, u32 *raw_prd,
106                                  u32 *raw_dty)
107 {
108         struct device *parent = priv->chip.dev->parent;
109         enum stm32_timers_dmas dma_id;
110         u32 ccen, ccr;
111         int ret;
112
113         /* Ensure registers have been updated, enable counter and capture */
114         regmap_update_bits(priv->regmap, TIM_EGR, TIM_EGR_UG, TIM_EGR_UG);
115         regmap_update_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN, TIM_CR1_CEN);
116
117         /* Use cc1 or cc3 DMA resp for PWM input channels 1 & 2 or 3 & 4 */
118         dma_id = pwm->hwpwm < 2 ? STM32_TIMERS_DMA_CH1 : STM32_TIMERS_DMA_CH3;
119         ccen = pwm->hwpwm < 2 ? TIM_CCER_CC12E : TIM_CCER_CC34E;
120         ccr = pwm->hwpwm < 2 ? TIM_CCR1 : TIM_CCR3;
121         regmap_update_bits(priv->regmap, TIM_CCER, ccen, ccen);
122
123         /*
124          * Timer DMA burst mode. Request 2 registers, 2 bursts, to get both
125          * CCR1 & CCR2 (or CCR3 & CCR4) on each capture event.
126          * We'll get two capture snapchots: { CCR1, CCR2 }, { CCR1, CCR2 }
127          * or { CCR3, CCR4 }, { CCR3, CCR4 }
128          */
129         ret = stm32_timers_dma_burst_read(parent, priv->capture, dma_id, ccr, 2,
130                                           2, tmo_ms);
131         if (ret)
132                 goto stop;
133
134         /* Period: t2 - t0 (take care of counter overflow) */
135         if (priv->capture[0] <= priv->capture[2])
136                 *raw_prd = priv->capture[2] - priv->capture[0];
137         else
138                 *raw_prd = priv->max_arr - priv->capture[0] + priv->capture[2];
139
140         /* Duty cycle capture requires at least two capture units */
141         if (pwm->chip->npwm < 2)
142                 *raw_dty = 0;
143         else if (priv->capture[0] <= priv->capture[3])
144                 *raw_dty = priv->capture[3] - priv->capture[0];
145         else
146                 *raw_dty = priv->max_arr - priv->capture[0] + priv->capture[3];
147
148         if (*raw_dty > *raw_prd) {
149                 /*
150                  * Race beetween PWM input and DMA: it may happen
151                  * falling edge triggers new capture on TI2/4 before DMA
152                  * had a chance to read CCR2/4. It means capture[1]
153                  * contains period + duty_cycle. So, subtract period.
154                  */
155                 *raw_dty -= *raw_prd;
156         }
157
158 stop:
159         regmap_update_bits(priv->regmap, TIM_CCER, ccen, 0);
160         regmap_update_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN, 0);
161
162         return ret;
163 }
164
165 static int stm32_pwm_capture(struct pwm_chip *chip, struct pwm_device *pwm,
166                              struct pwm_capture *result, unsigned long tmo_ms)
167 {
168         struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
169         unsigned long long prd, div, dty;
170         unsigned long rate;
171         unsigned int psc = 0, scale;
172         u32 raw_prd, raw_dty;
173         int ret = 0;
174
175         mutex_lock(&priv->lock);
176
177         if (active_channels(priv)) {
178                 ret = -EBUSY;
179                 goto unlock;
180         }
181
182         ret = clk_enable(priv->clk);
183         if (ret) {
184                 dev_err(priv->chip.dev, "failed to enable counter clock\n");
185                 goto unlock;
186         }
187
188         rate = clk_get_rate(priv->clk);
189         if (!rate) {
190                 ret = -EINVAL;
191                 goto clk_dis;
192         }
193
194         /* prescaler: fit timeout window provided by upper layer */
195         div = (unsigned long long)rate * (unsigned long long)tmo_ms;
196         do_div(div, MSEC_PER_SEC);
197         prd = div;
198         while ((div > priv->max_arr) && (psc < MAX_TIM_PSC)) {
199                 psc++;
200                 div = prd;
201                 do_div(div, psc + 1);
202         }
203         regmap_write(priv->regmap, TIM_ARR, priv->max_arr);
204         regmap_write(priv->regmap, TIM_PSC, psc);
205
206         /* Map TI1 or TI2 PWM input to IC1 & IC2 (or TI3/4 to IC3 & IC4) */
207         regmap_update_bits(priv->regmap,
208                            pwm->hwpwm < 2 ? TIM_CCMR1 : TIM_CCMR2,
209                            TIM_CCMR_CC1S | TIM_CCMR_CC2S, pwm->hwpwm & 0x1 ?
210                            TIM_CCMR_CC1S_TI2 | TIM_CCMR_CC2S_TI2 :
211                            TIM_CCMR_CC1S_TI1 | TIM_CCMR_CC2S_TI1);
212
213         /* Capture period on IC1/3 rising edge, duty cycle on IC2/4 falling. */
214         regmap_update_bits(priv->regmap, TIM_CCER, pwm->hwpwm < 2 ?
215                            TIM_CCER_CC12P : TIM_CCER_CC34P, pwm->hwpwm < 2 ?
216                            TIM_CCER_CC2P : TIM_CCER_CC4P);
217
218         ret = stm32_pwm_raw_capture(priv, pwm, tmo_ms, &raw_prd, &raw_dty);
219         if (ret)
220                 goto stop;
221
222         /*
223          * Got a capture. Try to improve accuracy at high rates:
224          * - decrease counter clock prescaler, scale up to max rate.
225          */
226         if (raw_prd) {
227                 u32 max_arr = priv->max_arr - 0x1000; /* arbitrary margin */
228
229                 scale = max_arr / min(max_arr, raw_prd);
230         } else {
231                 scale = priv->max_arr; /* bellow resolution, use max scale */
232         }
233
234         if (psc && scale > 1) {
235                 /* 2nd measure with new scale */
236                 psc /= scale;
237                 regmap_write(priv->regmap, TIM_PSC, psc);
238                 ret = stm32_pwm_raw_capture(priv, pwm, tmo_ms, &raw_prd,
239                                             &raw_dty);
240                 if (ret)
241                         goto stop;
242         }
243
244         prd = (unsigned long long)raw_prd * (psc + 1) * NSEC_PER_SEC;
245         result->period = DIV_ROUND_UP_ULL(prd, rate);
246         dty = (unsigned long long)raw_dty * (psc + 1) * NSEC_PER_SEC;
247         result->duty_cycle = DIV_ROUND_UP_ULL(dty, rate);
248 stop:
249         regmap_write(priv->regmap, TIM_CCER, 0);
250         regmap_write(priv->regmap, pwm->hwpwm < 2 ? TIM_CCMR1 : TIM_CCMR2, 0);
251         regmap_write(priv->regmap, TIM_PSC, 0);
252 clk_dis:
253         clk_disable(priv->clk);
254 unlock:
255         mutex_unlock(&priv->lock);
256
257         return ret;
258 }
259
260 static int stm32_pwm_config(struct stm32_pwm *priv, int ch,
261                             int duty_ns, int period_ns)
262 {
263         unsigned long long prd, div, dty;
264         unsigned int prescaler = 0;
265         u32 ccmr, mask, shift;
266
267         /* Period and prescaler values depends on clock rate */
268         div = (unsigned long long)clk_get_rate(priv->clk) * period_ns;
269
270         do_div(div, NSEC_PER_SEC);
271         prd = div;
272
273         while (div > priv->max_arr) {
274                 prescaler++;
275                 div = prd;
276                 do_div(div, prescaler + 1);
277         }
278
279         prd = div;
280
281         if (prescaler > MAX_TIM_PSC)
282                 return -EINVAL;
283
284         /*
285          * All channels share the same prescaler and counter so when two
286          * channels are active at the same time we can't change them
287          */
288         if (active_channels(priv) & ~(1 << ch * 4)) {
289                 u32 psc, arr;
290
291                 regmap_read(priv->regmap, TIM_PSC, &psc);
292                 regmap_read(priv->regmap, TIM_ARR, &arr);
293
294                 if ((psc != prescaler) || (arr != prd - 1))
295                         return -EBUSY;
296         }
297
298         regmap_write(priv->regmap, TIM_PSC, prescaler);
299         regmap_write(priv->regmap, TIM_ARR, prd - 1);
300         regmap_update_bits(priv->regmap, TIM_CR1, TIM_CR1_ARPE, TIM_CR1_ARPE);
301
302         /* Calculate the duty cycles */
303         dty = prd * duty_ns;
304         do_div(dty, period_ns);
305
306         write_ccrx(priv, ch, dty);
307
308         /* Configure output mode */
309         shift = (ch & 0x1) * CCMR_CHANNEL_SHIFT;
310         ccmr = (TIM_CCMR_PE | TIM_CCMR_M1) << shift;
311         mask = CCMR_CHANNEL_MASK << shift;
312
313         if (ch < 2)
314                 regmap_update_bits(priv->regmap, TIM_CCMR1, mask, ccmr);
315         else
316                 regmap_update_bits(priv->regmap, TIM_CCMR2, mask, ccmr);
317
318         regmap_update_bits(priv->regmap, TIM_BDTR,
319                            TIM_BDTR_MOE | TIM_BDTR_AOE,
320                            TIM_BDTR_MOE | TIM_BDTR_AOE);
321
322         return 0;
323 }
324
325 static int stm32_pwm_set_polarity(struct stm32_pwm *priv, int ch,
326                                   enum pwm_polarity polarity)
327 {
328         u32 mask;
329
330         mask = TIM_CCER_CC1P << (ch * 4);
331         if (priv->have_complementary_output)
332                 mask |= TIM_CCER_CC1NP << (ch * 4);
333
334         regmap_update_bits(priv->regmap, TIM_CCER, mask,
335                            polarity == PWM_POLARITY_NORMAL ? 0 : mask);
336
337         return 0;
338 }
339
340 static int stm32_pwm_enable(struct stm32_pwm *priv, int ch)
341 {
342         u32 mask;
343         int ret;
344
345         ret = clk_enable(priv->clk);
346         if (ret)
347                 return ret;
348
349         /* Enable channel */
350         mask = TIM_CCER_CC1E << (ch * 4);
351         if (priv->have_complementary_output)
352                 mask |= TIM_CCER_CC1NE << (ch * 4);
353
354         regmap_update_bits(priv->regmap, TIM_CCER, mask, mask);
355
356         /* Make sure that registers are updated */
357         regmap_update_bits(priv->regmap, TIM_EGR, TIM_EGR_UG, TIM_EGR_UG);
358
359         /* Enable controller */
360         regmap_update_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN, TIM_CR1_CEN);
361
362         return 0;
363 }
364
365 static void stm32_pwm_disable(struct stm32_pwm *priv, int ch)
366 {
367         u32 mask;
368
369         /* Disable channel */
370         mask = TIM_CCER_CC1E << (ch * 4);
371         if (priv->have_complementary_output)
372                 mask |= TIM_CCER_CC1NE << (ch * 4);
373
374         regmap_update_bits(priv->regmap, TIM_CCER, mask, 0);
375
376         /* When all channels are disabled, we can disable the controller */
377         if (!active_channels(priv))
378                 regmap_update_bits(priv->regmap, TIM_CR1, TIM_CR1_CEN, 0);
379
380         clk_disable(priv->clk);
381 }
382
383 static int stm32_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm,
384                            struct pwm_state *state)
385 {
386         bool enabled;
387         struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
388         int ret;
389
390         enabled = pwm->state.enabled;
391
392         if (enabled && !state->enabled) {
393                 stm32_pwm_disable(priv, pwm->hwpwm);
394                 return 0;
395         }
396
397         if (state->polarity != pwm->state.polarity)
398                 stm32_pwm_set_polarity(priv, pwm->hwpwm, state->polarity);
399
400         ret = stm32_pwm_config(priv, pwm->hwpwm,
401                                state->duty_cycle, state->period);
402         if (ret)
403                 return ret;
404
405         if (!enabled && state->enabled)
406                 ret = stm32_pwm_enable(priv, pwm->hwpwm);
407
408         return ret;
409 }
410
411 static int stm32_pwm_apply_locked(struct pwm_chip *chip, struct pwm_device *pwm,
412                                   struct pwm_state *state)
413 {
414         struct stm32_pwm *priv = to_stm32_pwm_dev(chip);
415         int ret;
416
417         /* protect common prescaler for all active channels */
418         mutex_lock(&priv->lock);
419         ret = stm32_pwm_apply(chip, pwm, state);
420         mutex_unlock(&priv->lock);
421
422         return ret;
423 }
424
425 static const struct pwm_ops stm32pwm_ops = {
426         .owner = THIS_MODULE,
427         .apply = stm32_pwm_apply_locked,
428 #if IS_ENABLED(CONFIG_DMA_ENGINE)
429         .capture = stm32_pwm_capture,
430 #endif
431 };
432
433 static int stm32_pwm_set_breakinput(struct stm32_pwm *priv,
434                                     int index, int level, int filter)
435 {
436         u32 bke = (index == 0) ? TIM_BDTR_BKE : TIM_BDTR_BK2E;
437         int shift = (index == 0) ? TIM_BDTR_BKF_SHIFT : TIM_BDTR_BK2F_SHIFT;
438         u32 mask = (index == 0) ? TIM_BDTR_BKE | TIM_BDTR_BKP | TIM_BDTR_BKF
439                                 : TIM_BDTR_BK2E | TIM_BDTR_BK2P | TIM_BDTR_BK2F;
440         u32 bdtr = bke;
441
442         /*
443          * The both bits could be set since only one will be wrote
444          * due to mask value.
445          */
446         if (level)
447                 bdtr |= TIM_BDTR_BKP | TIM_BDTR_BK2P;
448
449         bdtr |= (filter & TIM_BDTR_BKF_MASK) << shift;
450
451         regmap_update_bits(priv->regmap, TIM_BDTR, mask, bdtr);
452
453         regmap_read(priv->regmap, TIM_BDTR, &bdtr);
454
455         return (bdtr & bke) ? 0 : -EINVAL;
456 }
457
458 static int stm32_pwm_apply_breakinputs(struct stm32_pwm *priv,
459                                        struct device_node *np)
460 {
461         struct stm32_breakinput breakinput[MAX_BREAKINPUT];
462         int nb, ret, i, array_size;
463
464         nb = of_property_count_elems_of_size(np, "st,breakinput",
465                                              sizeof(struct stm32_breakinput));
466
467         /*
468          * Because "st,breakinput" parameter is optional do not make probe
469          * failed if it doesn't exist.
470          */
471         if (nb <= 0)
472                 return 0;
473
474         if (nb > MAX_BREAKINPUT)
475                 return -EINVAL;
476
477         array_size = nb * sizeof(struct stm32_breakinput) / sizeof(u32);
478         ret = of_property_read_u32_array(np, "st,breakinput",
479                                          (u32 *)breakinput, array_size);
480         if (ret)
481                 return ret;
482
483         for (i = 0; i < nb && !ret; i++) {
484                 ret = stm32_pwm_set_breakinput(priv,
485                                                breakinput[i].index,
486                                                breakinput[i].level,
487                                                breakinput[i].filter);
488         }
489
490         return ret;
491 }
492
493 static void stm32_pwm_detect_complementary(struct stm32_pwm *priv)
494 {
495         u32 ccer;
496
497         /*
498          * If complementary bit doesn't exist writing 1 will have no
499          * effect so we can detect it.
500          */
501         regmap_update_bits(priv->regmap,
502                            TIM_CCER, TIM_CCER_CC1NE, TIM_CCER_CC1NE);
503         regmap_read(priv->regmap, TIM_CCER, &ccer);
504         regmap_update_bits(priv->regmap, TIM_CCER, TIM_CCER_CC1NE, 0);
505
506         priv->have_complementary_output = (ccer != 0);
507 }
508
509 static int stm32_pwm_detect_channels(struct stm32_pwm *priv)
510 {
511         u32 ccer;
512         int npwm = 0;
513
514         /*
515          * If channels enable bits don't exist writing 1 will have no
516          * effect so we can detect and count them.
517          */
518         regmap_update_bits(priv->regmap,
519                            TIM_CCER, TIM_CCER_CCXE, TIM_CCER_CCXE);
520         regmap_read(priv->regmap, TIM_CCER, &ccer);
521         regmap_update_bits(priv->regmap, TIM_CCER, TIM_CCER_CCXE, 0);
522
523         if (ccer & TIM_CCER_CC1E)
524                 npwm++;
525
526         if (ccer & TIM_CCER_CC2E)
527                 npwm++;
528
529         if (ccer & TIM_CCER_CC3E)
530                 npwm++;
531
532         if (ccer & TIM_CCER_CC4E)
533                 npwm++;
534
535         return npwm;
536 }
537
538 static int stm32_pwm_probe(struct platform_device *pdev)
539 {
540         struct device *dev = &pdev->dev;
541         struct device_node *np = dev->of_node;
542         struct stm32_timers *ddata = dev_get_drvdata(pdev->dev.parent);
543         struct stm32_pwm *priv;
544         int ret;
545
546         priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
547         if (!priv)
548                 return -ENOMEM;
549
550         mutex_init(&priv->lock);
551         priv->regmap = ddata->regmap;
552         priv->clk = ddata->clk;
553         priv->max_arr = ddata->max_arr;
554
555         if (!priv->regmap || !priv->clk)
556                 return -EINVAL;
557
558         ret = stm32_pwm_apply_breakinputs(priv, np);
559         if (ret)
560                 return ret;
561
562         stm32_pwm_detect_complementary(priv);
563
564         priv->chip.base = -1;
565         priv->chip.dev = dev;
566         priv->chip.ops = &stm32pwm_ops;
567         priv->chip.npwm = stm32_pwm_detect_channels(priv);
568
569         ret = pwmchip_add(&priv->chip);
570         if (ret < 0)
571                 return ret;
572
573         platform_set_drvdata(pdev, priv);
574
575         return 0;
576 }
577
578 static int stm32_pwm_remove(struct platform_device *pdev)
579 {
580         struct stm32_pwm *priv = platform_get_drvdata(pdev);
581         unsigned int i;
582
583         for (i = 0; i < priv->chip.npwm; i++)
584                 pwm_disable(&priv->chip.pwms[i]);
585
586         pwmchip_remove(&priv->chip);
587
588         return 0;
589 }
590
591 static const struct of_device_id stm32_pwm_of_match[] = {
592         { .compatible = "st,stm32-pwm", },
593         { /* end node */ },
594 };
595 MODULE_DEVICE_TABLE(of, stm32_pwm_of_match);
596
597 static struct platform_driver stm32_pwm_driver = {
598         .probe  = stm32_pwm_probe,
599         .remove = stm32_pwm_remove,
600         .driver = {
601                 .name = "stm32-pwm",
602                 .of_match_table = stm32_pwm_of_match,
603         },
604 };
605 module_platform_driver(stm32_pwm_driver);
606
607 MODULE_ALIAS("platform:stm32-pwm");
608 MODULE_DESCRIPTION("STMicroelectronics STM32 PWM driver");
609 MODULE_LICENSE("GPL v2");
This page took 0.070962 seconds and 4 git commands to generate.