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 <common.h>
15 #include <dm.h>
16 #include <errno.h>
17 #include <log.h>
18 #include <sysreset.h>
19 
20 #include <asm/gpio.h>
21 #include <linux/delay.h>
22 
23 struct poweroff_gpio_info {
24 	struct gpio_desc gpio;
25 	u32 active_delay_ms;
26 	u32 inactive_delay_ms;
27 	u32 timeout_ms;
28 };
29 
poweroff_gpio_request(struct udevice * dev,enum sysreset_t type)30 static int poweroff_gpio_request(struct udevice *dev, enum sysreset_t type)
31 {
32 	struct poweroff_gpio_info *priv = dev_get_priv(dev);
33 	int r;
34 
35 	if (type != SYSRESET_POWER_OFF)
36 		return -ENOSYS;
37 
38 	debug("GPIO poweroff\n");
39 
40 	/* drive it active, also inactive->active edge */
41 	r = dm_gpio_set_value(&priv->gpio, 1);
42 	if (r < 0)
43 		return r;
44 	mdelay(priv->active_delay_ms);
45 
46 	/* drive inactive, also active->inactive edge */
47 	r = dm_gpio_set_value(&priv->gpio, 0);
48 	if (r < 0)
49 		return r;
50 	mdelay(priv->inactive_delay_ms);
51 
52 	/* drive it active, also inactive->active edge */
53 	r = dm_gpio_set_value(&priv->gpio, 1);
54 	if (r < 0)
55 		return r;
56 
57 	/* give it some time */
58 	mdelay(priv->timeout_ms);
59 
60 	return -EINPROGRESS;
61 }
62 
poweroff_gpio_probe(struct udevice * dev)63 static int poweroff_gpio_probe(struct udevice *dev)
64 {
65 	struct poweroff_gpio_info *priv = dev_get_priv(dev);
66 	int flags;
67 
68 	flags = dev_read_bool(dev, "input") ? GPIOD_IS_IN : GPIOD_IS_OUT;
69 	priv->active_delay_ms = dev_read_u32_default(dev, "active-delay-ms", 100);
70 	priv->inactive_delay_ms = dev_read_u32_default(dev, "inactive-delay-ms", 100);
71 	priv->timeout_ms = dev_read_u32_default(dev, "timeout-ms", 3000);
72 
73 	return gpio_request_by_name(dev, "gpios", 0, &priv->gpio, flags);
74 }
75 
76 static struct sysreset_ops poweroff_gpio_ops = {
77 	.request = poweroff_gpio_request,
78 };
79 
80 static const struct udevice_id poweroff_gpio_ids[] = {
81 	{ .compatible = "gpio-poweroff", },
82 	{},
83 };
84 
85 U_BOOT_DRIVER(poweroff_gpio) = {
86 	.name		= "poweroff-gpio",
87 	.id		= UCLASS_SYSRESET,
88 	.ops		= &poweroff_gpio_ops,
89 	.probe		= poweroff_gpio_probe,
90 	.priv_auto	= sizeof(struct poweroff_gpio_info),
91 	.of_match	= poweroff_gpio_ids,
92 };
93