power: regulator: pwm: support pwm polarity setting

The latest kernel PWM drivers enable the polarity settings. When system
run from U-Boot to kerenl, if there are differences in polarity set or
duty cycle, the PMW will re-init:
  close -> set polarity and duty cycle -> enable the PWM.
The power supply controled by pwm regulator may have voltage shaking,
which lead to the system not stable.

Signed-off-by: Elaine Zhang <zhangqing@rock-chips.com>
Signed-off-by: Kever Yang <kever.yang@rock-chips.com>
Acked-by: Simon Glass <sjg@chromium.org>
diff --git a/drivers/power/regulator/pwm_regulator.c b/drivers/power/regulator/pwm_regulator.c
index 4875238..a6c9fcc 100644
--- a/drivers/power/regulator/pwm_regulator.c
+++ b/drivers/power/regulator/pwm_regulator.c
@@ -24,6 +24,12 @@
 	int pwm_id;
 	/* the period of one PWM cycle */
 	int period_ns;
+	/*
+	 * the polarity of one PWM
+	 * 0: normal polarity
+	 * 1: inverted polarity
+	 */
+	bool polarity;
 	struct udevice *pwm;
 	/* initialize voltage of regulator */
 	unsigned int init_voltage;
@@ -49,7 +55,7 @@
 	int max_uV = priv->max_voltage;
 	int diff = max_uV - min_uV;
 
-	return 100 - (((req_uV * 100) - (min_uV * 100)) / diff);
+	return ((req_uV * 100) - (min_uV * 100)) / diff;
 }
 
 static int pwm_regulator_get_voltage(struct udevice *dev)
@@ -67,6 +73,12 @@
 
 	duty_cycle = pwm_voltage_to_duty_cycle_percentage(dev, uvolt);
 
+	ret = pwm_set_invert(priv->pwm, priv->pwm_id, priv->polarity);
+	if (ret) {
+		dev_err(dev, "Failed to init PWM\n");
+		return ret;
+	}
+
 	ret = pwm_set_config(priv->pwm, priv->pwm_id,
 			(priv->period_ns / 100) * duty_cycle, priv->period_ns);
 	if (ret) {
@@ -97,9 +109,9 @@
 		debug("%s: Cannot get PWM phandle: ret=%d\n", __func__, ret);
 		return ret;
 	}
-	/* TODO: pwm_id here from device tree if needed */
 
 	priv->period_ns = args.args[1];
+	priv->polarity = args.args[2];
 
 	priv->init_voltage = fdtdec_get_int(blob, node,
 			"regulator-init-microvolt", -1);