2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2003-2004 Sean M. Kelly <smkelly@FreeBSD.org>
5 * Copyright (c) 2013 iXsystems.com,
6 * author: Alfred Perlstein <alfred@freebsd.org>
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * Software watchdog daemon.
36 #include <sys/types.h>
37 __FBSDID("$FreeBSD$");
40 #include <sys/param.h>
41 #include <sys/rtprio.h>
44 #include <sys/sysctl.h>
45 #include <sys/watchdog.h>
65 static long fetchtimeout(int opt,
66 const char *longopt, const char *myoptarg, int zero_ok);
67 static void parseargs(int, char *[]);
68 static int seconds_to_pow2ns(int);
69 static void sighandler(int);
70 static void watchdog_loop(void);
71 static int watchdog_init(void);
72 static int watchdog_onoff(int onoff);
73 static int watchdog_patpat(u_int timeout);
74 static void usage(void);
75 static int tstotv(struct timeval *tv, struct timespec *ts);
76 static int tvtohz(struct timeval *tv);
78 static int debugging = 0;
79 static int end_program = 0;
80 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
81 static u_int timeout = WD_TO_128SEC;
82 static u_int exit_timeout = WD_TO_NEVER;
83 static u_int pretimeout = 0;
84 static u_int timeout_sec;
85 static u_int nap = 10;
86 static int passive = 0;
87 static int is_daemon = 0;
88 static int is_dry_run = 0; /* do not arm the watchdog, only
89 report on timing of the watch
91 static int do_timedog = 0;
92 static int do_syslog = 1;
94 static int carp_thresh_seconds = -1;
95 static char *test_cmd = NULL;
97 static const char *getopt_shortopts;
99 static int pretimeout_set;
100 static int pretimeout_act;
101 static int pretimeout_act_set;
103 static int softtimeout_set;
104 static int softtimeout_act;
105 static int softtimeout_act_set;
107 static struct option longopts[] = {
108 { "debug", no_argument, &debugging, 1 },
109 { "pretimeout", required_argument, &pretimeout_set, 1 },
110 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
111 { "softtimeout", no_argument, &softtimeout_set, 1 },
112 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
117 * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
118 * so that mlockall() won't needlessly wire megabytes of unused memory into the
119 * process. This must be done using the malloc_conf string so that it gets set
120 * up before the first allocation, which happens before entry to main().
122 const char * malloc_conf = "lg_chunk:0";
125 * Periodically pat the watchdog, preventing it from firing.
128 main(int argc, char *argv[])
135 errx(EX_SOFTWARE, "not super user");
137 parseargs(argc, argv);
140 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
143 rtp.type = RTP_PRIO_REALTIME;
145 if (rtprio(RTP_SET, 0, &rtp) == -1)
146 err(EX_OSERR, "rtprio");
148 if (!is_dry_run && watchdog_init() == -1)
149 errx(EX_SOFTWARE, "unable to initialize watchdog");
152 if (watchdog_onoff(1) == -1)
153 err(EX_OSERR, "patting the dog");
155 pfh = pidfile_open(pidfile, 0600, &otherpid);
157 if (errno == EEXIST) {
159 errx(EX_SOFTWARE, "%s already running, pid: %d",
160 getprogname(), otherpid);
162 warn("Cannot open or create pidfile");
165 if (debugging == 0 && daemon(0, 0) == -1) {
168 err(EX_OSERR, "daemon");
171 signal(SIGHUP, SIG_IGN);
172 signal(SIGINT, sighandler);
173 signal(SIGTERM, sighandler);
176 if (madvise(0, 0, MADV_PROTECT) != 0)
177 warn("madvise failed");
178 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
179 warn("mlockall failed");
188 timeout |= WD_PASSIVE;
190 timeout |= WD_ACTIVE;
191 if (watchdog_patpat(timeout) < 0)
192 err(EX_OSERR, "patting the dog");
198 pow2ns_to_ts(int pow2ns, struct timespec *ts)
203 ts->tv_sec = ns / 1000000000ULL;
204 ts->tv_nsec = ns % 1000000000ULL;
208 * Convert a timeout in seconds to N where 2^N nanoseconds is close to
211 * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
214 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
221 char shortopt[] = "- ";
226 a = fetchtimeout(opt, longopt, myoptarg, 1);
231 rv = seconds_to_pow2ns(a);
232 pow2ns_to_ts(rv, &ts);
236 printf("Timeout for %s%s "
237 "is 2^%d nanoseconds "
238 "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
239 longopt ? "-" : "", longopt ? longopt : shortopt,
241 myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
244 errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
251 * Catch signals and begin shutdown process.
254 sighandler(int signum)
257 if (signum == SIGINT || signum == SIGTERM)
262 * Open the watchdog device.
271 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
274 warn("Could not open watchdog device");
279 * If we are doing timing, then get the time.
282 watchdog_getuptime(struct timespec *tp)
289 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
291 warn("clock_gettime");
296 watchdog_check_dogfunction_time(struct timespec *tp_start,
297 struct timespec *tp_end)
299 struct timeval tv_start, tv_end, tv_now, tv;
300 const char *cmd_prefix, *cmd;
301 struct timespec tp_now;
307 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
308 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
309 timersub(&tv_end, &tv_start, &tv);
311 if (sec < carp_thresh_seconds)
315 cmd_prefix = "Watchdog program";
318 cmd_prefix = "Watchdog operation";
319 cmd = "stat(\"/etc\", &sb)";
322 syslog(LOG_CRIT, "%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);
327 warnx("%s: '%s' took too long: "
328 "%d.%06ld seconds >= %d seconds threshold",
329 cmd_prefix, cmd, sec, (long)tv.tv_usec,
330 carp_thresh_seconds);
333 * Adjust the sleep interval again in case syslog(3) took a non-trivial
334 * amount of time to run.
336 if (watchdog_getuptime(&tp_now))
338 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
339 timersub(&tv_now, &tv_start, &tv);
346 * Main program loop which is iterated every second.
351 struct timespec ts_start, ts_end;
356 while (end_program != 2) {
359 error = watchdog_getuptime(&ts_start);
365 if (test_cmd != NULL)
366 failed = system(test_cmd);
368 failed = stat("/etc", &sb);
370 error = watchdog_getuptime(&ts_end);
377 watchdog_patpat(timeout|WD_ACTIVE);
379 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
380 if (nap - waited > 0)
384 if (end_program != 0) {
385 if (watchdog_onoff(0) == 0) {
388 warnx("Could not stop the watchdog, not exiting");
396 * Reset the watchdog timer. This function must be called periodically
397 * to keep the watchdog from firing.
400 watchdog_patpat(u_int t)
406 return ioctl(fd, WDIOCPATPAT, &t);
410 * Toggle the kernel's watchdog. This routine is used to enable and
411 * disable the watchdog.
414 watchdog_onoff(int onoff)
418 /* fake successful watchdog op if a dry run */
424 * Call the WDIOC_SETSOFT regardless of softtimeout_set
425 * because we'll need to turn it off if someone had turned
428 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
430 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
433 error = watchdog_patpat((timeout|WD_ACTIVE));
435 warn("watchdog_patpat failed");
438 if (softtimeout_act_set) {
439 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
442 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
447 if (pretimeout_set) {
448 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
450 warn("setting WDIOC_SETPRETIMEOUT %d",
455 if (pretimeout_act_set) {
456 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
459 warn("setting WDIOC_SETPRETIMEOUTACT %d",
464 /* pat one more time for good measure */
465 return watchdog_patpat((timeout|WD_ACTIVE));
467 return watchdog_patpat(exit_timeout);
470 watchdog_patpat(exit_timeout);
475 * Tell user how to use the program.
481 fprintf(stderr, "usage:\n"
482 " watchdogd [-dnSw] [-e cmd] [-I pidfile] [-s sleep] [-t timeout]\n"
483 " [-T script_timeout] [-x exit_timeout]\n"
485 " [--pretimeout seconds] [-pretimeout-action action]\n"
486 " [--softtimeout] [-softtimeout-action action]\n"
489 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
494 fetchtimeout(int opt, const char *longopt, const char *myoptarg, int zero_ok)
503 rv = strtol(myoptarg, &p, 0);
504 if ((p != NULL && *p != '\0') || errno != 0)
505 errstr = "is not a number";
506 if (rv < 0 || (!zero_ok && rv == 0))
507 errstr = "must be greater than zero";
510 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
512 errx(EX_USAGE, "-%c argument %s", opt, errstr);
522 static const struct act_tbl act_tbl[] = {
523 { "panic", WD_SOFT_PANIC },
524 { "ddb", WD_SOFT_DDB },
525 { "log", WD_SOFT_LOG },
526 { "printf", WD_SOFT_PRINTF },
531 timeout_act_error(const char *lopt, const char *badact)
533 char *opts, *oldopts;
537 for (i = 0; act_tbl[i].at_act != NULL; i++) {
539 if (asprintf(&opts, "%s%s%s",
540 oldopts == NULL ? "" : oldopts,
541 oldopts == NULL ? "" : ", ",
542 act_tbl[i].at_act) == -1)
543 err(EX_OSERR, "malloc");
546 warnx("bad --%s argument '%s' must be one of (%s).",
552 * Take a comma separated list of actions and or the flags
553 * together for the ioctl.
556 timeout_act_str2int(const char *lopt, const char *acts)
559 char *dupacts, *tofree;
563 tofree = dupacts = strdup(acts);
565 err(EX_OSERR, "malloc");
566 while ((o = strsep(&dupacts, ",")) != NULL) {
567 for (i = 0; act_tbl[i].at_act != NULL; i++) {
568 if (!strcmp(o, act_tbl[i].at_act)) {
569 rv |= act_tbl[i].at_value;
573 if (act_tbl[i].at_act == NULL)
574 timeout_act_error(lopt, o);
581 tstotv(struct timeval *tv, struct timespec *ts)
584 tv->tv_sec = ts->tv_sec;
585 tv->tv_usec = ts->tv_nsec / 1000;
590 * Convert a timeval to a number of ticks.
591 * Mostly copied from the kernel.
594 tvtohz(struct timeval *tv)
596 register unsigned long ticks;
597 register long sec, usec;
605 error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
607 err(1, "sysctlbyname kern.hz");
612 * If the number of usecs in the whole seconds part of the time
613 * difference fits in a long, then the total number of usecs will
614 * fit in an unsigned long. Compute the total and convert it to
615 * ticks, rounding up and adding 1 to allow for the current tick
616 * to expire. Rounding also depends on unsigned long arithmetic
619 * Otherwise, if the number of ticks in the whole seconds part of
620 * the time difference fits in a long, then convert the parts to
621 * ticks separately and add, using similar rounding methods and
622 * overflow avoidance. This method would work in the previous
623 * case but it is slightly slower and assumes that hz is integral.
625 * Otherwise, round the time difference down to the maximum
626 * representable value.
628 * If ints have 32 bits, then the maximum value for any timeout in
629 * 10ms ticks is 248 days.
643 printf("tvotohz: negative time difference %ld sec %ld usec\n",
647 } else if (sec <= LONG_MAX / 1000000)
648 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
650 else if (sec <= LONG_MAX / hz)
652 + ((unsigned long)usec + (tick - 1)) / tick + 1;
661 seconds_to_pow2ns(int seconds)
668 errx(1, "seconds %d < 0", seconds);
669 ns = ((uint64_t)seconds) * 1000000000ULL;
671 shifted = 1ULL << power;
676 printf("shifted %lld\n", (long long)shifted);
677 printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
678 seconds, (long long)ns, (int)power);
685 * Handle the few command line arguments supported.
688 parseargs(int argc, char *argv[])
695 /* Get the default value of timeout_sec from the default timeout. */
696 pow2ns_to_ts(timeout, &ts);
697 timeout_sec = ts.tv_sec;
700 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
701 * otherwise run as a command line utility.
704 if (argv[0][c - 1] == 'd')
708 getopt_shortopts = "I:de:ns:t:ST:wx:?";
710 getopt_shortopts = "dt:?";
712 while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
713 &longindex)) != -1) {
722 test_cmd = strdup(optarg);
733 nap = fetchtimeout(c, NULL, optarg, 0);
739 timeout_sec = atoi(optarg);
740 timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
742 printf("Timeout is 2^%d nanoseconds\n",
746 carp_thresh_seconds =
747 fetchtimeout(c, "NULL", optarg, 0);
753 exit_timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
754 if (exit_timeout != 0)
755 exit_timeout |= WD_ACTIVE;
758 lopt = longopts[longindex].name;
759 if (!strcmp(lopt, "pretimeout")) {
760 pretimeout = fetchtimeout(0, lopt, optarg, 0);
761 } else if (!strcmp(lopt, "pretimeout-action")) {
762 pretimeout_act = timeout_act_str2int(lopt,
764 } else if (!strcmp(lopt, "softtimeout-action")) {
765 softtimeout_act = timeout_act_str2int(lopt,
768 /* warnx("bad option at index %d: %s", optind,
781 if (nap > timeout_sec / 2)
782 nap = timeout_sec / 2;
784 if (carp_thresh_seconds == -1)
785 carp_thresh_seconds = nap;
788 errx(EX_USAGE, "extra arguments.");
789 if (is_daemon && timeout < WD_TO_1SEC)
790 errx(EX_USAGE, "-t argument is less than one second.");
791 if (pretimeout_set) {
792 if (pretimeout >= timeout_sec) {
794 "pretimeout (%d) >= timeout (%d -> %ld)\n"
795 "see manual section TIMEOUT RESOLUTION",
796 pretimeout, timeout_sec, (long)ts.tv_sec);