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_frequency = 5;
34 static bool wdt_magicclose = false;
36 void watchdog_ping(void)
39 if (wdt_fd >= 0 && write(wdt_fd, "X", 1) < 0)
40 ERROR("WDT failed to write: %s\n", strerror(errno));
43 static void watchdog_timeout_cb(struct uloop_timeout *t)
46 uloop_timeout_set(t, wdt_frequency * 1000);
49 static int watchdog_open(bool cloexec)
51 char *env = getenv("WDTFD");
57 DEBUG(2, "Watchdog handover: fd=%s\n", env);
61 wdt_fd = open(WDT_PATH, O_WRONLY);
68 fcntl(wdt_fd, F_SETFD, fcntl(wdt_fd, F_GETFD) | FD_CLOEXEC);
73 static void watchdog_close(void)
78 if (write(wdt_fd, "V", 1) < 0)
79 ERROR("WDT failed to write release: %s\n", strerror(errno));
81 if (close(wdt_fd) == -1)
82 ERROR("WDT failed to close watchdog: %s\n", strerror(errno));
87 void watchdog_set_magicclose(bool val)
92 bool watchdog_get_magicclose(void)
94 return wdt_magicclose;
97 void watchdog_set_stopped(bool val)
100 uloop_timeout_cancel(&wdt_timeout);
107 watchdog_timeout_cb(&wdt_timeout);
111 bool watchdog_get_stopped(void)
113 return !wdt_timeout.pending;
116 int watchdog_timeout(int timeout)
122 DEBUG(4, "Set watchdog timeout: %ds\n", timeout);
123 ioctl(wdt_fd, WDIOC_SETTIMEOUT, &timeout);
125 ioctl(wdt_fd, WDIOC_GETTIMEOUT, &timeout);
130 int watchdog_frequency(int frequency)
136 DEBUG(4, "Set watchdog frequency: %ds\n", frequency);
137 wdt_frequency = frequency;
140 return wdt_frequency;
143 char* watchdog_fd(void)
145 static char fd_buf[3];
149 snprintf(fd_buf, sizeof(fd_buf), "%d", wdt_fd);
154 void watchdog_init(int preinit)
156 wdt_timeout.cb = watchdog_timeout_cb;
158 if (watchdog_open(!preinit) < 0)
161 LOG("- watchdog -\n");
162 watchdog_timeout(30);
163 watchdog_timeout_cb(&wdt_timeout);
165 DEBUG(4, "Opened watchdog with timeout %ds\n", watchdog_timeout(0));
169 void watchdog_set_cloexec(bool val)
174 int flags = fcntl(wdt_fd, F_GETFD);
178 flags &= ~FD_CLOEXEC;
179 fcntl(wdt_fd, F_SETFD, flags);