1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Toggles a GPIO pin to power down a device
4 *
5 * Created using the Linux driver as reference, which
6 * has been written by:
7 *
8 * Jamie Lentin <jm@lentin.co.uk>
9 * Andrew Lunn <andrew@lunn.ch>
10 *
11 * Copyright (C) 2012 Jamie Lentin
12 */
13
14 #include <dm.h>
15 #include <errno.h>
16 #include <log.h>
17 #include <sysreset.h>
18
19 #include <asm/gpio.h>
20 #include <linux/delay.h>
21
22 struct poweroff_gpio_info {
23 struct gpio_desc gpio;
24 u32 active_delay_ms;
25 u32 inactive_delay_ms;
26 u32 timeout_ms;
27 };
28
poweroff_gpio_request(struct udevice * dev,enum sysreset_t type)29 static int poweroff_gpio_request(struct udevice *dev, enum sysreset_t type)
30 {
31 struct poweroff_gpio_info *priv = dev_get_priv(dev);
32 int r;
33
34 if (type != SYSRESET_POWER_OFF)
35 return -EPROTONOSUPPORT;
36
37 debug("GPIO poweroff\n");
38
39 /* drive it active, also inactive->active edge */
40 r = dm_gpio_set_value(&priv->gpio, 1);
41 if (r < 0)
42 return r;
43 mdelay(priv->active_delay_ms);
44
45 /* drive inactive, also active->inactive edge */
46 r = dm_gpio_set_value(&priv->gpio, 0);
47 if (r < 0)
48 return r;
49 mdelay(priv->inactive_delay_ms);
50
51 /* drive it active, also inactive->active edge */
52 r = dm_gpio_set_value(&priv->gpio, 1);
53 if (r < 0)
54 return r;
55
56 /* give it some time */
57 mdelay(priv->timeout_ms);
58
59 return -EINPROGRESS;
60 }
61
poweroff_gpio_probe(struct udevice * dev)62 static int poweroff_gpio_probe(struct udevice *dev)
63 {
64 struct poweroff_gpio_info *priv = dev_get_priv(dev);
65 int flags;
66
67 flags = dev_read_bool(dev, "input") ? GPIOD_IS_IN : GPIOD_IS_OUT;
68 priv->active_delay_ms = dev_read_u32_default(dev, "active-delay-ms", 100);
69 priv->inactive_delay_ms = dev_read_u32_default(dev, "inactive-delay-ms", 100);
70 priv->timeout_ms = dev_read_u32_default(dev, "timeout-ms", 3000);
71
72 return gpio_request_by_name(dev, "gpios", 0, &priv->gpio, flags);
73 }
74
75 static struct sysreset_ops poweroff_gpio_ops = {
76 .request = poweroff_gpio_request,
77 };
78
79 static const struct udevice_id poweroff_gpio_ids[] = {
80 { .compatible = "gpio-poweroff", },
81 {},
82 };
83
84 U_BOOT_DRIVER(poweroff_gpio) = {
85 .name = "poweroff-gpio",
86 .id = UCLASS_SYSRESET,
87 .ops = &poweroff_gpio_ops,
88 .probe = poweroff_gpio_probe,
89 .priv_auto = sizeof(struct poweroff_gpio_info),
90 .of_match = poweroff_gpio_ids,
91 };
92