xref: /freebsd/sbin/adjkerntz/adjkerntz.c (revision e627b39baccd1ec9129690167cf5e6d860509655)
1 /*
2  * Copyright (C) 1993-1996 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 #ifndef lint
28 char copyright[] =
29 "@(#)Copyright (C) 1993-1996 by Andrey A. Chernov, Moscow, Russia.\n\
30  All rights reserved.\n";
31 #endif /* not lint */
32 
33 /*
34  * Andrey A. Chernov   <ache@astral.msk.su>    Dec 20 1993
35  *
36  * Fix kernel time value if machine run wall CMOS clock
37  * (and /etc/wall_cmos_clock file present)
38  * using zoneinfo rules or direct TZ environment variable set.
39  * Use Joerg Wunsch idea for seconds accurate offset calculation
40  * with Garrett Wollman and Bruce Evans fixes.
41  *
42  */
43 #include <stdio.h>
44 #include <signal.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <syslog.h>
48 #include <sys/stat.h>
49 #include <sys/time.h>
50 #include <sys/param.h>
51 #include <machine/cpu.h>
52 #include <sys/sysctl.h>
53 
54 #include "pathnames.h"
55 
56 /*#define DEBUG*/
57 
58 #define True (1)
59 #define False (0)
60 #define Unknown (-1)
61 
62 #define REPORT_PERIOD (30*60)
63 
64 void fake() {}
65 
66 int main(argc, argv)
67 	int argc;
68 	char **argv;
69 {
70 	struct tm local, utc;
71 	struct timeval tv, *stv;
72 	struct timezone tz, *stz;
73 	int kern_offset, wall_clock, disrtcset;
74 	size_t len;
75 	int mib[2];
76 	/* Avoid time_t here, can be unsigned long or worse */
77 	long offset, utcsec, localsec, diff;
78 	time_t initial_sec, final_sec;
79 	int ch;
80 	int initial_isdst = -1, final_isdst;
81 	int need_restore = False, sleep_mode = False, looping,
82 	    init = Unknown;
83 	sigset_t mask, emask;
84 
85 	while ((ch = getopt(argc, argv, "ais")) != EOF)
86 		switch((char)ch) {
87 		case 'i':               /* initial call, save offset */
88 			if (init != Unknown)
89 				goto usage;
90 			init = True;
91 			break;
92 		case 'a':               /* adjustment call, use saved offset */
93 			if (init != Unknown)
94 				goto usage;
95 			init = False;
96 			break;
97 		case 's':
98 			sleep_mode = True;
99 			break;
100 		default:
101 		usage:
102 			fprintf(stderr, "Usage:\n\
103 \tadjkerntz -i\t\t(initial call from /etc/rc)\n\
104 \tadjkerntz -a [-s]\t(adjustment call, -s for sleep/retry mode)\n");
105   			return 2;
106 		}
107 	if (init == Unknown)
108 		goto usage;
109 	if (init)
110 		sleep_mode = True;
111 
112 	sigemptyset(&mask);
113 	sigemptyset(&emask);
114 	sigaddset(&mask, SIGTERM);
115 
116 	openlog("adjkerntz", LOG_PID|LOG_PERROR, LOG_DAEMON);
117 
118 	(void) signal(SIGHUP, SIG_IGN);
119 
120 	if (init && daemon(0, 1)) {
121 		syslog(LOG_ERR, "daemon: %m");
122 		return 1;
123 	}
124 
125 again:
126 	(void) sigprocmask(SIG_BLOCK, &mask, NULL);
127 	(void) signal(SIGTERM, fake);
128 
129 	diff = 0;
130 	stv = NULL;
131 	stz = NULL;
132 	looping = False;
133 
134 	wall_clock = (access(_PATH_CLOCK, F_OK) == 0);
135 	if (init && !sleep_mode) {
136 		init = False;
137 		if (!wall_clock)
138 			return 0;
139 	}
140 
141 	mib[0] = CTL_MACHDEP;
142 	mib[1] = CPU_ADJKERNTZ;
143 	len = sizeof(kern_offset);
144 	if (sysctl(mib, 2, &kern_offset, &len, NULL, 0) == -1) {
145 		syslog(LOG_ERR, "sysctl(get_offset): %m");
146 		return 1;
147 	}
148 
149 /****** Critical section, do all things as fast as possible ******/
150 
151 	/* get local CMOS clock and possible kernel offset */
152 	if (gettimeofday(&tv, &tz)) {
153 		syslog(LOG_ERR, "gettimeofday: %m");
154 		return 1;
155 	}
156 
157 	/* get the actual local timezone difference */
158 	initial_sec = tv.tv_sec;
159 
160 recalculate:
161 	local = *localtime(&initial_sec);
162 	if (diff == 0)
163 		initial_isdst = local.tm_isdst;
164 	utc = *gmtime(&initial_sec);
165 	local.tm_isdst = utc.tm_isdst = initial_isdst;
166 
167 	/* calculate local CMOS diff from GMT */
168 
169 	utcsec = mktime(&utc);
170 	localsec = mktime(&local);
171 	if (utcsec == -1 || localsec == -1) {
172 		/*
173 		 * XXX user can only control local time, and it is
174 		 * unacceptable to fail here for init.  2:30 am in the
175 		 * middle of the nonexistent hour means 3:30 am.
176 		 */
177 		syslog(LOG_WARNING,
178 		"Warning: nonexistent %s time.",
179 			utcsec == -1 && localsec == -1 ? "UTC time and local" :
180 			utcsec == -1 ? "UTC" : "local");
181 		if (!sleep_mode) {
182 			syslog(LOG_WARNING, "Giving up.");
183 			return 1;
184 		}
185 		syslog(LOG_WARNING, "Will retry after %d minutes.",
186 			REPORT_PERIOD / 60);
187 		(void) signal(SIGTERM, SIG_DFL);
188 		(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
189 		(void) sleep(REPORT_PERIOD);
190 		goto again;
191 	}
192 	offset = utcsec - localsec;
193 #ifdef DEBUG
194 	fprintf(stderr, "Initial offset: %ld secs\n", offset);
195 #endif
196 
197 	/* correct the kerneltime for this diffs */
198 	/* subtract kernel offset, if present, old offset too */
199 
200 	diff = offset - tz.tz_minuteswest * 60 - kern_offset;
201 
202 	if (diff != 0) {
203 #ifdef DEBUG
204 		fprintf(stderr, "Initial diff: %ld secs\n", diff);
205 #endif
206 		/* Yet one step for final time */
207 
208 		final_sec = initial_sec + diff;
209 
210 		/* get the actual local timezone difference */
211 		local = *localtime(&final_sec);
212 		final_isdst = diff < 0 ? initial_isdst : local.tm_isdst;
213 		if (diff > 0 && initial_isdst != final_isdst) {
214 			if (looping)
215 				goto bad_final;
216 			looping = True;
217 			initial_isdst = final_isdst;
218 			goto recalculate;
219 		}
220 		utc = *gmtime(&final_sec);
221 		local.tm_isdst = utc.tm_isdst = final_isdst;
222 
223 		utcsec = mktime(&utc);
224 		localsec = mktime(&local);
225 		if (utcsec == -1 || localsec == -1) {
226 		bad_final:
227 			/*
228 			 * XXX as above.  The user has even less control,
229 			 * but perhaps we never get here.
230 			 */
231 			syslog(LOG_WARNING,
232 				"Warning: nonexistent final %s time.",
233 				utcsec == -1 && localsec == -1 ? "UTC time and local" :
234 				utcsec == -1 ? "UTC" : "local");
235 			if (!sleep_mode) {
236 				syslog(LOG_WARNING, "Giving up.");
237 				return 1;
238 			}
239 			syslog(LOG_WARNING, "Will retry after %d minutes.",
240 				REPORT_PERIOD / 60);
241 			(void) signal(SIGTERM, SIG_DFL);
242 			(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
243 			(void) sleep(REPORT_PERIOD);
244 			goto again;
245 		}
246 		offset = utcsec - localsec;
247 #ifdef DEBUG
248 		fprintf(stderr, "Final offset: %ld secs\n", offset);
249 #endif
250 
251 		/* correct the kerneltime for this diffs */
252 		/* subtract kernel offset, if present, old offset too */
253 
254 		diff = offset - tz.tz_minuteswest * 60 - kern_offset;
255 
256 		if (diff != 0) {
257 #ifdef DEBUG
258 			fprintf(stderr, "Final diff: %ld secs\n", diff);
259 #endif
260 			tv.tv_sec += diff;
261 			tv.tv_usec = 0;       /* we are restarting here... */
262 			stv = &tv;
263 		}
264 	}
265 
266 	if (tz.tz_dsttime != 0 || tz.tz_minuteswest != 0) {
267 		tz.tz_dsttime = tz.tz_minuteswest = 0;  /* zone info is garbage */
268 		stz = &tz;
269 	}
270 	if (!wall_clock && stz == NULL)
271 		stv = NULL;
272 
273 	/* if init or UTC clock and offset/date will be changed, */
274 	/* disable RTC modification for a while.                      */
275 
276 	if (   (init && stv != NULL)
277 	    || ((init || !wall_clock) && kern_offset != offset)
278 	   ) {
279 		mib[0] = CTL_MACHDEP;
280 		mib[1] = CPU_DISRTCSET;
281 		len = sizeof(disrtcset);
282 		if (sysctl(mib, 2, &disrtcset, &len, NULL, 0) == -1) {
283 			syslog(LOG_ERR, "sysctl(get_disrtcset): %m");
284 			return 1;
285 		}
286 		if (disrtcset == 0) {
287 			disrtcset = 1;
288 			need_restore = True;
289 			if (sysctl(mib, 2, NULL, NULL, &disrtcset, len) == -1) {
290 				syslog(LOG_ERR, "sysctl(set_disrtcset): %m");
291 				return 1;
292 			}
293 		}
294 	}
295 
296 	if (   (   (init && (stv != NULL || stz != NULL))
297 		|| (stz != NULL && stv == NULL)
298 	       )
299 	    && settimeofday(stv, stz)
300 	   ) {
301 		syslog(LOG_ERR, "settimeofday: %m");
302 		return 1;
303 	}
304 
305 	/* setting CPU_ADJKERNTZ have a side effect: resettodr(), which */
306 	/* can be disabled by CPU_DISRTCSET, so if init or UTC clock    */
307 	/* -- don't write RTC, else write RTC.                          */
308 
309 	if (kern_offset != offset) {
310 		kern_offset = offset;
311 		mib[0] = CTL_MACHDEP;
312 		mib[1] = CPU_ADJKERNTZ;
313 		len = sizeof(kern_offset);
314 		if (sysctl(mib, 2, NULL, NULL, &kern_offset, len) == -1) {
315 			syslog(LOG_ERR, "sysctl(update_offset): %m");
316 			return 1;
317 		}
318 	}
319 
320 	mib[0] = CTL_MACHDEP;
321 	mib[1] = CPU_WALLCLOCK;
322 	len = sizeof(wall_clock);
323 	if (sysctl(mib, 2, NULL, NULL, &wall_clock, len) == -1) {
324 		syslog(LOG_ERR, "sysctl(put_wallclock): %m");
325 		return 1;
326 	}
327 
328 	if (need_restore) {
329 		need_restore = False;
330 		mib[0] = CTL_MACHDEP;
331 		mib[1] = CPU_DISRTCSET;
332 		disrtcset = 0;
333 		len = sizeof(disrtcset);
334 		if (sysctl(mib, 2, NULL, NULL, &disrtcset, len) == -1) {
335 			syslog(LOG_ERR, "sysctl(restore_disrtcset): %m");
336 			return 1;
337 		}
338 	}
339 
340 /****** End of critical section ******/
341 
342 	if (init && wall_clock) {
343 		sleep_mode = False;
344 		/* wait for signals and acts like -a */
345 		(void) sigsuspend(&emask);
346 		goto again;
347 	}
348 
349 	return 0;
350 }
351