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 pretimeout = 0;
81 static u_int timeout_sec;
82 static u_int passive = 0;
83 static int is_daemon = 0;
84 static int is_dry_run = 0; /* do not arm the watchdog, only
85 report on timing of the watch
87 static int do_timedog = 0;
88 static int do_syslog = 1;
91 static int carp_thresh_seconds = -1;
92 static char *test_cmd = NULL;
94 static const char *getopt_shortopts;
96 static int pretimeout_set;
97 static int pretimeout_act;
98 static int pretimeout_act_set;
100 static int softtimeout_set;
101 static int softtimeout_act;
102 static int softtimeout_act_set;
104 static struct option longopts[] = {
105 { "debug", no_argument, &debugging, 1 },
106 { "pretimeout", required_argument, &pretimeout_set, 1 },
107 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
108 { "softtimeout", no_argument, &softtimeout_set, 1 },
109 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
114 * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
115 * so that mlockall() won't needlessly wire megabytes of unused memory into the
116 * process. This must be done using the malloc_conf string so that it gets set
117 * up before the first allocation, which happens before entry to main().
119 const char * malloc_conf = "lg_chunk:0";
122 * Periodically pat the watchdog, preventing it from firing.
125 main(int argc, char *argv[])
132 errx(EX_SOFTWARE, "not super user");
134 parseargs(argc, argv);
137 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
140 rtp.type = RTP_PRIO_REALTIME;
142 if (rtprio(RTP_SET, 0, &rtp) == -1)
143 err(EX_OSERR, "rtprio");
145 if (!is_dry_run && watchdog_init() == -1)
146 errx(EX_SOFTWARE, "unable to initialize watchdog");
149 if (watchdog_onoff(1) == -1)
150 err(EX_OSERR, "patting the dog");
152 pfh = pidfile_open(pidfile, 0600, &otherpid);
154 if (errno == EEXIST) {
156 errx(EX_SOFTWARE, "%s already running, pid: %d",
157 getprogname(), otherpid);
159 warn("Cannot open or create pidfile");
162 if (debugging == 0 && daemon(0, 0) == -1) {
165 err(EX_OSERR, "daemon");
168 signal(SIGHUP, SIG_IGN);
169 signal(SIGINT, sighandler);
170 signal(SIGTERM, sighandler);
173 if (madvise(0, 0, MADV_PROTECT) != 0)
174 warn("madvise failed");
175 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
176 warn("mlockall failed");
185 timeout |= WD_PASSIVE;
187 timeout |= WD_ACTIVE;
188 if (watchdog_patpat(timeout) < 0)
189 err(EX_OSERR, "patting the dog");
195 pow2ns_to_ts(int pow2ns, struct timespec *ts)
200 ts->tv_sec = ns / 1000000000ULL;
201 ts->tv_nsec = ns % 1000000000ULL;
205 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
208 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
211 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
218 char shortopt[] = "- ";
223 a = fetchtimeout(opt, longopt, myoptarg, 1);
228 rv = seconds_to_pow2ns(a);
229 pow2ns_to_ts(rv, &ts);
233 printf("Timeout for %s%s "
234 "is 2^%d nanoseconds "
235 "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
236 longopt ? "-" : "", longopt ? longopt : shortopt,
238 myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
241 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
248 * Catch signals and begin shutdown process.
251 sighandler(int signum)
254 if (signum == SIGINT || signum == SIGTERM)
259 * Open the watchdog device.
268 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
271 warn("Could not open watchdog device");
276 * If we are doing timing, then get the time.
279 watchdog_getuptime(struct timespec *tp)
286 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
288 warn("clock_gettime");
293 watchdog_check_dogfunction_time(struct timespec *tp_start,
294 struct timespec *tp_end)
296 struct timeval tv_start, tv_end, tv_now, tv;
297 const char *cmd_prefix, *cmd;
298 struct timespec tp_now;
304 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
305 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
306 timersub(&tv_end, &tv_start, &tv);
308 if (sec < carp_thresh_seconds)
312 cmd_prefix = "Watchdog program";
315 cmd_prefix = "Watchdog operation";
316 cmd = "stat(\"/etc\", &sb)";
319 syslog(LOG_CRIT, "%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);
324 warnx("%s: '%s' took too long: "
325 "%d.%06ld seconds >= %d seconds threshold",
326 cmd_prefix, cmd, sec, (long)tv.tv_usec,
327 carp_thresh_seconds);
330 * Adjust the sleep interval again in case syslog(3) took a non-trivial
331 * amount of time to run.
333 if (watchdog_getuptime(&tp_now))
335 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
336 timersub(&tv_now, &tv_start, &tv);
343 * Main program loop which is iterated every second.
348 struct timespec ts_start, ts_end;
353 while (end_program != 2) {
356 error = watchdog_getuptime(&ts_start);
362 if (test_cmd != NULL)
363 failed = system(test_cmd);
365 failed = stat("/etc", &sb);
367 error = watchdog_getuptime(&ts_end);
374 watchdog_patpat(timeout|WD_ACTIVE);
376 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
377 if (nap - waited > 0)
381 if (end_program != 0) {
382 if (watchdog_onoff(0) == 0) {
385 warnx("Could not stop the watchdog, not exiting");
393 * Reset the watchdog timer. This function must be called periodically
394 * to keep the watchdog from firing.
397 watchdog_patpat(u_int t)
403 return ioctl(fd, WDIOCPATPAT, &t);
407 * Toggle the kernel's watchdog. This routine is used to enable and
408 * disable the watchdog.
411 watchdog_onoff(int onoff)
415 /* fake successful watchdog op if a dry run */
421 * Call the WDIOC_SETSOFT regardless of softtimeout_set
422 * because we'll need to turn it off if someone had turned
425 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
427 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
430 error = watchdog_patpat((timeout|WD_ACTIVE));
432 warn("watchdog_patpat failed");
435 if (softtimeout_act_set) {
436 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
439 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
444 if (pretimeout_set) {
445 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
447 warn("setting WDIOC_SETPRETIMEOUT %d",
452 if (pretimeout_act_set) {
453 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
456 warn("setting WDIOC_SETPRETIMEOUTACT %d",
461 /* pat one more time for good measure */
462 return watchdog_patpat((timeout|WD_ACTIVE));
464 return watchdog_patpat(0);
472 * Tell user how to use the program.
478 fprintf(stderr, "usage:\n"
479 " watchdogd [-dnSw] [-e cmd] [-I file] [-s sleep] [-t timeout]\n"
480 " [-T script_timeout]\n"
482 " [--pretimeout seconds] [-pretimeout-action action]\n"
483 " [--softtimeout] [-softtimeout-action action]\n"
486 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
491 fetchtimeout(int opt, const char *longopt, const char *myoptarg, int zero_ok)
500 rv = strtol(myoptarg, &p, 0);
501 if ((p != NULL && *p != '\0') || errno != 0)
502 errstr = "is not a number";
503 if (rv < 0 || (!zero_ok && rv == 0))
504 errstr = "must be greater than zero";
507 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
509 errx(EX_USAGE, "-%c argument %s", opt, errstr);
519 static const struct act_tbl act_tbl[] = {
520 { "panic", WD_SOFT_PANIC },
521 { "ddb", WD_SOFT_DDB },
522 { "log", WD_SOFT_LOG },
523 { "printf", WD_SOFT_PRINTF },
528 timeout_act_error(const char *lopt, const char *badact)
530 char *opts, *oldopts;
534 for (i = 0; act_tbl[i].at_act != NULL; i++) {
536 if (asprintf(&opts, "%s%s%s",
537 oldopts == NULL ? "" : oldopts,
538 oldopts == NULL ? "" : ", ",
539 act_tbl[i].at_act) == -1)
540 err(EX_OSERR, "malloc");
543 warnx("bad --%s argument '%s' must be one of (%s).",
549 * Take a comma separated list of actions and or the flags
550 * together for the ioctl.
553 timeout_act_str2int(const char *lopt, const char *acts)
556 char *dupacts, *tofree;
560 tofree = dupacts = strdup(acts);
562 err(EX_OSERR, "malloc");
563 while ((o = strsep(&dupacts, ",")) != NULL) {
564 for (i = 0; act_tbl[i].at_act != NULL; i++) {
565 if (!strcmp(o, act_tbl[i].at_act)) {
566 rv |= act_tbl[i].at_value;
570 if (act_tbl[i].at_act == NULL)
571 timeout_act_error(lopt, o);
578 tstotv(struct timeval *tv, struct timespec *ts)
581 tv->tv_sec = ts->tv_sec;
582 tv->tv_usec = ts->tv_nsec / 1000;
587 * Convert a timeval to a number of ticks.
588 * Mostly copied from the kernel.
591 tvtohz(struct timeval *tv)
593 register unsigned long ticks;
594 register long sec, usec;
602 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
604 err(1, "sysctlbyname kern.hz");
609 * If the number of usecs in the whole seconds part of the time
610 * difference fits in a long, then the total number of usecs will
611 * fit in an unsigned long. Compute the total and convert it to
612 * ticks, rounding up and adding 1 to allow for the current tick
613 * to expire. Rounding also depends on unsigned long arithmetic
616 * Otherwise, if the number of ticks in the whole seconds part of
617 * the time difference fits in a long, then convert the parts to
618 * ticks separately and add, using similar rounding methods and
619 * overflow avoidance. This method would work in the previous
620 * case but it is slightly slower and assumes that hz is integral.
622 * Otherwise, round the time difference down to the maximum
623 * representable value.
625 * If ints have 32 bits, then the maximum value for any timeout in
626 * 10ms ticks is 248 days.
640 printf("tvotohz: negative time difference %ld sec %ld usec\n",
644 } else if (sec <= LONG_MAX / 1000000)
645 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
647 else if (sec <= LONG_MAX / hz)
649 + ((unsigned long)usec + (tick - 1)) / tick + 1;
658 seconds_to_pow2ns(int seconds)
665 errx(1, "seconds %d < 0", seconds);
666 ns = ((uint64_t)seconds) * 1000000000ULL;
668 shifted = 1ULL << power;
673 printf("shifted %lld\n", (long long)shifted);
674 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
675 seconds, (long long)ns, (int)power);
682 * Handle the few command line arguments supported.
685 parseargs(int argc, char *argv[])
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:w?";
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 lopt = longopts[longindex].name;
746 if (!strcmp(lopt, "pretimeout")) {
747 pretimeout = fetchtimeout(0, lopt, optarg, 0);
748 } else if (!strcmp(lopt, "pretimeout-action")) {
749 pretimeout_act = timeout_act_str2int(lopt,
751 } else if (!strcmp(lopt, "softtimeout-action")) {
752 softtimeout_act = timeout_act_str2int(lopt,
755 /* warnx("bad option at index %d: %s", optind,
768 if (carp_thresh_seconds == -1)
769 carp_thresh_seconds = nap;
772 errx(EX_USAGE, "extra arguments.");
773 if (is_daemon && timeout < WD_TO_1SEC)
774 errx(EX_USAGE, "-t argument is less than one second.");
775 if (pretimeout_set) {
778 pow2ns_to_ts(timeout, &ts);
779 if (pretimeout >= (uintmax_t)ts.tv_sec) {
781 "pretimeout (%d) >= timeout (%d -> %ld)\n"
782 "see manual section TIMEOUT RESOLUTION",
783 pretimeout, timeout_sec, (long)ts.tv_sec);