xref: /freebsd/sys/kern/subr_rtc.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
1 /*
2  * Copyright (c) 1988 University of Utah.
3  * Copyright (c) 1982, 1990, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * the Systems Programming Group of the University of Utah Computer
8  * Science Department.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
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.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	from: Utah $Hdr: clock.c 1.18 91/01/21$
39  *	from: @(#)clock.c	8.2 (Berkeley) 1/12/94
40  *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
41  *	and
42  *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
43  *
44  * $FreeBSD$
45  */
46 
47 /*
48  * Helpers for time-of-day clocks. This is useful for architectures that need
49  * support multiple models of such clocks, and generally serves to make the
50  * code more machine-independent.
51  * If the clock in question can also be used as a time counter, the driver
52  * needs to initiate this.
53  * This code is not yet used by all architectures.
54  */
55 
56 /*
57  * Generic routines to convert between a POSIX date
58  * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
59  * Derived from NetBSD arch/hp300/hp300/clock.c
60  */
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/kernel.h>
64 #include <sys/bus.h>
65 #include <sys/clock.h>
66 #include <sys/sysctl.h>
67 #include <sys/timetc.h>
68 
69 /* XXX: for the  CPU_* sysctl OID constants. */
70 #include <machine/cpu.h>
71 
72 #include "clock_if.h"
73 
74 static __inline int leapyear(int year);
75 static int sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS);
76 
77 #define	FEBRUARY	2
78 #define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
79 #define	days_in_month(y, m) \
80 	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
81 /* Day of week. Days are counted from 1/1/1970, which was a Thursday */
82 #define	day_of_week(days)	(((days) + 4) % 7)
83 
84 static const int month_days[12] = {
85 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
86 };
87 
88 static device_t clock_dev = NULL;
89 static long clock_res;
90 
91 int adjkerntz;		/* local offset from GMT in seconds */
92 int disable_rtc_set;	/* disable resettodr() if != 0 */
93 int wall_cmos_clock;	/* wall CMOS clock assumed if != 0 */
94 
95 /*
96  * These have traditionally been in machdep, but should probably be moved to
97  * kern.
98  */
99 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
100 	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
101 
102 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
103 	CTLFLAG_RW, &disable_rtc_set, 0, "");
104 
105 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
106 	CTLFLAG_RW, &wall_cmos_clock, 0, "");
107 
108 static int
109 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
110 {
111 	int error;
112 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
113 		req);
114 	if (!error && req->newptr)
115 		resettodr();
116 	return (error);
117 }
118 
119 /*
120  * This inline avoids some unnecessary modulo operations
121  * as compared with the usual macro:
122  *   ( ((year % 4) == 0 &&
123  *      (year % 100) != 0) ||
124  *     ((year % 400) == 0) )
125  * It is otherwise equivalent.
126  */
127 static __inline int
128 leapyear(int year)
129 {
130 	int rv = 0;
131 
132 	if ((year & 3) == 0) {
133 		rv = 1;
134 		if ((year % 100) == 0) {
135 			rv = 0;
136 			if ((year % 400) == 0)
137 				rv = 1;
138 		}
139 	}
140 	return (rv);
141 }
142 
143 int
144 clock_ct_to_ts(struct clocktime *ct, struct timespec *ts)
145 {
146 	time_t secs;
147 	int i, year, days;
148 
149 	year = ct->year;
150 
151 	/* Sanity checks. */
152 	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
153 	    ct->day > days_in_month(year, ct->mon) ||
154 	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 ||
155 	    ct->year > 2037)		/* time_t overflow */
156 		return (EINVAL);
157 
158 	/*
159 	 * Compute days since start of time
160 	 * First from years, then from months.
161 	 */
162 	days = 0;
163 	for (i = POSIX_BASE_YEAR; i < year; i++)
164 		days += days_in_year(i);
165 
166 	/* Months */
167 	for (i = 1; i < ct->mon; i++)
168 	  	days += days_in_month(year, i);
169 	days += (ct->day - 1);
170 
171 	/* Another sanity check. */
172 	if (ct->dow != -1 && ct->dow != day_of_week(days))
173 		return (EINVAL);
174 
175 	/* Add hours, minutes, seconds. */
176 	secs = ((days * 24 + ct->hour) * 60 + ct->min) * 60 + ct->sec;
177 
178 	ts->tv_sec = secs;
179 	ts->tv_nsec = ct->nsec;
180 	return (0);
181 }
182 
183 void
184 clock_ts_to_ct(struct timespec *ts, struct clocktime *ct)
185 {
186 	int i, year, days;
187 	time_t rsec;	/* remainder seconds */
188 	time_t secs;
189 
190 	secs = ts->tv_sec;
191 	days = secs / SECDAY;
192 	rsec = secs % SECDAY;
193 
194 	ct->dow = day_of_week(days);
195 
196 	/* Subtract out whole years, counting them in i. */
197 	for (year = POSIX_BASE_YEAR; days >= days_in_year(year); year++)
198 		days -= days_in_year(year);
199 	ct->year = year;
200 
201 	/* Subtract out whole months, counting them in i. */
202 	for (i = 1; days >= days_in_month(year, i); i++)
203 		days -= days_in_month(year, i);
204 	ct->mon = i;
205 
206 	/* Days are what is left over (+1) from all that. */
207 	ct->day = days + 1;
208 
209 	/* Hours, minutes, seconds are easy */
210 	ct->hour = rsec / 3600;
211 	rsec = rsec % 3600;
212 	ct->min  = rsec / 60;
213 	rsec = rsec % 60;
214 	ct->sec  = rsec;
215 	ct->nsec = ts->tv_nsec;
216 }
217 
218 void
219 clock_register(device_t dev, long res)
220 {
221 
222 	if (clock_dev != NULL) {
223 		if (clock_res > res) {
224 			if (bootverbose) {
225 				device_printf(dev, "not installed as "
226 				    "time-of-day clock: clock %s has higher "
227 				    "resolution\n", device_get_name(clock_dev));
228 			}
229 			return;
230 		} else {
231 			if (bootverbose) {
232 				device_printf(clock_dev, "removed as "
233 				    "time-of-day clock: clock %s has higher "
234 				    "resolution\n", device_get_name(dev));
235 			}
236 		}
237 	}
238 	clock_dev = dev;
239 	clock_res = res;
240 	if (bootverbose) {
241 		device_printf(dev, "registered as a time-of-day clock "
242 		    "(resolution %ldus)\n", res);
243 	}
244 }
245 
246 /*
247  * inittodr and settodr derived from the i386 versions written
248  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>,  reintroduced and
249  * updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
250  */
251 
252 /*
253  * Initialize the time of day register, based on the time base which is, e.g.
254  * from a filesystem.
255  */
256 void
257 inittodr(time_t base)
258 {
259 	struct timespec diff, ref, ts;
260 	int error;
261 
262 	if (base) {
263 		ref.tv_sec = base;
264 		ref.tv_nsec = 0;
265 		tc_setclock(&ref);
266 	}
267 
268 	if (clock_dev == NULL) {
269 		printf("warning: no time-of-day clock registered, system time "
270 		    "will not be set accurately\n");
271 		return;
272 	}
273 	error = CLOCK_GETTIME(clock_dev, &ts);
274 	if (error != 0 && error != EINVAL) {
275 		printf("warning: clock_gettime failed (%d), the system time "
276 		    "will not be set accurately\n", error);
277 		return;
278 	}
279 	if (error == EINVAL || ts.tv_sec < 0) {
280 		printf("Invalid time in real time clock.\n");
281 		printf("Check and reset the date immediately!\n");
282 	}
283 
284 	ts.tv_sec += tz.tz_minuteswest * 60 +
285 	    (wall_cmos_clock ? adjkerntz : 0);
286 
287 	if (timespeccmp(&ref, &ts, >)) {
288 		diff = ref;
289 		timespecsub(&ref, &ts);
290 	} else {
291 		diff = ts;
292 		timespecsub(&diff, &ref);
293 	}
294 	if (ts.tv_sec >= 2) {
295 		/* badly off, adjust it */
296 		tc_setclock(&ts);
297 	}
298 }
299 
300 /*
301  * Write system time back to RTC
302  */
303 void
304 resettodr()
305 {
306 	struct timespec ts;
307 	int error;
308 
309 	if (disable_rtc_set || clock_dev == NULL)
310 		return;
311 
312 	getnanotime(&ts);
313 	ts.tv_sec -= tz.tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
314 	if ((error = CLOCK_SETTIME(clock_dev, &ts)) != 0) {
315 		printf("warning: clock_settime failed (%d), time-of-day clock "
316 		    "not adjusted to system time\n", error);
317 		return;
318 	}
319 }
320