1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) 2022 VK
14 #define LEDS_PWM_DRIVER_NAME "led_pwm"
18 uint period; /* period in ns */
19 uint duty; /* duty cycle in ns */
20 uint channel; /* pwm channel number */
21 bool active_low; /* pwm polarity */
25 static int led_pwm_enable(struct udevice *dev)
27 struct led_pwm_priv *priv = dev_get_priv(dev);
30 ret = pwm_set_invert(priv->pwm, priv->channel, priv->active_low);
34 ret = pwm_set_config(priv->pwm, priv->channel, priv->period, priv->duty);
38 ret = pwm_set_enable(priv->pwm, priv->channel, true);
47 static int led_pwm_disable(struct udevice *dev)
49 struct led_pwm_priv *priv = dev_get_priv(dev);
52 ret = pwm_set_config(priv->pwm, priv->channel, priv->period, 0);
56 ret = pwm_set_enable(priv->pwm, priv->channel, false);
60 priv->enabled = false;
65 static int led_pwm_set_state(struct udevice *dev, enum led_state_t state)
67 struct led_pwm_priv *priv = dev_get_priv(dev);
72 ret = led_pwm_disable(dev);
75 ret = led_pwm_enable(dev);
78 ret = (priv->enabled) ? led_pwm_disable(dev) : led_pwm_enable(dev);
87 static enum led_state_t led_pwm_get_state(struct udevice *dev)
89 struct led_pwm_priv *priv = dev_get_priv(dev);
91 return (priv->enabled) ? LEDST_ON : LEDST_OFF;
94 static int led_pwm_probe(struct udevice *dev)
96 struct led_pwm_priv *priv = dev_get_priv(dev);
98 return led_pwm_set_state(dev, (priv->enabled) ? LEDST_ON : LEDST_OFF);
101 static int led_pwm_of_to_plat(struct udevice *dev)
103 struct led_pwm_priv *priv = dev_get_priv(dev);
104 struct ofnode_phandle_args args;
105 uint def_brightness, max_brightness;
108 ret = dev_read_phandle_with_args(dev, "pwms", "#pwm-cells", 0, 0, &args);
112 ret = uclass_get_device_by_ofnode(UCLASS_PWM, args.node, &priv->pwm);
116 priv->channel = args.args[0];
117 priv->period = args.args[1];
118 priv->active_low = dev_read_bool(dev, "active-low");
120 def_brightness = dev_read_u32_default(dev, "u-boot,default-brightness", 0);
121 max_brightness = dev_read_u32_default(dev, "max-brightness", 255);
122 priv->enabled = !!def_brightness;
125 * No need to handle pwm inverted case (active_low)
126 * because of pwm_set_invert function
128 if (def_brightness < max_brightness)
129 priv->duty = priv->period * def_brightness / max_brightness;
131 priv->duty = priv->period;
136 static int led_pwm_bind(struct udevice *parent)
138 return led_bind_generic(parent, LEDS_PWM_DRIVER_NAME);
141 static const struct led_ops led_pwm_ops = {
142 .set_state = led_pwm_set_state,
143 .get_state = led_pwm_get_state,
146 static const struct udevice_id led_pwm_ids[] = {
147 { .compatible = "pwm-leds" },
151 U_BOOT_DRIVER(led_pwm) = {
152 .name = LEDS_PWM_DRIVER_NAME,
155 .priv_auto = sizeof(struct led_pwm_priv),
156 .probe = led_pwm_probe,
157 .of_to_plat = led_pwm_of_to_plat,
160 U_BOOT_DRIVER(led_pwm_wrap) = {
161 .name = LEDS_PWM_DRIVER_NAME "_wrap",
163 .of_match = led_pwm_ids,
164 .bind = led_pwm_bind,