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>
62 static long fetchtimeout(int opt, const char *longopt, const char *myoptarg);
63 static void parseargs(int, char *[]);
64 static int seconds_to_pow2ns(int);
65 static void sighandler(int);
66 static void watchdog_loop(void);
67 static int watchdog_init(void);
68 static int watchdog_onoff(int onoff);
69 static int watchdog_patpat(u_int timeout);
70 static void usage(void);
71 static int tstotv(struct timeval *tv, struct timespec *ts);
72 static int tvtohz(struct timeval *tv);
74 static int debugging = 0;
75 static int end_program = 0;
76 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
77 static u_int timeout = WD_TO_128SEC;
78 static u_int pretimeout = 0;
79 static u_int timeout_sec;
80 static u_int passive = 0;
81 static int is_daemon = 0;
82 static int is_dry_run = 0; /* do not arm the watchdog, only
83 report on timing of the watch
85 static int do_timedog = 0;
86 static int do_syslog = 1;
89 static int carp_thresh_seconds = -1;
90 static char *test_cmd = NULL;
92 static const char *getopt_shortopts;
94 static int pretimeout_set;
95 static int pretimeout_act;
96 static int pretimeout_act_set;
98 static int softtimeout_set;
99 static int softtimeout_act;
100 static int softtimeout_act_set;
102 static struct option longopts[] = {
103 { "debug", no_argument, &debugging, 1 },
104 { "pretimeout", required_argument, &pretimeout_set, 1 },
105 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
106 { "softtimeout", no_argument, &softtimeout_set, 1 },
107 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
112 * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
113 * so that mlockall() won't needlessly wire megabytes of unused memory into the
114 * process. This must be done using the malloc_conf string so that it gets set
115 * up before the first allocation, which happens before entry to main().
117 const char * malloc_conf = "lg_chunk:0";
120 * Periodically pat the watchdog, preventing it from firing.
123 main(int argc, char *argv[])
130 errx(EX_SOFTWARE, "not super user");
132 parseargs(argc, argv);
135 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
138 rtp.type = RTP_PRIO_REALTIME;
140 if (rtprio(RTP_SET, 0, &rtp) == -1)
141 err(EX_OSERR, "rtprio");
143 if (!is_dry_run && watchdog_init() == -1)
144 errx(EX_SOFTWARE, "unable to initialize watchdog");
147 if (watchdog_onoff(1) == -1)
148 err(EX_OSERR, "patting the dog");
150 pfh = pidfile_open(pidfile, 0600, &otherpid);
152 if (errno == EEXIST) {
154 errx(EX_SOFTWARE, "%s already running, pid: %d",
155 getprogname(), otherpid);
157 warn("Cannot open or create pidfile");
160 if (debugging == 0 && daemon(0, 0) == -1) {
163 err(EX_OSERR, "daemon");
166 signal(SIGHUP, SIG_IGN);
167 signal(SIGINT, sighandler);
168 signal(SIGTERM, sighandler);
171 if (madvise(0, 0, MADV_PROTECT) != 0)
172 warn("madvise failed");
173 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
174 warn("mlockall failed");
183 timeout |= WD_PASSIVE;
185 timeout |= WD_ACTIVE;
186 if (watchdog_patpat(timeout) < 0)
187 err(EX_OSERR, "patting the dog");
193 pow2ns_to_ts(int pow2ns, struct timespec *ts)
198 ts->tv_sec = ns / 1000000000ULL;
199 ts->tv_nsec = ns % 1000000000ULL;
203 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
206 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
209 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
216 char shortopt[] = "- ";
221 a = fetchtimeout(opt, longopt, myoptarg);
226 rv = seconds_to_pow2ns(a);
227 pow2ns_to_ts(rv, &ts);
231 printf("Timeout for %s%s "
232 "is 2^%d nanoseconds "
233 "(in: %s sec -> out: %ld sec %ld ns -> %d ticks)\n",
234 longopt ? "-" : "", longopt ? longopt : shortopt,
236 myoptarg, ts.tv_sec, ts.tv_nsec, ticks);
239 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
246 * Catch signals and begin shutdown process.
249 sighandler(int signum)
252 if (signum == SIGINT || signum == SIGTERM)
257 * Open the watchdog device.
266 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
269 warn("Could not open watchdog device");
274 * If we are doing timing, then get the time.
277 watchdog_getuptime(struct timespec *tp)
284 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
286 warn("clock_gettime");
291 watchdog_check_dogfunction_time(struct timespec *tp_start,
292 struct timespec *tp_end)
294 struct timeval tv_start, tv_end, tv_now, tv;
295 const char *cmd_prefix, *cmd;
296 struct timespec tp_now;
302 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
303 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
304 timersub(&tv_end, &tv_start, &tv);
306 if (sec < carp_thresh_seconds)
310 cmd_prefix = "Watchdog program";
313 cmd_prefix = "Watchdog operation";
314 cmd = "stat(\"/etc\", &sb)";
317 syslog(LOG_CRIT, "%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);
322 warnx("%s: '%s' took too long: "
323 "%d.%06ld seconds >= %d seconds threshold",
324 cmd_prefix, cmd, sec, (long)tv.tv_usec,
325 carp_thresh_seconds);
328 * Adjust the sleep interval again in case syslog(3) took a non-trivial
329 * amount of time to run.
331 if (watchdog_getuptime(&tp_now))
333 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
334 timersub(&tv_now, &tv_start, &tv);
341 * Main program loop which is iterated every second.
346 struct timespec ts_start, ts_end;
351 while (end_program != 2) {
354 error = watchdog_getuptime(&ts_start);
360 if (test_cmd != NULL)
361 failed = system(test_cmd);
363 failed = stat("/etc", &sb);
365 error = watchdog_getuptime(&ts_end);
372 watchdog_patpat(timeout|WD_ACTIVE);
374 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
375 if (nap - waited > 0)
379 if (end_program != 0) {
380 if (watchdog_onoff(0) == 0) {
383 warnx("Could not stop the watchdog, not exiting");
391 * Reset the watchdog timer. This function must be called periodically
392 * to keep the watchdog from firing.
395 watchdog_patpat(u_int t)
401 return ioctl(fd, WDIOCPATPAT, &t);
405 * Toggle the kernel's watchdog. This routine is used to enable and
406 * disable the watchdog.
409 watchdog_onoff(int onoff)
413 /* fake successful watchdog op if a dry run */
419 * Call the WDIOC_SETSOFT regardless of softtimeout_set
420 * because we'll need to turn it off if someone had turned
423 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
425 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
428 error = watchdog_patpat((timeout|WD_ACTIVE));
430 warn("watchdog_patpat failed");
433 if (softtimeout_act_set) {
434 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
437 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
442 if (pretimeout_set) {
443 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
445 warn("setting WDIOC_SETPRETIMEOUT %d",
450 if (pretimeout_act_set) {
451 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
454 warn("setting WDIOC_SETPRETIMEOUTACT %d",
459 /* pat one more time for good measure */
460 return watchdog_patpat((timeout|WD_ACTIVE));
462 return watchdog_patpat(0);
470 * Tell user how to use the program.
476 fprintf(stderr, "usage:\n"
477 " watchdogd [-dnSw] [-e cmd] [-I file] [-s sleep] [-t timeout]\n"
478 " [-T script_timeout]\n"
480 " [--pretimeout seconds] [-pretimeout-action action]\n"
481 " [--softtimeout] [-softtimeout-action action]\n"
484 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
489 fetchtimeout(int opt, const char *longopt, const char *myoptarg)
498 rv = strtol(myoptarg, &p, 0);
499 if ((p != NULL && *p != '\0') || errno != 0)
500 errstr = "is not a number";
502 errstr = "must be greater than zero";
505 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
507 errx(EX_USAGE, "-%c argument %s", opt, errstr);
517 static const struct act_tbl act_tbl[] = {
518 { "panic", WD_SOFT_PANIC },
519 { "ddb", WD_SOFT_DDB },
520 { "log", WD_SOFT_LOG },
521 { "printf", WD_SOFT_PRINTF },
526 timeout_act_error(const char *lopt, const char *badact)
528 char *opts, *oldopts;
532 for (i = 0; act_tbl[i].at_act != NULL; i++) {
534 if (asprintf(&opts, "%s%s%s",
535 oldopts == NULL ? "" : oldopts,
536 oldopts == NULL ? "" : ", ",
537 act_tbl[i].at_act) == -1)
538 err(EX_OSERR, "malloc");
541 warnx("bad --%s argument '%s' must be one of (%s).",
547 * Take a comma separated list of actions and or the flags
548 * together for the ioctl.
551 timeout_act_str2int(const char *lopt, const char *acts)
554 char *dupacts, *tofree;
558 tofree = dupacts = strdup(acts);
560 err(EX_OSERR, "malloc");
561 while ((o = strsep(&dupacts, ",")) != NULL) {
562 for (i = 0; act_tbl[i].at_act != NULL; i++) {
563 if (!strcmp(o, act_tbl[i].at_act)) {
564 rv |= act_tbl[i].at_value;
568 if (act_tbl[i].at_act == NULL)
569 timeout_act_error(lopt, o);
576 tstotv(struct timeval *tv, struct timespec *ts)
579 tv->tv_sec = ts->tv_sec;
580 tv->tv_usec = ts->tv_nsec / 1000;
585 * Convert a timeval to a number of ticks.
586 * Mostly copied from the kernel.
589 tvtohz(struct timeval *tv)
591 register unsigned long ticks;
592 register long sec, usec;
600 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
602 err(1, "sysctlbyname kern.hz");
607 * If the number of usecs in the whole seconds part of the time
608 * difference fits in a long, then the total number of usecs will
609 * fit in an unsigned long. Compute the total and convert it to
610 * ticks, rounding up and adding 1 to allow for the current tick
611 * to expire. Rounding also depends on unsigned long arithmetic
614 * Otherwise, if the number of ticks in the whole seconds part of
615 * the time difference fits in a long, then convert the parts to
616 * ticks separately and add, using similar rounding methods and
617 * overflow avoidance. This method would work in the previous
618 * case but it is slightly slower and assumes that hz is integral.
620 * Otherwise, round the time difference down to the maximum
621 * representable value.
623 * If ints have 32 bits, then the maximum value for any timeout in
624 * 10ms ticks is 248 days.
638 printf("tvotohz: negative time difference %ld sec %ld usec\n",
642 } else if (sec <= LONG_MAX / 1000000)
643 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
645 else if (sec <= LONG_MAX / hz)
647 + ((unsigned long)usec + (tick - 1)) / tick + 1;
656 seconds_to_pow2ns(int seconds)
663 errx(1, "seconds %d < 0", seconds);
664 ns = ((uint64_t)seconds) * 1000000000ULL;
666 shifted = 1ULL << power;
671 printf("shifted %lld\n", (long long)shifted);
672 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
673 seconds, (long long)ns, (int)power);
680 * Handle the few command line arguments supported.
683 parseargs(int argc, char *argv[])
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:w?";
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);
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 = fetchtimeout(c, "NULL", optarg);
742 lopt = longopts[longindex].name;
743 if (!strcmp(lopt, "pretimeout")) {
744 pretimeout = fetchtimeout(0, lopt, optarg);
745 } else if (!strcmp(lopt, "pretimeout-action")) {
746 pretimeout_act = timeout_act_str2int(lopt,
748 } else if (!strcmp(lopt, "softtimeout-action")) {
749 softtimeout_act = timeout_act_str2int(lopt,
752 /* warnx("bad option at index %d: %s", optind,
765 if (carp_thresh_seconds == -1)
766 carp_thresh_seconds = nap;
769 errx(EX_USAGE, "extra arguments.");
770 if (is_daemon && timeout < WD_TO_1SEC)
771 errx(EX_USAGE, "-t argument is less than one second.");
772 if (pretimeout_set) {
775 pow2ns_to_ts(timeout, &ts);
776 if (pretimeout >= ts.tv_sec) {
778 "pretimeout (%d) >= timeout (%d -> %ld)\n"
779 "see manual section TIMEOUT RESOLUTION",
780 pretimeout, timeout_sec, (long)ts.tv_sec);