2 * Copyright (c) 2003-2004 Sean M. Kelly <smkelly@FreeBSD.org>
3 * Copyright (c) 2013 iXsystems.com,
4 * author: Alfred Perlstein <alfred@freebsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * Software watchdog daemon.
34 #include <sys/types.h>
35 __FBSDID("$FreeBSD$");
38 #include <sys/param.h>
39 #include <sys/rtprio.h>
42 #include <sys/sysctl.h>
43 #include <sys/watchdog.h>
63 static long fetchtimeout(int opt,
64 const char *longopt, const char *myoptarg, int zero_ok);
65 static void parseargs(int, char *[]);
66 static int seconds_to_pow2ns(int);
67 static void sighandler(int);
68 static void watchdog_loop(void);
69 static int watchdog_init(void);
70 static int watchdog_onoff(int onoff);
71 static int watchdog_patpat(u_int timeout);
72 static void usage(void);
73 static int tstotv(struct timeval *tv, struct timespec *ts);
74 static int tvtohz(struct timeval *tv);
76 static int debugging = 0;
77 static int end_program = 0;
78 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
79 static u_int timeout = WD_TO_128SEC;
80 static u_int exit_timeout = WD_TO_NEVER;
81 static u_int pretimeout = 0;
82 static u_int timeout_sec;
83 static u_int nap = 10;
84 static int passive = 0;
85 static int is_daemon = 0;
86 static int is_dry_run = 0; /* do not arm the watchdog, only
87 report on timing of the watch
89 static int do_timedog = 0;
90 static int do_syslog = 1;
92 static int carp_thresh_seconds = -1;
93 static char *test_cmd = NULL;
95 static const char *getopt_shortopts;
97 static int pretimeout_set;
98 static int pretimeout_act;
99 static int pretimeout_act_set;
101 static int softtimeout_set;
102 static int softtimeout_act;
103 static int softtimeout_act_set;
105 static struct option longopts[] = {
106 { "debug", no_argument, &debugging, 1 },
107 { "pretimeout", required_argument, &pretimeout_set, 1 },
108 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
109 { "softtimeout", no_argument, &softtimeout_set, 1 },
110 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
115 * Periodically pat the watchdog, preventing it from firing.
118 main(int argc, char *argv[])
125 errx(EX_SOFTWARE, "not super user");
127 parseargs(argc, argv);
130 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
133 rtp.type = RTP_PRIO_REALTIME;
135 if (rtprio(RTP_SET, 0, &rtp) == -1)
136 err(EX_OSERR, "rtprio");
138 if (!is_dry_run && watchdog_init() == -1)
139 errx(EX_SOFTWARE, "unable to initialize watchdog");
142 if (watchdog_onoff(1) == -1)
143 err(EX_OSERR, "patting the dog");
145 pfh = pidfile_open(pidfile, 0600, &otherpid);
147 if (errno == EEXIST) {
149 errx(EX_SOFTWARE, "%s already running, pid: %d",
150 getprogname(), otherpid);
152 warn("Cannot open or create pidfile");
155 if (debugging == 0 && daemon(0, 0) == -1) {
158 err(EX_OSERR, "daemon");
161 signal(SIGHUP, SIG_IGN);
162 signal(SIGINT, sighandler);
163 signal(SIGTERM, sighandler);
166 if (madvise(0, 0, MADV_PROTECT) != 0)
167 warn("madvise failed");
168 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
169 warn("mlockall failed");
178 timeout |= WD_PASSIVE;
180 timeout |= WD_ACTIVE;
181 if (watchdog_patpat(timeout) < 0)
182 err(EX_OSERR, "patting the dog");
188 pow2ns_to_ts(int pow2ns, struct timespec *ts)
193 ts->tv_sec = ns / 1000000000ULL;
194 ts->tv_nsec = ns % 1000000000ULL;
198 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
201 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
204 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
211 char shortopt[] = "- ";
216 a = fetchtimeout(opt, longopt, myoptarg, 1);
221 rv = seconds_to_pow2ns(a);
222 pow2ns_to_ts(rv, &ts);
226 printf("Timeout for %s%s "
227 "is 2^%d nanoseconds "
228 "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
229 longopt ? "-" : "", longopt ? longopt : shortopt,
231 myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
234 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
241 * Catch signals and begin shutdown process.
244 sighandler(int signum)
247 if (signum == SIGINT || signum == SIGTERM)
252 * Open the watchdog device.
261 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
264 warn("Could not open watchdog device");
269 * If we are doing timing, then get the time.
272 watchdog_getuptime(struct timespec *tp)
279 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
281 warn("clock_gettime");
286 watchdog_check_dogfunction_time(struct timespec *tp_start,
287 struct timespec *tp_end)
289 struct timeval tv_start, tv_end, tv_now, tv;
290 const char *cmd_prefix, *cmd;
291 struct timespec tp_now;
297 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
298 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
299 timersub(&tv_end, &tv_start, &tv);
301 if (sec < carp_thresh_seconds)
305 cmd_prefix = "Watchdog program";
308 cmd_prefix = "Watchdog operation";
309 cmd = "stat(\"/etc\", &sb)";
312 syslog(LOG_CRIT, "%s: '%s' took too long: "
313 "%d.%06ld seconds >= %d seconds threshold",
314 cmd_prefix, cmd, sec, (long)tv.tv_usec,
315 carp_thresh_seconds);
317 warnx("%s: '%s' took too long: "
318 "%d.%06ld seconds >= %d seconds threshold",
319 cmd_prefix, cmd, sec, (long)tv.tv_usec,
320 carp_thresh_seconds);
323 * Adjust the sleep interval again in case syslog(3) took a non-trivial
324 * amount of time to run.
326 if (watchdog_getuptime(&tp_now))
328 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
329 timersub(&tv_now, &tv_start, &tv);
336 * Main program loop which is iterated every second.
341 struct timespec ts_start, ts_end;
346 while (end_program != 2) {
349 error = watchdog_getuptime(&ts_start);
355 if (test_cmd != NULL)
356 failed = system(test_cmd);
358 failed = stat("/etc", &sb);
360 error = watchdog_getuptime(&ts_end);
367 watchdog_patpat(timeout|WD_ACTIVE);
369 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
370 if (nap - waited > 0)
374 if (end_program != 0) {
375 if (watchdog_onoff(0) == 0) {
378 warnx("Could not stop the watchdog, not exiting");
386 * Reset the watchdog timer. This function must be called periodically
387 * to keep the watchdog from firing.
390 watchdog_patpat(u_int t)
396 return ioctl(fd, WDIOCPATPAT, &t);
400 * Toggle the kernel's watchdog. This routine is used to enable and
401 * disable the watchdog.
404 watchdog_onoff(int onoff)
408 /* fake successful watchdog op if a dry run */
414 * Call the WDIOC_SETSOFT regardless of softtimeout_set
415 * because we'll need to turn it off if someone had turned
418 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
420 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
423 error = watchdog_patpat((timeout|WD_ACTIVE));
425 warn("watchdog_patpat failed");
428 if (softtimeout_act_set) {
429 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
432 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
437 if (pretimeout_set) {
438 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
440 warn("setting WDIOC_SETPRETIMEOUT %d",
445 if (pretimeout_act_set) {
446 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
449 warn("setting WDIOC_SETPRETIMEOUTACT %d",
454 /* pat one more time for good measure */
455 return watchdog_patpat((timeout|WD_ACTIVE));
457 return watchdog_patpat(exit_timeout);
460 watchdog_patpat(exit_timeout);
465 * Tell user how to use the program.
471 fprintf(stderr, "usage:\n"
472 " watchdogd [-dnSw] [-e cmd] [-I pidfile] [-s sleep] [-t timeout]\n"
473 " [-T script_timeout] [-x exit_timeout]\n"
475 " [--pretimeout seconds] [-pretimeout-action action]\n"
476 " [--softtimeout] [-softtimeout-action action]\n"
479 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
484 fetchtimeout(int opt, const char *longopt, const char *myoptarg, int zero_ok)
493 rv = strtol(myoptarg, &p, 0);
494 if ((p != NULL && *p != '\0') || errno != 0)
495 errstr = "is not a number";
496 if (rv < 0 || (!zero_ok && rv == 0))
497 errstr = "must be greater than zero";
500 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
502 errx(EX_USAGE, "-%c argument %s", opt, errstr);
512 static const struct act_tbl act_tbl[] = {
513 { "panic", WD_SOFT_PANIC },
514 { "ddb", WD_SOFT_DDB },
515 { "log", WD_SOFT_LOG },
516 { "printf", WD_SOFT_PRINTF },
521 timeout_act_error(const char *lopt, const char *badact)
523 char *opts, *oldopts;
527 for (i = 0; act_tbl[i].at_act != NULL; i++) {
529 if (asprintf(&opts, "%s%s%s",
530 oldopts == NULL ? "" : oldopts,
531 oldopts == NULL ? "" : ", ",
532 act_tbl[i].at_act) == -1)
533 err(EX_OSERR, "malloc");
536 warnx("bad --%s argument '%s' must be one of (%s).",
542 * Take a comma separated list of actions and or the flags
543 * together for the ioctl.
546 timeout_act_str2int(const char *lopt, const char *acts)
549 char *dupacts, *tofree;
553 tofree = dupacts = strdup(acts);
555 err(EX_OSERR, "malloc");
556 while ((o = strsep(&dupacts, ",")) != NULL) {
557 for (i = 0; act_tbl[i].at_act != NULL; i++) {
558 if (!strcmp(o, act_tbl[i].at_act)) {
559 rv |= act_tbl[i].at_value;
563 if (act_tbl[i].at_act == NULL)
564 timeout_act_error(lopt, o);
571 tstotv(struct timeval *tv, struct timespec *ts)
574 tv->tv_sec = ts->tv_sec;
575 tv->tv_usec = ts->tv_nsec / 1000;
580 * Convert a timeval to a number of ticks.
581 * Mostly copied from the kernel.
584 tvtohz(struct timeval *tv)
586 register unsigned long ticks;
587 register long sec, usec;
595 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
597 err(1, "sysctlbyname kern.hz");
602 * If the number of usecs in the whole seconds part of the time
603 * difference fits in a long, then the total number of usecs will
604 * fit in an unsigned long. Compute the total and convert it to
605 * ticks, rounding up and adding 1 to allow for the current tick
606 * to expire. Rounding also depends on unsigned long arithmetic
609 * Otherwise, if the number of ticks in the whole seconds part of
610 * the time difference fits in a long, then convert the parts to
611 * ticks separately and add, using similar rounding methods and
612 * overflow avoidance. This method would work in the previous
613 * case but it is slightly slower and assumes that hz is integral.
615 * Otherwise, round the time difference down to the maximum
616 * representable value.
618 * If ints have 32 bits, then the maximum value for any timeout in
619 * 10ms ticks is 248 days.
633 printf("tvotohz: negative time difference %ld sec %ld usec\n",
637 } else if (sec <= LONG_MAX / 1000000)
638 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
640 else if (sec <= LONG_MAX / hz)
642 + ((unsigned long)usec + (tick - 1)) / tick + 1;
651 seconds_to_pow2ns(int seconds)
658 errx(1, "seconds %d < 0", seconds);
659 ns = ((uint64_t)seconds) * 1000000000ULL;
661 shifted = 1ULL << power;
666 printf("shifted %lld\n", (long long)shifted);
667 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
668 seconds, (long long)ns, (int)power);
675 * Handle the few command line arguments supported.
678 parseargs(int argc, char *argv[])
685 /* Get the default value of timeout_sec from the default timeout. */
686 pow2ns_to_ts(timeout, &ts);
687 timeout_sec = ts.tv_sec;
690 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
691 * otherwise run as a command line utility.
694 if (argv[0][c - 1] == 'd')
698 getopt_shortopts = "I:de:ns:t:ST:wx:?";
700 getopt_shortopts = "dt:?";
702 while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
703 &longindex)) != -1) {
712 test_cmd = strdup(optarg);
723 nap = fetchtimeout(c, NULL, optarg, 0);
729 timeout_sec = atoi(optarg);
730 timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
732 printf("Timeout is 2^%d nanoseconds\n",
736 carp_thresh_seconds =
737 fetchtimeout(c, "NULL", optarg, 0);
743 exit_timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
744 if (exit_timeout != 0)
745 exit_timeout |= WD_ACTIVE;
748 lopt = longopts[longindex].name;
749 if (!strcmp(lopt, "pretimeout")) {
750 pretimeout = fetchtimeout(0, lopt, optarg, 0);
751 } else if (!strcmp(lopt, "pretimeout-action")) {
752 pretimeout_act = timeout_act_str2int(lopt,
754 } else if (!strcmp(lopt, "softtimeout-action")) {
755 softtimeout_act = timeout_act_str2int(lopt,
758 /* warnx("bad option at index %d: %s", optind,
771 if (nap > timeout_sec / 2)
772 nap = timeout_sec / 2;
774 if (carp_thresh_seconds == -1)
775 carp_thresh_seconds = nap;
778 errx(EX_USAGE, "extra arguments.");
779 if (is_daemon && timeout < WD_TO_1SEC)
780 errx(EX_USAGE, "-t argument is less than one second.");
781 if (pretimeout_set) {
782 if (pretimeout >= timeout_sec) {
784 "pretimeout (%d) >= timeout (%d -> %ld)\n"
785 "see manual section TIMEOUT RESOLUTION",
786 pretimeout, timeout_sec, (long)ts.tv_sec);