adjkerntz.c revision 33831
1185573Srwatson/*
2181053Srwatson * Copyright (C) 1993-1996 by Andrey A. Chernov, Moscow, Russia.
3155191Srwatson * All rights reserved.
4155191Srwatson *
5155191Srwatson * Redistribution and use in source and binary forms, with or without
6155191Srwatson * modification, are permitted provided that the following conditions
7155191Srwatson * are met:
8155191Srwatson * 1. Redistributions of source code must retain the above copyright
9155191Srwatson *    notice, this list of conditions and the following disclaimer.
10155191Srwatson * 2. Redistributions in binary form must reproduce the above copyright
11155191Srwatson *    notice, this list of conditions and the following disclaimer in the
12155191Srwatson *    documentation and/or other materials provided with the distribution.
13155191Srwatson *
14155191Srwatson * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
15155191Srwatson * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16155191Srwatson * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17155191Srwatson * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18155191Srwatson * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19155191Srwatson * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20155191Srwatson * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21155191Srwatson * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22155191Srwatson * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23155191Srwatson * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24155191Srwatson * SUCH DAMAGE.
25155191Srwatson *
26155191Srwatson *		$Id: adjkerntz.c,v 1.20 1997/06/10 11:01:13 charnier Exp $
27155191Srwatson */
28155191Srwatson
29155191Srwatson#ifndef lint
30155191Srwatsonchar copyright[] =
31155191Srwatson"@(#)Copyright (C) 1993-1996 by Andrey A. Chernov, Moscow, Russia.\n\
32155191Srwatson All rights reserved.\n";
33185573Srwatson#endif /* not lint */
34155191Srwatson
35155191Srwatson/*
36155191Srwatson * Andrey A. Chernov   <ache@astral.msk.su>    Dec 20 1993
37156289Srwatson *
38156289Srwatson * Fix kernel time value if machine run wall CMOS clock
39155191Srwatson * (and /etc/wall_cmos_clock file present)
40156289Srwatson * using zoneinfo rules or direct TZ environment variable set.
41156289Srwatson * Use Joerg Wunsch idea for seconds accurate offset calculation
42156289Srwatson * with Garrett Wollman and Bruce Evans fixes.
43156289Srwatson *
44155191Srwatson */
45155191Srwatson#include <stdio.h>
46155191Srwatson#include <signal.h>
47155191Srwatson#include <stdlib.h>
48155191Srwatson#include <unistd.h>
49155191Srwatson#include <syslog.h>
50155191Srwatson#include <sys/stat.h>
51156289Srwatson#include <sys/time.h>
52156289Srwatson#include <sys/param.h>
53156289Srwatson#include <machine/cpu.h>
54156289Srwatson#include <sys/sysctl.h>
55156289Srwatson
56155191Srwatson#include "pathnames.h"
57156289Srwatson
58156289Srwatson/*#define DEBUG*/
59156289Srwatson
60156289Srwatson#define True (1)
61156289Srwatson#define False (0)
62156289Srwatson#define Unknown (-1)
63156289Srwatson
64156289Srwatson#define REPORT_PERIOD (30*60)
65156289Srwatson
66156289Srwatsonstatic void usage __P((void));
67156289Srwatson
68161635Srwatsonvoid fake() {}
69161635Srwatson
70161870Srwatsonint main(argc, argv)
71161635Srwatson	int argc;
72161870Srwatson	char **argv;
73161635Srwatson{
74155191Srwatson	struct tm local, utc;
75184856Scsjp	struct timeval tv, *stv;
76161635Srwatson	struct timezone tz, *stz;
77184856Scsjp	int kern_offset, wall_clock, disrtcset;
78161635Srwatson	size_t len;
79155191Srwatson	int mib[2];
80155191Srwatson	/* Avoid time_t here, can be unsigned long or worse */
81155191Srwatson	long offset, utcsec, localsec, diff;
82155191Srwatson	time_t initial_sec, final_sec;
83155191Srwatson	int ch;
84155191Srwatson	int initial_isdst = -1, final_isdst;
85155191Srwatson	int need_restore = False, sleep_mode = False, looping,
86155191Srwatson	    init = Unknown;
87155191Srwatson	sigset_t mask, emask;
88155191Srwatson
89155191Srwatson	while ((ch = getopt(argc, argv, "ais")) != -1)
90155191Srwatson		switch((char)ch) {
91155191Srwatson		case 'i':               /* initial call, save offset */
92155191Srwatson			if (init != Unknown)
93155191Srwatson				usage();
94155191Srwatson			init = True;
95155191Srwatson			break;
96155191Srwatson		case 'a':               /* adjustment call, use saved offset */
97155191Srwatson			if (init != Unknown)
98155191Srwatson				usage();
99155191Srwatson			init = False;
100155191Srwatson			break;
101155191Srwatson		case 's':
102155191Srwatson			sleep_mode = True;
103155191Srwatson			break;
104155191Srwatson		default:
105155191Srwatson			usage();
106155191Srwatson		}
107155191Srwatson	if (init == Unknown)
108155191Srwatson		usage();
109155191Srwatson	if (init)
110155191Srwatson		sleep_mode = True;
111155191Srwatson
112155191Srwatson	sigemptyset(&mask);
113155191Srwatson	sigemptyset(&emask);
114155191Srwatson	sigaddset(&mask, SIGTERM);
115155191Srwatson
116155191Srwatson	openlog("adjkerntz", LOG_PID|LOG_PERROR, LOG_DAEMON);
117155191Srwatson
118156289Srwatson	(void) signal(SIGHUP, SIG_IGN);
119
120	if (init && daemon(0, 1)) {
121		syslog(LOG_ERR, "daemon: %m");
122		return 1;
123	}
124
125again:
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
160recalculate:
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			/*
261			 * stv is abused as a flag.  The important value
262			 * is in `diff'.
263			 */
264			stv = &tv;
265		}
266	}
267
268	if (tz.tz_dsttime != 0 || tz.tz_minuteswest != 0) {
269		tz.tz_dsttime = tz.tz_minuteswest = 0;  /* zone info is garbage */
270		stz = &tz;
271	}
272	if (!wall_clock && stz == NULL)
273		stv = NULL;
274
275	/* if init or UTC clock and offset/date will be changed, */
276	/* disable RTC modification for a while.                      */
277
278	if (   (init && stv != NULL)
279	    || ((init || !wall_clock) && kern_offset != offset)
280	   ) {
281		mib[0] = CTL_MACHDEP;
282		mib[1] = CPU_DISRTCSET;
283		len = sizeof(disrtcset);
284		if (sysctl(mib, 2, &disrtcset, &len, NULL, 0) == -1) {
285			syslog(LOG_ERR, "sysctl(get_disrtcset): %m");
286			return 1;
287		}
288		if (disrtcset == 0) {
289			disrtcset = 1;
290			need_restore = True;
291			if (sysctl(mib, 2, NULL, NULL, &disrtcset, len) == -1) {
292				syslog(LOG_ERR, "sysctl(set_disrtcset): %m");
293				return 1;
294			}
295		}
296	}
297
298	if (   (init && (stv != NULL || stz != NULL))
299	    || (stz != NULL && stv == NULL)
300	   ) {
301		if (stv != NULL) {
302			/*
303			 * Get the time again, as close as possible to
304			 * adjusting it, to minimise drift.
305			 * XXX we'd better not fail between here and
306			 * restoring disrtcset, since we don't clean up
307			 * anything.
308			 */
309			if (gettimeofday(&tv, (struct timezone *)NULL)) {
310				syslog(LOG_ERR, "gettimeofday: %m");
311				return 1;
312			}
313			tv.tv_sec += diff;
314			stv = &tv;
315		}
316		if (settimeofday(stv, stz)) {
317			syslog(LOG_ERR, "settimeofday: %m");
318			return 1;
319		}
320	}
321
322	/* setting CPU_ADJKERNTZ have a side effect: resettodr(), which */
323	/* can be disabled by CPU_DISRTCSET, so if init or UTC clock    */
324	/* -- don't write RTC, else write RTC.                          */
325
326	if (kern_offset != offset) {
327		kern_offset = offset;
328		mib[0] = CTL_MACHDEP;
329		mib[1] = CPU_ADJKERNTZ;
330		len = sizeof(kern_offset);
331		if (sysctl(mib, 2, NULL, NULL, &kern_offset, len) == -1) {
332			syslog(LOG_ERR, "sysctl(update_offset): %m");
333			return 1;
334		}
335	}
336
337	mib[0] = CTL_MACHDEP;
338	mib[1] = CPU_WALLCLOCK;
339	len = sizeof(wall_clock);
340	if (sysctl(mib, 2, NULL, NULL, &wall_clock, len) == -1) {
341		syslog(LOG_ERR, "sysctl(put_wallclock): %m");
342		return 1;
343	}
344
345	if (need_restore) {
346		need_restore = False;
347		mib[0] = CTL_MACHDEP;
348		mib[1] = CPU_DISRTCSET;
349		disrtcset = 0;
350		len = sizeof(disrtcset);
351		if (sysctl(mib, 2, NULL, NULL, &disrtcset, len) == -1) {
352			syslog(LOG_ERR, "sysctl(restore_disrtcset): %m");
353			return 1;
354		}
355	}
356
357/****** End of critical section ******/
358
359	if (init && wall_clock) {
360		sleep_mode = False;
361		/* wait for signals and acts like -a */
362		(void) sigsuspend(&emask);
363		goto again;
364	}
365
366	return 0;
367}
368
369static void
370usage()
371{
372	fprintf(stderr, "%s\n%s\n%s\n%s\n",
373		"usage: adjkerntz -i",
374		"\t\t(initial call from /etc/rc)",
375		"       adjkerntz -a [-s]",
376		"\t\t(adjustment call, -s for sleep/retry mode)");
377	exit(2);
378}
379