@@ -33,7 +33,7 @@
#include <linux/units.h>
/* Loongson PWM registers */
-#define LOONGSON_PWM_REG_DUTY 0x4 /* Low Pulse Buffer Register */
+#define LOONGSON_PWM_REG_LOW 0x4 /* Low Pulse Buffer Register */
#define LOONGSON_PWM_REG_PERIOD 0x8 /* Pulse Period Buffer Register */
#define LOONGSON_PWM_REG_CTRL 0xc /* Control Register */
@@ -120,20 +120,20 @@ static int pwm_loongson_enable(struct pwm_chip *chip, struct pwm_device *pwm)
static int pwm_loongson_config(struct pwm_chip *chip, struct pwm_device *pwm,
u64 duty_ns, u64 period_ns)
{
- u64 duty, period;
+ u64 low, duty, period;
struct pwm_loongson_ddata *ddata = to_pwm_loongson_ddata(chip);
- /* duty = duty_ns * ddata->clk_rate / NSEC_PER_SEC */
- duty = mul_u64_u64_div_u64(duty_ns, ddata->clk_rate, NSEC_PER_SEC);
- if (duty > U32_MAX)
- duty = U32_MAX;
-
/* period = period_ns * ddata->clk_rate / NSEC_PER_SEC */
period = mul_u64_u64_div_u64(period_ns, ddata->clk_rate, NSEC_PER_SEC);
if (period > U32_MAX)
period = U32_MAX;
- pwm_loongson_writel(ddata, duty, LOONGSON_PWM_REG_DUTY);
+ /* duty = duty_ns * ddata->clk_rate / NSEC_PER_SEC */
+ duty = mul_u64_u64_div_u64_roundup(duty_ns, ddata->clk_rate, NSEC_PER_SEC);
+ duty = min(duty, period);
+ low = period - duty;
+
+ pwm_loongson_writel(ddata, low, LOONGSON_PWM_REG_LOW);
pwm_loongson_writel(ddata, period, LOONGSON_PWM_REG_PERIOD);
return 0;
@@ -168,15 +168,20 @@ static int pwm_loongson_apply(struct pwm_chip *chip, struct pwm_device *pwm,
static int pwm_loongson_get_state(struct pwm_chip *chip, struct pwm_device *pwm,
struct pwm_state *state)
{
- u32 duty, period, ctrl;
+ u32 low, period, ctrl;
struct pwm_loongson_ddata *ddata = to_pwm_loongson_ddata(chip);
- duty = pwm_loongson_readl(ddata, LOONGSON_PWM_REG_DUTY);
+ low = pwm_loongson_readl(ddata, LOONGSON_PWM_REG_LOW);
period = pwm_loongson_readl(ddata, LOONGSON_PWM_REG_PERIOD);
ctrl = pwm_loongson_readl(ddata, LOONGSON_PWM_REG_CTRL);
- /* duty & period have a max of 2^32, so we can't overflow */
- state->duty_cycle = DIV64_U64_ROUND_UP((u64)duty * NSEC_PER_SEC, ddata->clk_rate);
+ /* low & period have a max of 2^32 - 1, so we can't overflow */
+ if (low >= period)
+ state->duty_cycle = 0;
+ else
+ state->duty_cycle =
+ DIV64_U64_ROUND_UP((u64)(period - low) * NSEC_PER_SEC, ddata->clk_rate);
+
state->period = DIV64_U64_ROUND_UP((u64)period * NSEC_PER_SEC, ddata->clk_rate);
state->polarity = (ctrl & LOONGSON_PWM_CTRL_REG_INVERT) ? PWM_POLARITY_INVERSED :
PWM_POLARITY_NORMAL;