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/watchdog.h>
61 static void parseargs(int, char *[]);
62 static void sighandler(int);
63 static void watchdog_loop(void);
64 static int watchdog_init(void);
65 static int watchdog_onoff(int onoff);
66 static int watchdog_patpat(u_int timeout);
67 static void usage(void);
69 static int debugging = 0;
70 static int end_program = 0;
71 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
72 static u_int timeout = WD_TO_128SEC;
73 static u_int pretimeout = 0;
74 static u_int passive = 0;
75 static int is_daemon = 0;
76 static int is_dry_run = 0; /* do not arm the watchdog, only
77 report on timing of the watch
79 static int do_timedog = 0;
80 static int do_syslog = 1;
83 static int carp_thresh_seconds = -1;
84 static char *test_cmd = NULL;
86 static const char *getopt_shortopts;
88 static int pretimeout_set;
89 static int pretimeout_act;
90 static int pretimeout_act_set;
92 static int softtimeout_set;
93 static int softtimeout_act;
94 static int softtimeout_act_set;
96 static struct option longopts[] = {
97 { "debug", no_argument, &debugging, 1 },
98 { "pretimeout", required_argument, &pretimeout_set, 1 },
99 { "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
100 { "softtimeout", no_argument, &softtimeout_set, 1 },
101 { "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
106 * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
107 * so that mlockall() won't needlessly wire megabytes of unused memory into the
108 * process. This must be done using the malloc_conf string so that it gets set
109 * up before the first allocation, which happens before entry to main().
111 const char * malloc_conf = "lg_chunk:0";
114 * Periodically pat the watchdog, preventing it from firing.
117 main(int argc, char *argv[])
124 errx(EX_SOFTWARE, "not super user");
126 parseargs(argc, argv);
129 openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
132 rtp.type = RTP_PRIO_REALTIME;
134 if (rtprio(RTP_SET, 0, &rtp) == -1)
135 err(EX_OSERR, "rtprio");
137 if (!is_dry_run && watchdog_init() == -1)
138 errx(EX_SOFTWARE, "unable to initialize watchdog");
141 if (watchdog_onoff(1) == -1)
142 err(EX_OSERR, "patting the dog");
144 pfh = pidfile_open(pidfile, 0600, &otherpid);
146 if (errno == EEXIST) {
148 errx(EX_SOFTWARE, "%s already running, pid: %d",
149 getprogname(), otherpid);
151 warn("Cannot open or create pidfile");
154 if (debugging == 0 && daemon(0, 0) == -1) {
157 err(EX_OSERR, "daemon");
160 signal(SIGHUP, SIG_IGN);
161 signal(SIGINT, sighandler);
162 signal(SIGTERM, sighandler);
165 if (madvise(0, 0, MADV_PROTECT) != 0)
166 warn("madvise failed");
167 if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
168 warn("mlockall failed");
177 timeout |= WD_PASSIVE;
179 timeout |= WD_ACTIVE;
180 if (watchdog_patpat(timeout) < 0)
181 err(EX_OSERR, "patting the dog");
187 * Catch signals and begin shutdown process.
190 sighandler(int signum)
193 if (signum == SIGINT || signum == SIGTERM)
198 * Open the watchdog device.
207 fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
210 warn("Could not open watchdog device");
215 * If we are doing timing, then get the time.
218 watchdog_getuptime(struct timespec *tp)
225 error = clock_gettime(CLOCK_UPTIME_FAST, tp);
227 warn("clock_gettime");
232 watchdog_check_dogfunction_time(struct timespec *tp_start,
233 struct timespec *tp_end)
235 struct timeval tv_start, tv_end, tv_now, tv;
236 const char *cmd_prefix, *cmd;
237 struct timespec tp_now;
243 TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
244 TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
245 timersub(&tv_end, &tv_start, &tv);
247 if (sec < carp_thresh_seconds)
251 cmd_prefix = "Watchdog program";
254 cmd_prefix = "Watchdog operation";
255 cmd = "stat(\"/etc\", &sb)";
258 syslog(LOG_CRIT, "%s: '%s' took too long: "
259 "%d.%06ld seconds >= %d seconds threshold",
260 cmd_prefix, cmd, sec, (long)tv.tv_usec,
261 carp_thresh_seconds);
263 warnx("%s: '%s' took too long: "
264 "%d.%06ld seconds >= %d seconds threshold",
265 cmd_prefix, cmd, sec, (long)tv.tv_usec,
266 carp_thresh_seconds);
269 * Adjust the sleep interval again in case syslog(3) took a non-trivial
270 * amount of time to run.
272 if (watchdog_getuptime(&tp_now))
274 TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
275 timersub(&tv_now, &tv_start, &tv);
282 * Main program loop which is iterated every second.
287 struct timespec ts_start, ts_end;
292 while (end_program != 2) {
295 error = watchdog_getuptime(&ts_start);
301 if (test_cmd != NULL)
302 failed = system(test_cmd);
304 failed = stat("/etc", &sb);
306 error = watchdog_getuptime(&ts_end);
313 watchdog_patpat(timeout|WD_ACTIVE);
315 waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
316 if (nap - waited > 0)
320 if (end_program != 0) {
321 if (watchdog_onoff(0) == 0) {
324 warnx("Could not stop the watchdog, not exiting");
332 * Reset the watchdog timer. This function must be called periodically
333 * to keep the watchdog from firing.
336 watchdog_patpat(u_int t)
342 return ioctl(fd, WDIOCPATPAT, &t);
346 * Toggle the kernel's watchdog. This routine is used to enable and
347 * disable the watchdog.
350 watchdog_onoff(int onoff)
354 /* fake successful watchdog op if a dry run */
360 * Call the WDIOC_SETSOFT regardless of softtimeout_set
361 * because we'll need to turn it off if someone had turned
364 error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
366 warn("setting WDIOC_SETSOFT %d", softtimeout_set);
369 error = watchdog_patpat((timeout|WD_ACTIVE));
371 warn("watchdog_patpat failed");
374 if (softtimeout_act_set) {
375 error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
378 warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
383 if (pretimeout_set) {
384 error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
386 warn("setting WDIOC_SETPRETIMEOUT %d",
391 if (pretimeout_act_set) {
392 error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
395 warn("setting WDIOC_SETPRETIMEOUTACT %d",
400 /* pat one more time for good measure */
401 return watchdog_patpat((timeout|WD_ACTIVE));
403 return watchdog_patpat(0);
411 * Tell user how to use the program.
417 fprintf(stderr, "usage:\n"
418 " watchdogd [-dnSw] [-e cmd] [-I file] [-s sleep] [-t timeout]\n"
419 " [-T script_timeout]\n"
421 " [--pretimeout seconds] [-pretimeout-action action]\n"
422 " [--softtimeout] [-softtimeout-action action]\n"
425 fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
430 fetchtimeout(int opt, const char *longopt, const char *myoptarg)
439 rv = strtol(myoptarg, &p, 0);
440 if ((p != NULL && *p != '\0') || errno != 0)
441 errstr = "is not a number";
443 errstr = "must be greater than zero";
446 errx(EX_USAGE, "--%s argument %s", longopt, errstr);
448 errx(EX_USAGE, "-%c argument %s", opt, errstr);
458 struct act_tbl act_tbl[] = {
459 { "panic", WD_SOFT_PANIC },
460 { "ddb", WD_SOFT_DDB },
461 { "log", WD_SOFT_LOG },
462 { "printf", WD_SOFT_PRINTF },
467 timeout_act_error(const char *lopt, const char *badact)
469 char *opts, *oldopts;
473 for (i = 0; act_tbl[i].at_act != NULL; i++) {
475 if (asprintf(&opts, "%s%s%s",
476 oldopts == NULL ? "" : oldopts,
477 oldopts == NULL ? "" : ", ",
478 act_tbl[i].at_act) == -1)
479 err(EX_OSERR, "malloc");
482 warnx("bad --%s argument '%s' must be one of (%s).",
488 * Take a comma separated list of actions and or the flags
489 * together for the ioctl.
492 timeout_act_str2int(const char *lopt, const char *acts)
495 char *dupacts, *tofree;
499 tofree = dupacts = strdup(acts);
501 err(EX_OSERR, "malloc");
502 while ((o = strsep(&dupacts, ",")) != NULL) {
503 for (i = 0; act_tbl[i].at_act != NULL; i++) {
504 if (!strcmp(o, act_tbl[i].at_act)) {
505 rv |= act_tbl[i].at_value;
509 if (act_tbl[i].at_act == NULL)
510 timeout_act_error(lopt, o);
517 * Handle the few command line arguments supported.
520 parseargs(int argc, char *argv[])
529 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
530 * otherwise run as a command line utility.
533 if (argv[0][c - 1] == 'd')
537 getopt_shortopts = "I:de:ns:t:ST:w?";
539 getopt_shortopts = "dt:?";
541 while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
542 &longindex)) != -1) {
551 test_cmd = strdup(optarg);
562 nap = fetchtimeout(c, NULL, optarg);
570 a = strtod(optarg, &p);
571 if ((p != NULL && *p != '\0') || errno != 0)
572 errx(EX_USAGE, "-t argument is not a number");
574 errx(EX_USAGE, "-t argument must be positive");
577 timeout = WD_TO_NEVER;
579 timeout = flsll(a * 1e9);
581 printf("Timeout is 2^%d nanoseconds\n",
585 carp_thresh_seconds = fetchtimeout(c, "NULL", optarg);
591 lopt = longopts[longindex].name;
592 if (!strcmp(lopt, "pretimeout")) {
593 pretimeout = fetchtimeout(0, lopt, optarg);
594 } else if (!strcmp(lopt, "pretimeout-action")) {
595 pretimeout_act = timeout_act_str2int(lopt,
597 } else if (!strcmp(lopt, "softtimeout-action")) {
598 softtimeout_act = timeout_act_str2int(lopt,
601 /* warnx("bad option at index %d: %s", optind,
614 if (carp_thresh_seconds == -1)
615 carp_thresh_seconds = nap;
618 errx(EX_USAGE, "extra arguments.");
619 if (is_daemon && timeout < WD_TO_1SEC)
620 errx(EX_USAGE, "-t argument is less than one second.");