2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
15 #include <linux/watchdog.h>
17 #include <sys/ioctl.h>
18 #include <sys/types.h>
24 #include <libubox/uloop.h>
29 #define WDT_PATH "/dev/watchdog"
31 static struct uloop_timeout wdt_timeout
;
32 static int wdt_fd
= -1;
33 static int wdt_drv_timeout
= 30;
34 static int wdt_frequency
= 5;
35 static bool wdt_magicclose
= false;
37 void watchdog_ping(void)
40 if (wdt_fd
>= 0 && write(wdt_fd
, "X", 1) < 0)
41 ERROR("WDT failed to write: %m\n");
44 static void watchdog_timeout_cb(struct uloop_timeout
*t
)
47 uloop_timeout_set(t
, wdt_frequency
* 1000);
50 static int watchdog_open(bool cloexec
)
52 char *env
= getenv("WDTFD");
58 DEBUG(2, "Watchdog handover: fd=%s\n", env
);
62 wdt_fd
= open(WDT_PATH
, O_WRONLY
);
69 fcntl(wdt_fd
, F_SETFD
, fcntl(wdt_fd
, F_GETFD
) | FD_CLOEXEC
);
74 static void watchdog_close(void)
79 if (write(wdt_fd
, "V", 1) < 0)
80 ERROR("WDT failed to write release: %m\n");
82 if (close(wdt_fd
) == -1)
83 ERROR("WDT failed to close watchdog: %m\n");
88 static int watchdog_set_drv_timeout(void)
93 return ioctl(wdt_fd
, WDIOC_SETTIMEOUT
, &wdt_drv_timeout
);
96 void watchdog_set_magicclose(bool val
)
101 bool watchdog_get_magicclose(void)
103 return wdt_magicclose
;
106 void watchdog_set_stopped(bool val
)
109 uloop_timeout_cancel(&wdt_timeout
);
116 watchdog_set_drv_timeout();
117 watchdog_timeout_cb(&wdt_timeout
);
121 bool watchdog_get_stopped(void)
123 return !wdt_timeout
.pending
;
126 int watchdog_timeout(int timeout
)
129 DEBUG(4, "Set watchdog timeout: %ds\n", timeout
);
130 wdt_drv_timeout
= timeout
;
133 watchdog_set_drv_timeout();
136 return wdt_drv_timeout
;
139 int watchdog_frequency(int frequency
)
142 DEBUG(4, "Set watchdog frequency: %ds\n", frequency
);
143 wdt_frequency
= frequency
;
146 return wdt_frequency
;
149 char* watchdog_fd(void)
151 static char fd_buf
[12];
156 snprintf(fd_buf
, sizeof(fd_buf
), "%d", wdt_fd
);
161 void watchdog_init(int preinit
)
163 wdt_timeout
.cb
= watchdog_timeout_cb
;
165 if (watchdog_open(!preinit
) < 0)
168 LOG("- watchdog -\n");
169 watchdog_set_drv_timeout();
170 watchdog_timeout_cb(&wdt_timeout
);
172 DEBUG(4, "Opened watchdog with timeout %ds\n", watchdog_timeout(0));
176 void watchdog_set_cloexec(bool val
)
181 int flags
= fcntl(wdt_fd
, F_GETFD
);
185 flags
&= ~FD_CLOEXEC
;
186 fcntl(wdt_fd
, F_SETFD
, flags
);