[PATCH v1 5/5] pwm: tiecap: Improve period calculation around overflow handling
From: Uwe Kleine-König
Date: Fri Nov 27 2026 - 12:40:31 EST
Up to now the driver refused to configure for periods longer than 1
second returning -ERANGE. That is wrong for two reasons: a) Too big
requests should be clamped to the biggest possible value; and b)
depending on the input clock rate longer periods are actually possible.
To address this use mul_u64_u64_div_u64() to convert from nanoseconds to
clock ticks which doesn't overflow if the result doesn't overflow. To
ensure the latter make sure that the clock rate isn't faster than 1 GHz.
But in return refuse requests of too small periods.
Signed-off-by: Uwe Kleine-König <u.kleine-koenig@xxxxxxxxxxxx>
---
drivers/pwm/pwm-tiecap.c | 38 ++++++++++++++++++++------------------
1 file changed, 20 insertions(+), 18 deletions(-)
diff --git a/drivers/pwm/pwm-tiecap.c b/drivers/pwm/pwm-tiecap.c
index 05c38967504a..fe803630d753 100644
--- a/drivers/pwm/pwm-tiecap.c
+++ b/drivers/pwm/pwm-tiecap.c
@@ -52,27 +52,25 @@ static inline struct ecap_pwm_chip *to_ecap_pwm_chip(struct pwm_chip *chip)
* duty_ns = 10^9 * duty_cycles / PWM_CLK_RATE
*/
static int ecap_pwm_config(struct pwm_chip *chip, struct pwm_device *pwm,
- int duty_ns, int period_ns, int enabled)
+ u64 duty_ns, u64 period_ns, int enabled)
{
struct ecap_pwm_chip *pc = to_ecap_pwm_chip(chip);
u32 period_cycles, duty_cycles;
- unsigned long long c;
u16 value;
- c = pc->clk_rate;
- c = c * period_ns;
- do_div(c, NSEC_PER_SEC);
- period_cycles = (u32)c;
+ /*
+ * With pc->clk_rate ≤ NSEC_PER_SEC the multiplication+division
+ * doesn't overflow.
+ */
+ period_cycles = min(U32_MAX,
+ mul_u64_u64_div_u64(period_ns, pc->clk_rate,
+ NSEC_PER_SEC));
+ if (period_cycles < 1)
+ return -EINVAL;
- if (period_cycles < 1) {
- period_cycles = 1;
- duty_cycles = 1;
- } else {
- c = pc->clk_rate;
- c = c * duty_ns;
- do_div(c, NSEC_PER_SEC);
- duty_cycles = (u32)c;
- }
+ duty_cycles = min(U32_MAX,
+ mul_u64_u64_div_u64(duty_ns, pc->clk_rate,
+ NSEC_PER_SEC));
pm_runtime_get_sync(pwmchip_parent(chip));
@@ -193,9 +191,6 @@ static int ecap_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm,
return 0;
}
- if (state->period > NSEC_PER_SEC)
- return -ERANGE;
-
err = ecap_pwm_config(chip, pwm, state->duty_cycle,
state->period, enabled);
if (err)
@@ -291,6 +286,13 @@ static int ecap_pwm_probe(struct platform_device *pdev)
pc->clk_rate = clk_get_rate(clk);
if (!pc->clk_rate)
return dev_err_probe(dev, -EINVAL, "Failed to get clock rate\n");
+ /*
+ * By ensuring that clk_rate is at most 1 GHz we can be sure that the
+ * conversion from 64-bit ns to 64-bit clk ticks doesn't overflow.
+ */
+ if (pc->clk_rate > NSEC_PER_SEC)
+ return dev_err_probe(dev, -EINVAL, "Invalid clk rate (%lu Hz)\n",
+ pc->clk_rate);
chip->ops = &ecap_pwm_ops;
--
2.47.3