diff mbox series

[V2,3/6] pwm: sprd: Optimize the calculation method of duty

Message ID 20240125025533.10315-4-Wenhua.Lin@unisoc.com
State New
Headers show
Series [V2,1/6] pwm: sprd: Add support for UMS9620 | expand

Commit Message

Wenhua Lin Jan. 25, 2024, 2:55 a.m. UTC
Use DIV_ROUND_CLOSEST_ULL to avoid overflow and improve accuracy
when calculating duty.

Signed-off-by: Wenhua Lin <Wenhua.Lin@unisoc.com>
---
 drivers/pwm/pwm-sprd.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

Comments

Uwe Kleine-König Jan. 26, 2024, 7:30 a.m. UTC | #1
Hello,

On Thu, Jan 25, 2024 at 10:55:30AM +0800, Wenhua Lin wrote:
> diff --git a/drivers/pwm/pwm-sprd.c b/drivers/pwm/pwm-sprd.c
> index cc54aa77c7e6..8de3f9e154ce 100644
> --- a/drivers/pwm/pwm-sprd.c
> +++ b/drivers/pwm/pwm-sprd.c
> @@ -156,7 +156,8 @@ static int sprd_pwm_config(struct sprd_pwm_chip *spc, struct pwm_device *pwm,
>  	 * given settings (MOD and input clock).
>  	 */
>  	mod = spc->mod[pwm->hwpwm];
> -	duty = duty_ns * mod / period_ns;
> +	tmp = (u64)duty_ns * mod;
> +	duty = DIV_ROUND_CLOSEST_ULL(tmp, period_ns);

Please stick to rounding down in .apply() (and so sprd_pwm_config()).
Given that duty_ns is an u64 in .apply(), you're loosing precision
anyhow. Look at how the microchip-core driver uses mul_u64_u64_div_u64()
for how to do that properly.

You tested your patch with CONFIG_PWM_DEBUG enabled, right?

Best regards
Uwe
diff mbox series

Patch

diff --git a/drivers/pwm/pwm-sprd.c b/drivers/pwm/pwm-sprd.c
index cc54aa77c7e6..8de3f9e154ce 100644
--- a/drivers/pwm/pwm-sprd.c
+++ b/drivers/pwm/pwm-sprd.c
@@ -156,7 +156,8 @@  static int sprd_pwm_config(struct sprd_pwm_chip *spc, struct pwm_device *pwm,
 	 * given settings (MOD and input clock).
 	 */
 	mod = spc->mod[pwm->hwpwm];
-	duty = duty_ns * mod / period_ns;
+	tmp = (u64)duty_ns * mod;
+	duty = DIV_ROUND_CLOSEST_ULL(tmp, period_ns);
 
 	tmp = (u64)chn->clk_rate * period_ns;
 	do_div(tmp, NSEC_PER_SEC);