static int mxs_pwm_apply()

in pwm-mxs.c [47:114]


static int mxs_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm,
			 const struct pwm_state *state)
{
	struct mxs_pwm_chip *mxs = to_mxs_pwm_chip(chip);
	int ret, div = 0;
	unsigned int period_cycles, duty_cycles;
	unsigned long rate;
	unsigned long long c;
	unsigned int pol_bits;

	/*
	 * If the PWM channel is disabled, make sure to turn on the
	 * clock before calling clk_get_rate() and writing to the
	 * registers. Otherwise, just keep it enabled.
	 */
	if (!pwm_is_enabled(pwm)) {
		ret = clk_prepare_enable(mxs->clk);
		if (ret)
			return ret;
	}

	if (!state->enabled && pwm_is_enabled(pwm))
		writel(1 << pwm->hwpwm, mxs->base + PWM_CTRL + CLR);

	rate = clk_get_rate(mxs->clk);
	while (1) {
		c = rate >> cdiv_shift[div];
		c = c * state->period;
		do_div(c, 1000000000);
		if (c < PERIOD_PERIOD_MAX)
			break;
		div++;
		if (div >= PERIOD_CDIV_MAX)
			return -EINVAL;
	}

	period_cycles = c;
	c *= state->duty_cycle;
	do_div(c, state->period);
	duty_cycles = c;

	/*
	 * The data sheet the says registers must be written to in
	 * this order (ACTIVEn, then PERIODn). Also, the new settings
	 * only take effect at the beginning of a new period, avoiding
	 * glitches.
	 */

	pol_bits = state->polarity == PWM_POLARITY_NORMAL ?
		PERIOD_POLARITY_NORMAL : PERIOD_POLARITY_INVERSE;
	writel(duty_cycles << 16,
	       mxs->base + PWM_ACTIVE0 + pwm->hwpwm * 0x20);
	writel(PERIOD_PERIOD(period_cycles) | pol_bits | PERIOD_CDIV(div),
	       mxs->base + PWM_PERIOD0 + pwm->hwpwm * 0x20);

	if (state->enabled) {
		if (!pwm_is_enabled(pwm)) {
			/*
			 * The clock was enabled above. Just enable
			 * the channel in the control register.
			 */
			writel(1 << pwm->hwpwm, mxs->base + PWM_CTRL + SET);
		}
	} else {
		clk_disable_unprepare(mxs->clk);
	}
	return 0;
}