1 // SPDX-License-Identifier: GPL-2.0+
3 * GPIO driver wrapping PWM API
5 * PWM 0% and PWM 100% are equivalent to digital GPIO
6 * outputs, and there are times where it is useful to use
7 * PWM outputs as straight GPIOs (eg outputs of NXP PCA9685
8 * I2C PWM chip). This driver wraps the PWM API as a GPIO
11 * Copyright (C) 2021 Raspberry Pi (Trading) Ltd.
14 #include <linux/err.h>
15 #include <linux/gpio/driver.h>
16 #include <linux/module.h>
17 #include <linux/platform_device.h>
18 #include <linux/pwm.h>
22 struct pwm_device **pwm;
25 static int pwm_gpio_get_direction(struct gpio_chip *gc, unsigned int off)
27 return GPIO_LINE_DIRECTION_OUT;
30 static void pwm_gpio_set(struct gpio_chip *gc, unsigned int off, int val)
32 struct pwm_gpio *pwm_gpio = gpiochip_get_data(gc);
33 struct pwm_state state;
35 pwm_get_state(pwm_gpio->pwm[off], &state);
36 state.duty_cycle = val ? state.period : 0;
37 pwm_apply_state(pwm_gpio->pwm[off], &state);
40 static int pwm_gpio_parse_dt(struct pwm_gpio *pwm_gpio,
43 struct device_node *node = dev->of_node;
44 struct pwm_state state;
45 int ret = 0, i, num_gpios;
51 num_gpios = of_property_count_strings(node, "pwm-names");
55 pwm_gpio->pwm = devm_kzalloc(dev,
56 sizeof(*pwm_gpio->pwm) * num_gpios,
61 for (i = 0; i < num_gpios; i++) {
62 ret = of_property_read_string_index(node, "pwm-names", i,
65 dev_err(dev, "unable to get pwm device index %d, name %s",
70 pwm_gpio->pwm[i] = devm_pwm_get(dev, pwm_name);
71 if (IS_ERR(pwm_gpio->pwm[i])) {
72 ret = PTR_ERR(pwm_gpio->pwm[i]);
73 if (ret != -EPROBE_DEFER)
74 dev_err(dev, "unable to request PWM\n");
78 /* Sync up PWM state. */
79 pwm_init_state(pwm_gpio->pwm[i], &state);
82 pwm_apply_state(pwm_gpio->pwm[i], &state);
85 pwm_gpio->gc.ngpio = num_gpios;
91 static int pwm_gpio_probe(struct platform_device *pdev)
93 struct device *dev = &pdev->dev;
94 struct pwm_gpio *pwm_gpio;
97 pwm_gpio = devm_kzalloc(dev, sizeof(*pwm_gpio), GFP_KERNEL);
101 pwm_gpio->gc.parent = dev;
102 pwm_gpio->gc.label = "pwm-gpio";
103 pwm_gpio->gc.owner = THIS_MODULE;
104 pwm_gpio->gc.of_node = dev->of_node;
105 pwm_gpio->gc.base = -1;
107 pwm_gpio->gc.get_direction = pwm_gpio_get_direction;
108 pwm_gpio->gc.set = pwm_gpio_set;
109 pwm_gpio->gc.can_sleep = true;
111 ret = pwm_gpio_parse_dt(pwm_gpio, dev);
115 if (!pwm_gpio->gc.ngpio)
118 return devm_gpiochip_add_data(dev, &pwm_gpio->gc, pwm_gpio);
121 static int pwm_gpio_remove(struct platform_device *pdev)
126 static const struct of_device_id pwm_gpio_of_match[] = {
127 { .compatible = "pwm-gpio" },
130 MODULE_DEVICE_TABLE(of, pwm_gpio_of_match);
132 static struct platform_driver pwm_gpio_driver = {
135 .of_match_table = of_match_ptr(pwm_gpio_of_match),
137 .probe = pwm_gpio_probe,
138 .remove = pwm_gpio_remove,
140 module_platform_driver(pwm_gpio_driver);
142 MODULE_LICENSE("GPL");
143 MODULE_AUTHOR("Dave Stevenson <dave.stevenson@raspberrypi.com>");
144 MODULE_DESCRIPTION("PWM GPIO driver");