1 // SPDX-License-Identifier: GPL-2.0-only
3 * linux/arch/unicore32/kernel/pwm.c
5 * Code specific to PKUnity SoC and UniCore ISA
8 * Copyright (C) 2001-2010 Guan Xuetao
11 #include <linux/module.h>
12 #include <linux/kernel.h>
13 #include <linux/platform_device.h>
14 #include <linux/slab.h>
15 #include <linux/err.h>
16 #include <linux/clk.h>
18 #include <linux/pwm.h>
20 #include <asm/div64.h>
21 #include <mach/hardware.h>
23 struct puv3_pwm_chip {
29 static inline struct puv3_pwm_chip *to_puv3(struct pwm_chip *chip)
31 return container_of(chip, struct puv3_pwm_chip, chip);
35 * period_ns = 10^9 * (PRESCALE + 1) * (PV + 1) / PWM_CLK_RATE
36 * duty_ns = 10^9 * (PRESCALE + 1) * DC / PWM_CLK_RATE
38 static int puv3_pwm_config(struct pwm_chip *chip, struct pwm_device *pwm,
39 int duty_ns, int period_ns)
41 unsigned long period_cycles, prescale, pv, dc;
42 struct puv3_pwm_chip *puv3 = to_puv3(chip);
45 c = clk_get_rate(puv3->clk);
47 do_div(c, 1000000000);
50 if (period_cycles < 1)
53 prescale = (period_cycles - 1) / 1024;
54 pv = period_cycles / (prescale + 1) - 1;
59 if (duty_ns == period_ns)
60 dc = OST_PWMDCCR_FDCYCLE;
62 dc = (pv + 1) * duty_ns / period_ns;
65 * NOTE: the clock to PWM has to be enabled first
66 * before writing to the registers
68 clk_prepare_enable(puv3->clk);
70 writel(prescale, puv3->base + OST_PWM_PWCR);
71 writel(pv - dc, puv3->base + OST_PWM_DCCR);
72 writel(pv, puv3->base + OST_PWM_PCR);
74 clk_disable_unprepare(puv3->clk);
79 static int puv3_pwm_enable(struct pwm_chip *chip, struct pwm_device *pwm)
81 struct puv3_pwm_chip *puv3 = to_puv3(chip);
83 return clk_prepare_enable(puv3->clk);
86 static void puv3_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm)
88 struct puv3_pwm_chip *puv3 = to_puv3(chip);
90 clk_disable_unprepare(puv3->clk);
93 static const struct pwm_ops puv3_pwm_ops = {
94 .config = puv3_pwm_config,
95 .enable = puv3_pwm_enable,
96 .disable = puv3_pwm_disable,
100 static int pwm_probe(struct platform_device *pdev)
102 struct puv3_pwm_chip *puv3;
106 puv3 = devm_kzalloc(&pdev->dev, sizeof(*puv3), GFP_KERNEL);
110 puv3->clk = devm_clk_get(&pdev->dev, "OST_CLK");
111 if (IS_ERR(puv3->clk))
112 return PTR_ERR(puv3->clk);
114 r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
115 puv3->base = devm_ioremap_resource(&pdev->dev, r);
116 if (IS_ERR(puv3->base))
117 return PTR_ERR(puv3->base);
119 puv3->chip.dev = &pdev->dev;
120 puv3->chip.ops = &puv3_pwm_ops;
121 puv3->chip.base = -1;
124 ret = pwmchip_add(&puv3->chip);
126 dev_err(&pdev->dev, "pwmchip_add() failed: %d\n", ret);
130 platform_set_drvdata(pdev, puv3);
134 static int pwm_remove(struct platform_device *pdev)
136 struct puv3_pwm_chip *puv3 = platform_get_drvdata(pdev);
138 return pwmchip_remove(&puv3->chip);
141 static struct platform_driver puv3_pwm_driver = {
143 .name = "PKUnity-v3-PWM",
146 .remove = pwm_remove,
148 module_platform_driver(puv3_pwm_driver);
150 MODULE_LICENSE("GPL v2");