1 // SPDX-License-Identifier: GPL-2.0-only
3 * Toggles a GPIO pin to power down a device
5 * Jamie Lentin <jm@lentin.co.uk>
6 * Andrew Lunn <andrew@lunn.ch>
8 * Copyright (C) 2012 Jamie Lentin
10 #include <linux/kernel.h>
11 #include <linux/init.h>
12 #include <linux/delay.h>
13 #include <linux/platform_device.h>
14 #include <linux/property.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/mod_devicetable.h>
17 #include <linux/module.h>
18 #include <linux/reboot.h>
20 #define DEFAULT_TIMEOUT_MS 3000
22 struct gpio_poweroff {
23 struct gpio_desc *reset_gpio;
26 u32 inactive_delay_ms;
29 static int gpio_poweroff_do_poweroff(struct sys_off_data *data)
31 struct gpio_poweroff *gpio_poweroff = data->cb_data;
33 /* drive it active, also inactive->active edge */
34 gpiod_direction_output(gpio_poweroff->reset_gpio, 1);
35 mdelay(gpio_poweroff->active_delay_ms);
37 /* drive inactive, also active->inactive edge */
38 gpiod_set_value_cansleep(gpio_poweroff->reset_gpio, 0);
39 mdelay(gpio_poweroff->inactive_delay_ms);
41 /* drive it active, also inactive->active edge */
42 gpiod_set_value_cansleep(gpio_poweroff->reset_gpio, 1);
44 /* give it some time */
45 mdelay(gpio_poweroff->timeout_ms);
52 static int gpio_poweroff_probe(struct platform_device *pdev)
54 struct gpio_poweroff *gpio_poweroff;
56 enum gpiod_flags flags;
57 int priority = SYS_OFF_PRIO_DEFAULT;
60 gpio_poweroff = devm_kzalloc(&pdev->dev, sizeof(*gpio_poweroff), GFP_KERNEL);
64 input = device_property_read_bool(&pdev->dev, "input");
68 flags = GPIOD_OUT_LOW;
71 gpio_poweroff->active_delay_ms = 100;
72 gpio_poweroff->inactive_delay_ms = 100;
73 gpio_poweroff->timeout_ms = DEFAULT_TIMEOUT_MS;
75 device_property_read_u32(&pdev->dev, "active-delay-ms", &gpio_poweroff->active_delay_ms);
76 device_property_read_u32(&pdev->dev, "inactive-delay-ms",
77 &gpio_poweroff->inactive_delay_ms);
78 device_property_read_u32(&pdev->dev, "timeout-ms", &gpio_poweroff->timeout_ms);
79 device_property_read_u32(&pdev->dev, "priority", &priority);
81 dev_err(&pdev->dev, "Invalid priority property: %u\n", priority);
85 gpio_poweroff->reset_gpio = devm_gpiod_get(&pdev->dev, NULL, flags);
86 if (IS_ERR(gpio_poweroff->reset_gpio))
87 return PTR_ERR(gpio_poweroff->reset_gpio);
89 ret = devm_register_sys_off_handler(&pdev->dev, SYS_OFF_MODE_POWER_OFF,
90 priority, gpio_poweroff_do_poweroff, gpio_poweroff);
92 return dev_err_probe(&pdev->dev, ret, "Cannot register poweroff handler\n");
97 static const struct of_device_id of_gpio_poweroff_match[] = {
98 { .compatible = "gpio-poweroff", },
101 MODULE_DEVICE_TABLE(of, of_gpio_poweroff_match);
103 static struct platform_driver gpio_poweroff_driver = {
104 .probe = gpio_poweroff_probe,
106 .name = "poweroff-gpio",
107 .of_match_table = of_gpio_poweroff_match,
111 module_platform_driver(gpio_poweroff_driver);
113 MODULE_AUTHOR("Jamie Lentin <jm@lentin.co.uk>");
114 MODULE_DESCRIPTION("GPIO poweroff driver");
115 MODULE_ALIAS("platform:poweroff-gpio");