2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2003-2004 Sean M. Kelly <smkelly@FreeBSD.org>
5 * Copyright (c) 2013 iXsystems.com,
6 * author: Alfred Perlstein <alfred@freebsd.org>
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * Software watchdog daemon.
36 #include <sys/types.h>
37 __FBSDID("$FreeBSD$");
40 #include <sys/param.h>
41 #include <sys/rtprio.h>
44 #include <sys/sysctl.h>
45 #include <sys/watchdog.h>
65 static long fetchtimeout(int opt,
66 const char *longopt, const char *myoptarg, int zero_ok);
67 static void parseargs(int, char *[]);
68 static int seconds_to_pow2ns(int);
69 static void sighandler(int);
70 static void watchdog_loop(void);
71 static int watchdog_init(void);
72 static int watchdog_onoff(int onoff);
73 static int watchdog_patpat(u_int timeout);
74 static void usage(void);
75 static int tstotv(struct timeval *tv, struct timespec *ts);
76 static int tvtohz(struct timeval *tv);
78 static int debugging = 0;
79 static int end_program = 0;
80 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
81 static u_int timeout = WD_TO_128SEC;
82 static u_int exit_timeout = WD_TO_NEVER;
83 static u_int pretimeout = 0;
84 static u_int timeout_sec;
85 static u_int nap = 10;
86 static int passive = 0;
87 static int is_daemon = 0;
88 static int is_dry_run = 0; /* do not arm the watchdog, only
89 report on timing of the watch
91 static int do_timedog = 0;
92 static int do_syslog = 1;
94 static int carp_thresh_seconds = -1;
95 static char *test_cmd = NULL;
97 static const char *getopt_shortopts;
99 static int pretimeout_set;
100 static int pretimeout_act;
101 static int pretimeout_act_set;
103 static int softtimeout_set;
104 static int softtimeout_act;
105 static int softtimeout_act_set;
107 static struct option longopts[] = {
108 { "debug", no_argument, &debugging, 1 },
109 { "pretimeout", required_argument, &pretimeout_set, 1 },
110 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
111 { "softtimeout", no_argument, &softtimeout_set, 1 },
112 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
117 * Periodically pat the watchdog, preventing it from firing.
120 main(int argc, char *argv[])
127 errx(EX_SOFTWARE, "not super user");
129 parseargs(argc, argv);
132 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
135 rtp.type = RTP_PRIO_REALTIME;
137 if (rtprio(RTP_SET, 0, &rtp) == -1)
138 err(EX_OSERR, "rtprio");
140 if (!is_dry_run && watchdog_init() == -1)
141 errx(EX_SOFTWARE, "unable to initialize watchdog");
144 if (watchdog_onoff(1) == -1)
145 err(EX_OSERR, "patting the dog");
147 pfh = pidfile_open(pidfile, 0600, &otherpid);
149 if (errno == EEXIST) {
151 errx(EX_SOFTWARE, "%s already running, pid: %d",
152 getprogname(), otherpid);
154 warn("Cannot open or create pidfile");
157 if (debugging == 0 && daemon(0, 0) == -1) {
160 err(EX_OSERR, "daemon");
163 signal(SIGHUP, SIG_IGN);
164 signal(SIGINT, sighandler);
165 signal(SIGTERM, sighandler);
168 if (madvise(0, 0, MADV_PROTECT) != 0)
169 warn("madvise failed");
170 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
171 warn("mlockall failed");
180 timeout |= WD_PASSIVE;
182 timeout |= WD_ACTIVE;
183 if (watchdog_patpat(timeout) < 0)
184 err(EX_OSERR, "patting the dog");
190 pow2ns_to_ts(int pow2ns, struct timespec *ts)
195 ts->tv_sec = ns / 1000000000ULL;
196 ts->tv_nsec = ns % 1000000000ULL;
200 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
203 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
206 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
213 char shortopt[] = "- ";
218 a = fetchtimeout(opt, longopt, myoptarg, 1);
223 rv = seconds_to_pow2ns(a);
224 pow2ns_to_ts(rv, &ts);
228 printf("Timeout for %s%s "
229 "is 2^%d nanoseconds "
230 "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
231 longopt ? "-" : "", longopt ? longopt : shortopt,
233 myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
236 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
243 * Catch signals and begin shutdown process.
246 sighandler(int signum)
249 if (signum == SIGINT || signum == SIGTERM)
254 * Open the watchdog device.
263 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
266 warn("Could not open watchdog device");
271 * If we are doing timing, then get the time.
274 watchdog_getuptime(struct timespec *tp)
281 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
283 warn("clock_gettime");
288 watchdog_check_dogfunction_time(struct timespec *tp_start,
289 struct timespec *tp_end)
291 struct timeval tv_start, tv_end, tv_now, tv;
292 const char *cmd_prefix, *cmd;
293 struct timespec tp_now;
299 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
300 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
301 timersub(&tv_end, &tv_start, &tv);
303 if (sec < carp_thresh_seconds)
307 cmd_prefix = "Watchdog program";
310 cmd_prefix = "Watchdog operation";
311 cmd = "stat(\"/etc\", &sb)";
314 syslog(LOG_CRIT, "%s: '%s' took too long: "
315 "%d.%06ld seconds >= %d seconds threshold",
316 cmd_prefix, cmd, sec, (long)tv.tv_usec,
317 carp_thresh_seconds);
319 warnx("%s: '%s' took too long: "
320 "%d.%06ld seconds >= %d seconds threshold",
321 cmd_prefix, cmd, sec, (long)tv.tv_usec,
322 carp_thresh_seconds);
325 * Adjust the sleep interval again in case syslog(3) took a non-trivial
326 * amount of time to run.
328 if (watchdog_getuptime(&tp_now))
330 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
331 timersub(&tv_now, &tv_start, &tv);
338 * Main program loop which is iterated every second.
343 struct timespec ts_start, ts_end;
348 while (end_program != 2) {
351 error = watchdog_getuptime(&ts_start);
357 if (test_cmd != NULL)
358 failed = system(test_cmd);
360 failed = stat("/etc", &sb);
362 error = watchdog_getuptime(&ts_end);
369 watchdog_patpat(timeout|WD_ACTIVE);
371 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
372 if (nap - waited > 0)
376 if (end_program != 0) {
377 if (watchdog_onoff(0) == 0) {
380 warnx("Could not stop the watchdog, not exiting");
388 * Reset the watchdog timer. This function must be called periodically
389 * to keep the watchdog from firing.
392 watchdog_patpat(u_int t)
398 return ioctl(fd, WDIOCPATPAT, &t);
402 * Toggle the kernel's watchdog. This routine is used to enable and
403 * disable the watchdog.
406 watchdog_onoff(int onoff)
410 /* fake successful watchdog op if a dry run */
416 * Call the WDIOC_SETSOFT regardless of softtimeout_set
417 * because we'll need to turn it off if someone had turned
420 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
422 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
425 error = watchdog_patpat((timeout|WD_ACTIVE));
427 warn("watchdog_patpat failed");
430 if (softtimeout_act_set) {
431 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
434 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
439 if (pretimeout_set) {
440 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
442 warn("setting WDIOC_SETPRETIMEOUT %d",
447 if (pretimeout_act_set) {
448 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
451 warn("setting WDIOC_SETPRETIMEOUTACT %d",
456 /* pat one more time for good measure */
457 return watchdog_patpat((timeout|WD_ACTIVE));
459 return watchdog_patpat(exit_timeout);
462 watchdog_patpat(exit_timeout);
467 * Tell user how to use the program.
473 fprintf(stderr, "usage:\n"
474 " watchdogd [-dnSw] [-e cmd] [-I pidfile] [-s sleep] [-t timeout]\n"
475 " [-T script_timeout] [-x exit_timeout]\n"
477 " [--pretimeout seconds] [-pretimeout-action action]\n"
478 " [--softtimeout] [-softtimeout-action action]\n"
481 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
486 fetchtimeout(int opt, const char *longopt, const char *myoptarg, int zero_ok)
495 rv = strtol(myoptarg, &p, 0);
496 if ((p != NULL && *p != '\0') || errno != 0)
497 errstr = "is not a number";
498 if (rv < 0 || (!zero_ok && rv == 0))
499 errstr = "must be greater than zero";
502 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
504 errx(EX_USAGE, "-%c argument %s", opt, errstr);
514 static const struct act_tbl act_tbl[] = {
515 { "panic", WD_SOFT_PANIC },
516 { "ddb", WD_SOFT_DDB },
517 { "log", WD_SOFT_LOG },
518 { "printf", WD_SOFT_PRINTF },
523 timeout_act_error(const char *lopt, const char *badact)
525 char *opts, *oldopts;
529 for (i = 0; act_tbl[i].at_act != NULL; i++) {
531 if (asprintf(&opts, "%s%s%s",
532 oldopts == NULL ? "" : oldopts,
533 oldopts == NULL ? "" : ", ",
534 act_tbl[i].at_act) == -1)
535 err(EX_OSERR, "malloc");
538 warnx("bad --%s argument '%s' must be one of (%s).",
544 * Take a comma separated list of actions and or the flags
545 * together for the ioctl.
548 timeout_act_str2int(const char *lopt, const char *acts)
551 char *dupacts, *tofree;
555 tofree = dupacts = strdup(acts);
557 err(EX_OSERR, "malloc");
558 while ((o = strsep(&dupacts, ",")) != NULL) {
559 for (i = 0; act_tbl[i].at_act != NULL; i++) {
560 if (!strcmp(o, act_tbl[i].at_act)) {
561 rv |= act_tbl[i].at_value;
565 if (act_tbl[i].at_act == NULL)
566 timeout_act_error(lopt, o);
573 tstotv(struct timeval *tv, struct timespec *ts)
576 tv->tv_sec = ts->tv_sec;
577 tv->tv_usec = ts->tv_nsec / 1000;
582 * Convert a timeval to a number of ticks.
583 * Mostly copied from the kernel.
586 tvtohz(struct timeval *tv)
588 register unsigned long ticks;
589 register long sec, usec;
597 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
599 err(1, "sysctlbyname kern.hz");
604 * If the number of usecs in the whole seconds part of the time
605 * difference fits in a long, then the total number of usecs will
606 * fit in an unsigned long. Compute the total and convert it to
607 * ticks, rounding up and adding 1 to allow for the current tick
608 * to expire. Rounding also depends on unsigned long arithmetic
611 * Otherwise, if the number of ticks in the whole seconds part of
612 * the time difference fits in a long, then convert the parts to
613 * ticks separately and add, using similar rounding methods and
614 * overflow avoidance. This method would work in the previous
615 * case but it is slightly slower and assumes that hz is integral.
617 * Otherwise, round the time difference down to the maximum
618 * representable value.
620 * If ints have 32 bits, then the maximum value for any timeout in
621 * 10ms ticks is 248 days.
635 printf("tvotohz: negative time difference %ld sec %ld usec\n",
639 } else if (sec <= LONG_MAX / 1000000)
640 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
642 else if (sec <= LONG_MAX / hz)
644 + ((unsigned long)usec + (tick - 1)) / tick + 1;
653 seconds_to_pow2ns(int seconds)
660 errx(1, "seconds %d < 0", seconds);
661 ns = ((uint64_t)seconds) * 1000000000ULL;
663 shifted = 1ULL << power;
668 printf("shifted %lld\n", (long long)shifted);
669 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
670 seconds, (long long)ns, (int)power);
677 * Handle the few command line arguments supported.
680 parseargs(int argc, char *argv[])
687 /* Get the default value of timeout_sec from the default timeout. */
688 pow2ns_to_ts(timeout, &ts);
689 timeout_sec = ts.tv_sec;
692 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
693 * otherwise run as a command line utility.
696 if (argv[0][c - 1] == 'd')
700 getopt_shortopts = "I:de:ns:t:ST:wx:?";
702 getopt_shortopts = "dt:?";
704 while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
705 &longindex)) != -1) {
714 test_cmd = strdup(optarg);
725 nap = fetchtimeout(c, NULL, optarg, 0);
731 timeout_sec = atoi(optarg);
732 timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
734 printf("Timeout is 2^%d nanoseconds\n",
738 carp_thresh_seconds =
739 fetchtimeout(c, "NULL", optarg, 0);
745 exit_timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
746 if (exit_timeout != 0)
747 exit_timeout |= WD_ACTIVE;
750 lopt = longopts[longindex].name;
751 if (!strcmp(lopt, "pretimeout")) {
752 pretimeout = fetchtimeout(0, lopt, optarg, 0);
753 } else if (!strcmp(lopt, "pretimeout-action")) {
754 pretimeout_act = timeout_act_str2int(lopt,
756 } else if (!strcmp(lopt, "softtimeout-action")) {
757 softtimeout_act = timeout_act_str2int(lopt,
760 /* warnx("bad option at index %d: %s", optind,
773 if (nap > timeout_sec / 2)
774 nap = timeout_sec / 2;
776 if (carp_thresh_seconds == -1)
777 carp_thresh_seconds = nap;
780 errx(EX_USAGE, "extra arguments.");
781 if (is_daemon && timeout < WD_TO_1SEC)
782 errx(EX_USAGE, "-t argument is less than one second.");
783 if (pretimeout_set) {
784 if (pretimeout >= timeout_sec) {
786 "pretimeout (%d) >= timeout (%d -> %ld)\n"
787 "see manual section TIMEOUT RESOLUTION",
788 pretimeout, timeout_sec, (long)ts.tv_sec);