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, const char *longopt, const char *myoptarg);
64 static void parseargs(int, char *[]);
65 static int seconds_to_pow2ns(int);
66 static void sighandler(int);
67 static void watchdog_loop(void);
68 static int watchdog_init(void);
69 static int watchdog_onoff(int onoff);
70 static int watchdog_patpat(u_int timeout);
71 static void usage(void);
72 static int tstotv(struct timeval *tv, struct timespec *ts);
73 static int tvtohz(struct timeval *tv);
75 static int debugging = 0;
76 static int end_program = 0;
77 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
78 static u_int timeout = WD_TO_128SEC;
79 static u_int pretimeout = 0;
80 static u_int timeout_sec;
81 static u_int passive = 0;
82 static int is_daemon = 0;
83 static int is_dry_run = 0; /* do not arm the watchdog, only
84 report on timing of the watch
86 static int do_timedog = 0;
87 static int do_syslog = 1;
90 static int carp_thresh_seconds = -1;
91 static char *test_cmd = NULL;
93 static const char *getopt_shortopts;
95 static int pretimeout_set;
96 static int pretimeout_act;
97 static int pretimeout_act_set;
99 static int softtimeout_set;
100 static int softtimeout_act;
101 static int softtimeout_act_set;
103 static struct option longopts[] = {
104 { "debug", no_argument, &debugging, 1 },
105 { "pretimeout", required_argument, &pretimeout_set, 1 },
106 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
107 { "softtimeout", no_argument, &softtimeout_set, 1 },
108 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
113 * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
114 * so that mlockall() won't needlessly wire megabytes of unused memory into the
115 * process. This must be done using the malloc_conf string so that it gets set
116 * up before the first allocation, which happens before entry to main().
118 const char * malloc_conf = "lg_chunk:0";
121 * Periodically pat the watchdog, preventing it from firing.
124 main(int argc, char *argv[])
131 errx(EX_SOFTWARE, "not super user");
133 parseargs(argc, argv);
136 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
139 rtp.type = RTP_PRIO_REALTIME;
141 if (rtprio(RTP_SET, 0, &rtp) == -1)
142 err(EX_OSERR, "rtprio");
144 if (!is_dry_run && watchdog_init() == -1)
145 errx(EX_SOFTWARE, "unable to initialize watchdog");
148 if (watchdog_onoff(1) == -1)
149 err(EX_OSERR, "patting the dog");
151 pfh = pidfile_open(pidfile, 0600, &otherpid);
153 if (errno == EEXIST) {
155 errx(EX_SOFTWARE, "%s already running, pid: %d",
156 getprogname(), otherpid);
158 warn("Cannot open or create pidfile");
161 if (debugging == 0 && daemon(0, 0) == -1) {
164 err(EX_OSERR, "daemon");
167 signal(SIGHUP, SIG_IGN);
168 signal(SIGINT, sighandler);
169 signal(SIGTERM, sighandler);
172 if (madvise(0, 0, MADV_PROTECT) != 0)
173 warn("madvise failed");
174 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
175 warn("mlockall failed");
184 timeout |= WD_PASSIVE;
186 timeout |= WD_ACTIVE;
187 if (watchdog_patpat(timeout) < 0)
188 err(EX_OSERR, "patting the dog");
194 pow2ns_to_ts(int pow2ns, struct timespec *ts)
199 ts->tv_sec = ns / 1000000000ULL;
200 ts->tv_nsec = ns % 1000000000ULL;
204 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
207 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
210 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
217 char shortopt[] = "- ";
222 a = fetchtimeout(opt, longopt, myoptarg);
227 rv = seconds_to_pow2ns(a);
228 pow2ns_to_ts(rv, &ts);
232 printf("Timeout for %s%s "
233 "is 2^%d nanoseconds "
234 "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
235 longopt ? "-" : "", longopt ? longopt : shortopt,
237 myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
240 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
247 * Catch signals and begin shutdown process.
250 sighandler(int signum)
253 if (signum == SIGINT || signum == SIGTERM)
258 * Open the watchdog device.
267 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
270 warn("Could not open watchdog device");
275 * If we are doing timing, then get the time.
278 watchdog_getuptime(struct timespec *tp)
285 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
287 warn("clock_gettime");
292 watchdog_check_dogfunction_time(struct timespec *tp_start,
293 struct timespec *tp_end)
295 struct timeval tv_start, tv_end, tv_now, tv;
296 const char *cmd_prefix, *cmd;
297 struct timespec tp_now;
303 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
304 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
305 timersub(&tv_end, &tv_start, &tv);
307 if (sec < carp_thresh_seconds)
311 cmd_prefix = "Watchdog program";
314 cmd_prefix = "Watchdog operation";
315 cmd = "stat(\"/etc\", &sb)";
318 syslog(LOG_CRIT, "%s: '%s' took too long: "
319 "%d.%06ld seconds >= %d seconds threshold",
320 cmd_prefix, cmd, sec, (long)tv.tv_usec,
321 carp_thresh_seconds);
323 warnx("%s: '%s' took too long: "
324 "%d.%06ld seconds >= %d seconds threshold",
325 cmd_prefix, cmd, sec, (long)tv.tv_usec,
326 carp_thresh_seconds);
329 * Adjust the sleep interval again in case syslog(3) took a non-trivial
330 * amount of time to run.
332 if (watchdog_getuptime(&tp_now))
334 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
335 timersub(&tv_now, &tv_start, &tv);
342 * Main program loop which is iterated every second.
347 struct timespec ts_start, ts_end;
352 while (end_program != 2) {
355 error = watchdog_getuptime(&ts_start);
361 if (test_cmd != NULL)
362 failed = system(test_cmd);
364 failed = stat("/etc", &sb);
366 error = watchdog_getuptime(&ts_end);
373 watchdog_patpat(timeout|WD_ACTIVE);
375 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
376 if (nap - waited > 0)
380 if (end_program != 0) {
381 if (watchdog_onoff(0) == 0) {
384 warnx("Could not stop the watchdog, not exiting");
392 * Reset the watchdog timer. This function must be called periodically
393 * to keep the watchdog from firing.
396 watchdog_patpat(u_int t)
402 return ioctl(fd, WDIOCPATPAT, &t);
406 * Toggle the kernel's watchdog. This routine is used to enable and
407 * disable the watchdog.
410 watchdog_onoff(int onoff)
414 /* fake successful watchdog op if a dry run */
420 * Call the WDIOC_SETSOFT regardless of softtimeout_set
421 * because we'll need to turn it off if someone had turned
424 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
426 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
429 error = watchdog_patpat((timeout|WD_ACTIVE));
431 warn("watchdog_patpat failed");
434 if (softtimeout_act_set) {
435 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
438 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
443 if (pretimeout_set) {
444 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
446 warn("setting WDIOC_SETPRETIMEOUT %d",
451 if (pretimeout_act_set) {
452 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
455 warn("setting WDIOC_SETPRETIMEOUTACT %d",
460 /* pat one more time for good measure */
461 return watchdog_patpat((timeout|WD_ACTIVE));
463 return watchdog_patpat(0);
471 * Tell user how to use the program.
477 fprintf(stderr, "usage:\n"
478 " watchdogd [-dnSw] [-e cmd] [-I file] [-s sleep] [-t timeout]\n"
479 " [-T script_timeout]\n"
481 " [--pretimeout seconds] [-pretimeout-action action]\n"
482 " [--softtimeout] [-softtimeout-action action]\n"
485 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
490 fetchtimeout(int opt, const char *longopt, const char *myoptarg)
499 rv = strtol(myoptarg, &p, 0);
500 if ((p != NULL && *p != '\0') || errno != 0)
501 errstr = "is not a number";
503 errstr = "must be greater than zero";
506 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
508 errx(EX_USAGE, "-%c argument %s", opt, errstr);
518 static const struct act_tbl act_tbl[] = {
519 { "panic", WD_SOFT_PANIC },
520 { "ddb", WD_SOFT_DDB },
521 { "log", WD_SOFT_LOG },
522 { "printf", WD_SOFT_PRINTF },
527 timeout_act_error(const char *lopt, const char *badact)
529 char *opts, *oldopts;
533 for (i = 0; act_tbl[i].at_act != NULL; i++) {
535 if (asprintf(&opts, "%s%s%s",
536 oldopts == NULL ? "" : oldopts,
537 oldopts == NULL ? "" : ", ",
538 act_tbl[i].at_act) == -1)
539 err(EX_OSERR, "malloc");
542 warnx("bad --%s argument '%s' must be one of (%s).",
548 * Take a comma separated list of actions and or the flags
549 * together for the ioctl.
552 timeout_act_str2int(const char *lopt, const char *acts)
555 char *dupacts, *tofree;
559 tofree = dupacts = strdup(acts);
561 err(EX_OSERR, "malloc");
562 while ((o = strsep(&dupacts, ",")) != NULL) {
563 for (i = 0; act_tbl[i].at_act != NULL; i++) {
564 if (!strcmp(o, act_tbl[i].at_act)) {
565 rv |= act_tbl[i].at_value;
569 if (act_tbl[i].at_act == NULL)
570 timeout_act_error(lopt, o);
577 tstotv(struct timeval *tv, struct timespec *ts)
580 tv->tv_sec = ts->tv_sec;
581 tv->tv_usec = ts->tv_nsec / 1000;
586 * Convert a timeval to a number of ticks.
587 * Mostly copied from the kernel.
590 tvtohz(struct timeval *tv)
592 register unsigned long ticks;
593 register long sec, usec;
601 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
603 err(1, "sysctlbyname kern.hz");
608 * If the number of usecs in the whole seconds part of the time
609 * difference fits in a long, then the total number of usecs will
610 * fit in an unsigned long. Compute the total and convert it to
611 * ticks, rounding up and adding 1 to allow for the current tick
612 * to expire. Rounding also depends on unsigned long arithmetic
615 * Otherwise, if the number of ticks in the whole seconds part of
616 * the time difference fits in a long, then convert the parts to
617 * ticks separately and add, using similar rounding methods and
618 * overflow avoidance. This method would work in the previous
619 * case but it is slightly slower and assumes that hz is integral.
621 * Otherwise, round the time difference down to the maximum
622 * representable value.
624 * If ints have 32 bits, then the maximum value for any timeout in
625 * 10ms ticks is 248 days.
639 printf("tvotohz: negative time difference %ld sec %ld usec\n",
643 } else if (sec <= LONG_MAX / 1000000)
644 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
646 else if (sec <= LONG_MAX / hz)
648 + ((unsigned long)usec + (tick - 1)) / tick + 1;
657 seconds_to_pow2ns(int seconds)
664 errx(1, "seconds %d < 0", seconds);
665 ns = ((uint64_t)seconds) * 1000000000ULL;
667 shifted = 1ULL << power;
672 printf("shifted %lld\n", (long long)shifted);
673 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
674 seconds, (long long)ns, (int)power);
681 * Handle the few command line arguments supported.
684 parseargs(int argc, char *argv[])
691 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
692 * otherwise run as a command line utility.
695 if (argv[0][c - 1] == 'd')
699 getopt_shortopts = "I:de:ns:t:ST:w?";
701 getopt_shortopts = "dt:?";
703 while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
704 &longindex)) != -1) {
713 test_cmd = strdup(optarg);
724 nap = fetchtimeout(c, NULL, optarg);
730 timeout_sec = atoi(optarg);
731 timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
733 printf("Timeout is 2^%d nanoseconds\n",
737 carp_thresh_seconds = fetchtimeout(c, "NULL", optarg);
743 lopt = longopts[longindex].name;
744 if (!strcmp(lopt, "pretimeout")) {
745 pretimeout = fetchtimeout(0, lopt, optarg);
746 } else if (!strcmp(lopt, "pretimeout-action")) {
747 pretimeout_act = timeout_act_str2int(lopt,
749 } else if (!strcmp(lopt, "softtimeout-action")) {
750 softtimeout_act = timeout_act_str2int(lopt,
753 /* warnx("bad option at index %d: %s", optind,
766 if (carp_thresh_seconds == -1)
767 carp_thresh_seconds = nap;
770 errx(EX_USAGE, "extra arguments.");
771 if (is_daemon && timeout < WD_TO_1SEC)
772 errx(EX_USAGE, "-t argument is less than one second.");
773 if (pretimeout_set) {
776 pow2ns_to_ts(timeout, &ts);
777 if (pretimeout >= (uintmax_t)ts.tv_sec) {
779 "pretimeout (%d) >= timeout (%d -> %ld)\n"
780 "see manual section TIMEOUT RESOLUTION",
781 pretimeout, timeout_sec, (long)ts.tv_sec);