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 * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
116 * so that mlockall() won't needlessly wire megabytes of unused memory into the
117 * process. This must be done using the malloc_conf string so that it gets set
118 * up before the first allocation, which happens before entry to main().
120 const char * malloc_conf = "lg_chunk:0";
123 * Periodically pat the watchdog, preventing it from firing.
126 main(int argc, char *argv[])
133 errx(EX_SOFTWARE, "not super user");
135 parseargs(argc, argv);
138 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
141 rtp.type = RTP_PRIO_REALTIME;
143 if (rtprio(RTP_SET, 0, &rtp) == -1)
144 err(EX_OSERR, "rtprio");
146 if (!is_dry_run && watchdog_init() == -1)
147 errx(EX_SOFTWARE, "unable to initialize watchdog");
150 if (watchdog_onoff(1) == -1)
151 err(EX_OSERR, "patting the dog");
153 pfh = pidfile_open(pidfile, 0600, &otherpid);
155 if (errno == EEXIST) {
157 errx(EX_SOFTWARE, "%s already running, pid: %d",
158 getprogname(), otherpid);
160 warn("Cannot open or create pidfile");
163 if (debugging == 0 && daemon(0, 0) == -1) {
166 err(EX_OSERR, "daemon");
169 signal(SIGHUP, SIG_IGN);
170 signal(SIGINT, sighandler);
171 signal(SIGTERM, sighandler);
174 if (madvise(0, 0, MADV_PROTECT) != 0)
175 warn("madvise failed");
176 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
177 warn("mlockall failed");
186 timeout |= WD_PASSIVE;
188 timeout |= WD_ACTIVE;
189 if (watchdog_patpat(timeout) < 0)
190 err(EX_OSERR, "patting the dog");
196 pow2ns_to_ts(int pow2ns, struct timespec *ts)
201 ts->tv_sec = ns / 1000000000ULL;
202 ts->tv_nsec = ns % 1000000000ULL;
206 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
209 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
212 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
219 char shortopt[] = "- ";
224 a = fetchtimeout(opt, longopt, myoptarg, 1);
229 rv = seconds_to_pow2ns(a);
230 pow2ns_to_ts(rv, &ts);
234 printf("Timeout for %s%s "
235 "is 2^%d nanoseconds "
236 "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
237 longopt ? "-" : "", longopt ? longopt : shortopt,
239 myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
242 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
249 * Catch signals and begin shutdown process.
252 sighandler(int signum)
255 if (signum == SIGINT || signum == SIGTERM)
260 * Open the watchdog device.
269 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
272 warn("Could not open watchdog device");
277 * If we are doing timing, then get the time.
280 watchdog_getuptime(struct timespec *tp)
287 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
289 warn("clock_gettime");
294 watchdog_check_dogfunction_time(struct timespec *tp_start,
295 struct timespec *tp_end)
297 struct timeval tv_start, tv_end, tv_now, tv;
298 const char *cmd_prefix, *cmd;
299 struct timespec tp_now;
305 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
306 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
307 timersub(&tv_end, &tv_start, &tv);
309 if (sec < carp_thresh_seconds)
313 cmd_prefix = "Watchdog program";
316 cmd_prefix = "Watchdog operation";
317 cmd = "stat(\"/etc\", &sb)";
320 syslog(LOG_CRIT, "%s: '%s' took too long: "
321 "%d.%06ld seconds >= %d seconds threshold",
322 cmd_prefix, cmd, sec, (long)tv.tv_usec,
323 carp_thresh_seconds);
325 warnx("%s: '%s' took too long: "
326 "%d.%06ld seconds >= %d seconds threshold",
327 cmd_prefix, cmd, sec, (long)tv.tv_usec,
328 carp_thresh_seconds);
331 * Adjust the sleep interval again in case syslog(3) took a non-trivial
332 * amount of time to run.
334 if (watchdog_getuptime(&tp_now))
336 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
337 timersub(&tv_now, &tv_start, &tv);
344 * Main program loop which is iterated every second.
349 struct timespec ts_start, ts_end;
354 while (end_program != 2) {
357 error = watchdog_getuptime(&ts_start);
363 if (test_cmd != NULL)
364 failed = system(test_cmd);
366 failed = stat("/etc", &sb);
368 error = watchdog_getuptime(&ts_end);
375 watchdog_patpat(timeout|WD_ACTIVE);
377 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
378 if (nap - waited > 0)
382 if (end_program != 0) {
383 if (watchdog_onoff(0) == 0) {
386 warnx("Could not stop the watchdog, not exiting");
394 * Reset the watchdog timer. This function must be called periodically
395 * to keep the watchdog from firing.
398 watchdog_patpat(u_int t)
404 return ioctl(fd, WDIOCPATPAT, &t);
408 * Toggle the kernel's watchdog. This routine is used to enable and
409 * disable the watchdog.
412 watchdog_onoff(int onoff)
416 /* fake successful watchdog op if a dry run */
422 * Call the WDIOC_SETSOFT regardless of softtimeout_set
423 * because we'll need to turn it off if someone had turned
426 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
428 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
431 error = watchdog_patpat((timeout|WD_ACTIVE));
433 warn("watchdog_patpat failed");
436 if (softtimeout_act_set) {
437 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
440 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
445 if (pretimeout_set) {
446 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
448 warn("setting WDIOC_SETPRETIMEOUT %d",
453 if (pretimeout_act_set) {
454 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
457 warn("setting WDIOC_SETPRETIMEOUTACT %d",
462 /* pat one more time for good measure */
463 return watchdog_patpat((timeout|WD_ACTIVE));
465 return watchdog_patpat(exit_timeout);
468 watchdog_patpat(exit_timeout);
473 * Tell user how to use the program.
479 fprintf(stderr, "usage:\n"
480 " watchdogd [-dnSw] [-e cmd] [-I pidfile] [-s sleep] [-t timeout]\n"
481 " [-T script_timeout] [-x exit_timeout]\n"
483 " [--pretimeout seconds] [-pretimeout-action action]\n"
484 " [--softtimeout] [-softtimeout-action action]\n"
487 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
492 fetchtimeout(int opt, const char *longopt, const char *myoptarg, int zero_ok)
501 rv = strtol(myoptarg, &p, 0);
502 if ((p != NULL && *p != '\0') || errno != 0)
503 errstr = "is not a number";
504 if (rv < 0 || (!zero_ok && rv == 0))
505 errstr = "must be greater than zero";
508 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
510 errx(EX_USAGE, "-%c argument %s", opt, errstr);
520 static const struct act_tbl act_tbl[] = {
521 { "panic", WD_SOFT_PANIC },
522 { "ddb", WD_SOFT_DDB },
523 { "log", WD_SOFT_LOG },
524 { "printf", WD_SOFT_PRINTF },
529 timeout_act_error(const char *lopt, const char *badact)
531 char *opts, *oldopts;
535 for (i = 0; act_tbl[i].at_act != NULL; i++) {
537 if (asprintf(&opts, "%s%s%s",
538 oldopts == NULL ? "" : oldopts,
539 oldopts == NULL ? "" : ", ",
540 act_tbl[i].at_act) == -1)
541 err(EX_OSERR, "malloc");
544 warnx("bad --%s argument '%s' must be one of (%s).",
550 * Take a comma separated list of actions and or the flags
551 * together for the ioctl.
554 timeout_act_str2int(const char *lopt, const char *acts)
557 char *dupacts, *tofree;
561 tofree = dupacts = strdup(acts);
563 err(EX_OSERR, "malloc");
564 while ((o = strsep(&dupacts, ",")) != NULL) {
565 for (i = 0; act_tbl[i].at_act != NULL; i++) {
566 if (!strcmp(o, act_tbl[i].at_act)) {
567 rv |= act_tbl[i].at_value;
571 if (act_tbl[i].at_act == NULL)
572 timeout_act_error(lopt, o);
579 tstotv(struct timeval *tv, struct timespec *ts)
582 tv->tv_sec = ts->tv_sec;
583 tv->tv_usec = ts->tv_nsec / 1000;
588 * Convert a timeval to a number of ticks.
589 * Mostly copied from the kernel.
592 tvtohz(struct timeval *tv)
594 register unsigned long ticks;
595 register long sec, usec;
603 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
605 err(1, "sysctlbyname kern.hz");
610 * If the number of usecs in the whole seconds part of the time
611 * difference fits in a long, then the total number of usecs will
612 * fit in an unsigned long. Compute the total and convert it to
613 * ticks, rounding up and adding 1 to allow for the current tick
614 * to expire. Rounding also depends on unsigned long arithmetic
617 * Otherwise, if the number of ticks in the whole seconds part of
618 * the time difference fits in a long, then convert the parts to
619 * ticks separately and add, using similar rounding methods and
620 * overflow avoidance. This method would work in the previous
621 * case but it is slightly slower and assumes that hz is integral.
623 * Otherwise, round the time difference down to the maximum
624 * representable value.
626 * If ints have 32 bits, then the maximum value for any timeout in
627 * 10ms ticks is 248 days.
641 printf("tvotohz: negative time difference %ld sec %ld usec\n",
645 } else if (sec <= LONG_MAX / 1000000)
646 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
648 else if (sec <= LONG_MAX / hz)
650 + ((unsigned long)usec + (tick - 1)) / tick + 1;
659 seconds_to_pow2ns(int seconds)
666 errx(1, "seconds %d < 0", seconds);
667 ns = ((uint64_t)seconds) * 1000000000ULL;
669 shifted = 1ULL << power;
674 printf("shifted %lld\n", (long long)shifted);
675 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
676 seconds, (long long)ns, (int)power);
683 * Handle the few command line arguments supported.
686 parseargs(int argc, char *argv[])
693 /* Get the default value of timeout_sec from the default timeout. */
694 pow2ns_to_ts(timeout, &ts);
695 timeout_sec = ts.tv_sec;
698 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
699 * otherwise run as a command line utility.
702 if (argv[0][c - 1] == 'd')
706 getopt_shortopts = "I:de:ns:t:ST:wx:?";
708 getopt_shortopts = "dt:?";
710 while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
711 &longindex)) != -1) {
720 test_cmd = strdup(optarg);
731 nap = fetchtimeout(c, NULL, optarg, 0);
737 timeout_sec = atoi(optarg);
738 timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
740 printf("Timeout is 2^%d nanoseconds\n",
744 carp_thresh_seconds =
745 fetchtimeout(c, "NULL", optarg, 0);
751 exit_timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
752 if (exit_timeout != 0)
753 exit_timeout |= WD_ACTIVE;
756 lopt = longopts[longindex].name;
757 if (!strcmp(lopt, "pretimeout")) {
758 pretimeout = fetchtimeout(0, lopt, optarg, 0);
759 } else if (!strcmp(lopt, "pretimeout-action")) {
760 pretimeout_act = timeout_act_str2int(lopt,
762 } else if (!strcmp(lopt, "softtimeout-action")) {
763 softtimeout_act = timeout_act_str2int(lopt,
766 /* warnx("bad option at index %d: %s", optind,
779 if (nap > timeout_sec / 2)
780 nap = timeout_sec / 2;
782 if (carp_thresh_seconds == -1)
783 carp_thresh_seconds = nap;
786 errx(EX_USAGE, "extra arguments.");
787 if (is_daemon && timeout < WD_TO_1SEC)
788 errx(EX_USAGE, "-t argument is less than one second.");
789 if (pretimeout_set) {
790 if (pretimeout >= timeout_sec) {
792 "pretimeout (%d) >= timeout (%d -> %ld)\n"
793 "see manual section TIMEOUT RESOLUTION",
794 pretimeout, timeout_sec, (long)ts.tv_sec);