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;
35 void watchdog_ping(void)
38 if (wdt_fd >= 0 && write(wdt_fd, "X", 1) < 0)
39 ERROR("WDT failed to write: %s\n", strerror(errno));
42 static void watchdog_timeout_cb(struct uloop_timeout *t)
45 uloop_timeout_set(t, wdt_frequency * 1000);
48 void watchdog_set_stopped(bool val)
51 uloop_timeout_cancel(&wdt_timeout);
53 watchdog_timeout_cb(&wdt_timeout);
56 bool watchdog_get_stopped(void)
58 return !wdt_timeout.pending;
61 int watchdog_timeout(int timeout)
67 DEBUG(4, "Set watchdog timeout: %ds\n", timeout);
68 ioctl(wdt_fd, WDIOC_SETTIMEOUT, &timeout);
70 ioctl(wdt_fd, WDIOC_GETTIMEOUT, &timeout);
75 int watchdog_frequency(int frequency)
81 DEBUG(4, "Set watchdog frequency: %ds\n", frequency);
82 wdt_frequency = frequency;
88 char* watchdog_fd(void)
90 static char fd_buf[3];
94 snprintf(fd_buf, sizeof(fd_buf), "%d", wdt_fd);
99 void watchdog_init(int preinit)
101 char *env = getenv("WDTFD");
106 wdt_timeout.cb = watchdog_timeout_cb;
108 DEBUG(2, "Watchdog handover: fd=%s\n", env);
112 wdt_fd = open("/dev/watchdog", O_WRONLY);
119 fcntl(wdt_fd, F_SETFD, fcntl(wdt_fd, F_GETFD) | FD_CLOEXEC);
121 LOG("- watchdog -\n");
122 watchdog_timeout(30);
123 watchdog_timeout_cb(&wdt_timeout);
125 DEBUG(4, "Opened watchdog with timeout %ds\n", watchdog_timeout(0));
129 void watchdog_no_cloexec(void)
134 fcntl(wdt_fd, F_SETFD, fcntl(wdt_fd, F_GETFD) & ~FD_CLOEXEC);