xref: /freebsd/sbin/adjkerntz/adjkerntz.c (revision 390e8cc2974df1888369c06339ef8e0e92b312b6)
1 /*
2  * Copyright (C) 1993-1998 by Andrey A. Chernov, Moscow, Russia.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #if 0
28 #ifndef lint
29 static const char copyright[] =
30 "@(#)Copyright (C) 1993-1996 by Andrey A. Chernov, Moscow, Russia.\n\
31  All rights reserved.\n";
32 #endif /* not lint */
33 #endif
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 /*
38  * Andrey A. Chernov   <ache@astral.msk.su>    Dec 20 1993
39  *
40  * Fix kernel time value if machine run wall CMOS clock
41  * (and /etc/wall_cmos_clock file present)
42  * using zoneinfo rules or direct TZ environment variable set.
43  * Use Joerg Wunsch idea for seconds accurate offset calculation
44  * with Garrett Wollman and Bruce Evans fixes.
45  *
46  */
47 #include <stdio.h>
48 #include <signal.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <syslog.h>
52 #include <sys/time.h>
53 #include <sys/param.h>
54 #include <machine/cpu.h>
55 #include <sys/sysctl.h>
56 
57 #include "pathnames.h"
58 
59 /*#define DEBUG*/
60 
61 #define True (1)
62 #define False (0)
63 #define Unknown (-1)
64 
65 #define REPORT_PERIOD (30*60)
66 
67 static void fake(int);
68 static void usage(void);
69 
70 static void
71 fake(int unused __unused)
72 {
73 
74 	/* Do nothing. */
75 }
76 
77 int
78 main(int argc, char *argv[])
79 {
80 	struct tm local;
81 	struct timeval tv, *stv;
82 	struct timezone tz, *stz;
83 	int kern_offset, wall_clock, disrtcset;
84 	size_t len;
85 	int mib[2];
86 	/* Avoid time_t here, can be unsigned long or worse */
87 	long offset, localsec, diff;
88 	time_t initial_sec, final_sec;
89 	int ch;
90 	int initial_isdst = -1, final_isdst;
91 	int need_restore = False, sleep_mode = False, looping,
92 	    init = Unknown;
93 	sigset_t mask, emask;
94 
95 	while ((ch = getopt(argc, argv, "ais")) != -1)
96 		switch((char)ch) {
97 		case 'i':               /* initial call, save offset */
98 			if (init != Unknown)
99 				usage();
100 			init = True;
101 			break;
102 		case 'a':               /* adjustment call, use saved offset */
103 			if (init != Unknown)
104 				usage();
105 			init = False;
106 			break;
107 		case 's':
108 			sleep_mode = True;
109 			break;
110 		default:
111 			usage();
112 		}
113 	if (init == Unknown)
114 		usage();
115 
116 	if (access(_PATH_CLOCK, F_OK) != 0)
117 		return 0;
118 
119 	if (init)
120 		sleep_mode = True;
121 
122 	sigemptyset(&mask);
123 	sigemptyset(&emask);
124 	sigaddset(&mask, SIGTERM);
125 
126 	openlog("adjkerntz", LOG_PID|LOG_PERROR, LOG_DAEMON);
127 
128 	(void) signal(SIGHUP, SIG_IGN);
129 
130 	if (init && daemon(0, 1)) {
131 		syslog(LOG_ERR, "daemon: %m");
132 		return 1;
133 	}
134 
135 again:
136 	(void) sigprocmask(SIG_BLOCK, &mask, NULL);
137 	(void) signal(SIGTERM, fake);
138 
139 	diff = 0;
140 	stv = NULL;
141 	stz = NULL;
142 	looping = False;
143 
144 	wall_clock = (access(_PATH_CLOCK, F_OK) == 0);
145 	if (init && !sleep_mode) {
146 		init = False;
147 		if (!wall_clock)
148 			return 0;
149 	}
150 
151 	mib[0] = CTL_MACHDEP;
152 	mib[1] = CPU_ADJKERNTZ;
153 	len = sizeof(kern_offset);
154 	if (sysctl(mib, 2, &kern_offset, &len, NULL, 0) == -1) {
155 		syslog(LOG_ERR, "sysctl(get_offset): %m");
156 		return 1;
157 	}
158 
159 /****** Critical section, do all things as fast as possible ******/
160 
161 	/* get local CMOS clock and possible kernel offset */
162 	if (gettimeofday(&tv, &tz)) {
163 		syslog(LOG_ERR, "gettimeofday: %m");
164 		return 1;
165 	}
166 
167 	/* get the actual local timezone difference */
168 	initial_sec = tv.tv_sec;
169 
170 recalculate:
171 	local = *localtime(&initial_sec);
172 	if (diff == 0)
173 		initial_isdst = local.tm_isdst;
174 	local.tm_isdst = initial_isdst;
175 
176 	/* calculate local CMOS diff from GMT */
177 
178 	localsec = mktime(&local);
179 	if (localsec == -1) {
180 		/*
181 		 * XXX user can only control local time, and it is
182 		 * unacceptable to fail here for init.  2:30 am in the
183 		 * middle of the nonexistent hour means 3:30 am.
184 		 */
185 		if (!sleep_mode) {
186 			syslog(LOG_WARNING,
187 			"Warning: nonexistent local time, try to run later.");
188 			syslog(LOG_WARNING, "Giving up.");
189 			return 1;
190 		}
191 		syslog(LOG_WARNING,
192 			"Warning: nonexistent local time.");
193 		syslog(LOG_WARNING, "Will retry after %d minutes.",
194 			REPORT_PERIOD / 60);
195 		(void) signal(SIGTERM, SIG_DFL);
196 		(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
197 		(void) sleep(REPORT_PERIOD);
198 		goto again;
199 	}
200 	offset = -local.tm_gmtoff;
201 #ifdef DEBUG
202 	fprintf(stderr, "Initial offset: %ld secs\n", offset);
203 #endif
204 
205 	/* correct the kerneltime for this diffs */
206 	/* subtract kernel offset, if present, old offset too */
207 
208 	diff = offset - tz.tz_minuteswest * 60 - kern_offset;
209 
210 	if (diff != 0) {
211 #ifdef DEBUG
212 		fprintf(stderr, "Initial diff: %ld secs\n", diff);
213 #endif
214 		/* Yet one step for final time */
215 
216 		final_sec = initial_sec + diff;
217 
218 		/* get the actual local timezone difference */
219 		local = *localtime(&final_sec);
220 		final_isdst = diff < 0 ? initial_isdst : local.tm_isdst;
221 		if (diff > 0 && initial_isdst != final_isdst) {
222 			if (looping)
223 				goto bad_final;
224 			looping = True;
225 			initial_isdst = final_isdst;
226 			goto recalculate;
227 		}
228 		local.tm_isdst =  final_isdst;
229 
230 		localsec = mktime(&local);
231 		if (localsec == -1) {
232 		bad_final:
233 			/*
234 			 * XXX as above.  The user has even less control,
235 			 * but perhaps we never get here.
236 			 */
237 			if (!sleep_mode) {
238 				syslog(LOG_WARNING,
239 					"Warning: nonexistent final local time, try to run later.");
240 				syslog(LOG_WARNING, "Giving up.");
241 				return 1;
242 			}
243 			syslog(LOG_WARNING,
244 				"Warning: nonexistent final local time.");
245 			syslog(LOG_WARNING, "Will retry after %d minutes.",
246 				REPORT_PERIOD / 60);
247 			(void) signal(SIGTERM, SIG_DFL);
248 			(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
249 			(void) sleep(REPORT_PERIOD);
250 			goto again;
251 		}
252 		offset = -local.tm_gmtoff;
253 #ifdef DEBUG
254 		fprintf(stderr, "Final offset: %ld secs\n", offset);
255 #endif
256 
257 		/* correct the kerneltime for this diffs */
258 		/* subtract kernel offset, if present, old offset too */
259 
260 		diff = offset - tz.tz_minuteswest * 60 - kern_offset;
261 
262 		if (diff != 0) {
263 #ifdef DEBUG
264 			fprintf(stderr, "Final diff: %ld secs\n", diff);
265 #endif
266 			/*
267 			 * stv is abused as a flag.  The important value
268 			 * is in `diff'.
269 			 */
270 			stv = &tv;
271 		}
272 	}
273 
274 	if (tz.tz_dsttime != 0 || tz.tz_minuteswest != 0) {
275 		tz.tz_dsttime = tz.tz_minuteswest = 0;  /* zone info is garbage */
276 		stz = &tz;
277 	}
278 	if (!wall_clock && stz == NULL)
279 		stv = NULL;
280 
281 	/* if init or UTC clock and offset/date will be changed, */
282 	/* disable RTC modification for a while.                      */
283 
284 	if (   (init && stv != NULL)
285 	    || ((init || !wall_clock) && kern_offset != offset)
286 	   ) {
287 		mib[0] = CTL_MACHDEP;
288 		mib[1] = CPU_DISRTCSET;
289 		len = sizeof(disrtcset);
290 		if (sysctl(mib, 2, &disrtcset, &len, NULL, 0) == -1) {
291 			syslog(LOG_ERR, "sysctl(get_disrtcset): %m");
292 			return 1;
293 		}
294 		if (disrtcset == 0) {
295 			disrtcset = 1;
296 			need_restore = True;
297 			if (sysctl(mib, 2, NULL, NULL, &disrtcset, len) == -1) {
298 				syslog(LOG_ERR, "sysctl(set_disrtcset): %m");
299 				return 1;
300 			}
301 		}
302 	}
303 
304 	if (   (init && (stv != NULL || stz != NULL))
305 	    || (stz != NULL && stv == NULL)
306 	   ) {
307 		if (stv != NULL) {
308 			/*
309 			 * Get the time again, as close as possible to
310 			 * adjusting it, to minimise drift.
311 			 * XXX we'd better not fail between here and
312 			 * restoring disrtcset, since we don't clean up
313 			 * anything.
314 			 */
315 			if (gettimeofday(&tv, (struct timezone *)NULL)) {
316 				syslog(LOG_ERR, "gettimeofday: %m");
317 				return 1;
318 			}
319 			tv.tv_sec += diff;
320 			stv = &tv;
321 		}
322 		if (settimeofday(stv, stz)) {
323 			syslog(LOG_ERR, "settimeofday: %m");
324 			return 1;
325 		}
326 	}
327 
328 	/* setting CPU_ADJKERNTZ have a side effect: resettodr(), which */
329 	/* can be disabled by CPU_DISRTCSET, so if init or UTC clock    */
330 	/* -- don't write RTC, else write RTC.                          */
331 
332 	if (kern_offset != offset) {
333 		kern_offset = offset;
334 		mib[0] = CTL_MACHDEP;
335 		mib[1] = CPU_ADJKERNTZ;
336 		len = sizeof(kern_offset);
337 		if (sysctl(mib, 2, NULL, NULL, &kern_offset, len) == -1) {
338 			syslog(LOG_ERR, "sysctl(update_offset): %m");
339 			return 1;
340 		}
341 	}
342 
343 	mib[0] = CTL_MACHDEP;
344 	mib[1] = CPU_WALLCLOCK;
345 	len = sizeof(wall_clock);
346 	if (sysctl(mib, 2, NULL, NULL, &wall_clock, len) == -1) {
347 		syslog(LOG_ERR, "sysctl(put_wallclock): %m");
348 		return 1;
349 	}
350 
351 	if (need_restore) {
352 		need_restore = False;
353 		mib[0] = CTL_MACHDEP;
354 		mib[1] = CPU_DISRTCSET;
355 		disrtcset = 0;
356 		len = sizeof(disrtcset);
357 		if (sysctl(mib, 2, NULL, NULL, &disrtcset, len) == -1) {
358 			syslog(LOG_ERR, "sysctl(restore_disrtcset): %m");
359 			return 1;
360 		}
361 	}
362 
363 /****** End of critical section ******/
364 
365 	if (init && wall_clock) {
366 		sleep_mode = False;
367 		/* wait for signals and acts like -a */
368 		(void) sigsuspend(&emask);
369 		goto again;
370 	}
371 
372 	return 0;
373 }
374 
375 static void
376 usage(void)
377 {
378 	fprintf(stderr, "%s\n%s\n%s\n%s\n",
379 		"usage: adjkerntz -i",
380 		"\t\t(initial call from /etc/rc)",
381 		"       adjkerntz -a [-s]",
382 		"\t\t(adjustment call, -s for sleep/retry mode)");
383 	exit(2);
384 }
385