xref: /freebsd/sys/kern/subr_rtc.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 
45 /*
46  * Helpers for time-of-day clocks. This is useful for architectures that need
47  * support multiple models of such clocks, and generally serves to make the
48  * code more machine-independent.
49  * If the clock in question can also be used as a time counter, the driver
50  * needs to initiate this.
51  * This code is not yet used by all architectures.
52  */
53 
54 /*
55  * Generic routines to convert between a POSIX date
56  * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
57  * Derived from NetBSD arch/hp300/hp300/clock.c
58  */
59 
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62 
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/bus.h>
67 #include <sys/clock.h>
68 #include <sys/sysctl.h>
69 #include <sys/timetc.h>
70 
71 /* XXX: for the  CPU_* sysctl OID constants. */
72 #include <machine/cpu.h>
73 
74 #include "clock_if.h"
75 
76 static __inline int leapyear(int year);
77 static int sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS);
78 
79 #define	FEBRUARY	2
80 #define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
81 #define	days_in_month(y, m) \
82 	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
83 /* Day of week. Days are counted from 1/1/1970, which was a Thursday */
84 #define	day_of_week(days)	(((days) + 4) % 7)
85 
86 static const int month_days[12] = {
87 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
88 };
89 
90 static device_t clock_dev = NULL;
91 static long clock_res;
92 
93 int adjkerntz;		/* local offset from GMT in seconds */
94 int disable_rtc_set;	/* disable resettodr() if != 0 */
95 int wall_cmos_clock;	/* wall CMOS clock assumed if != 0 */
96 
97 /*
98  * These have traditionally been in machdep, but should probably be moved to
99  * kern.
100  */
101 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
102 	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
103 
104 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
105 	CTLFLAG_RW, &disable_rtc_set, 0, "");
106 
107 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
108 	CTLFLAG_RW, &wall_cmos_clock, 0, "");
109 
110 static int
111 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
112 {
113 	int error;
114 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
115 		req);
116 	if (!error && req->newptr)
117 		resettodr();
118 	return (error);
119 }
120 
121 /*
122  * This inline avoids some unnecessary modulo operations
123  * as compared with the usual macro:
124  *   ( ((year % 4) == 0 &&
125  *      (year % 100) != 0) ||
126  *     ((year % 400) == 0) )
127  * It is otherwise equivalent.
128  */
129 static __inline int
130 leapyear(int year)
131 {
132 	int rv = 0;
133 
134 	if ((year & 3) == 0) {
135 		rv = 1;
136 		if ((year % 100) == 0) {
137 			rv = 0;
138 			if ((year % 400) == 0)
139 				rv = 1;
140 		}
141 	}
142 	return (rv);
143 }
144 
145 int
146 clock_ct_to_ts(struct clocktime *ct, struct timespec *ts)
147 {
148 	time_t secs;
149 	int i, year, days;
150 
151 	year = ct->year;
152 
153 	/* Sanity checks. */
154 	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
155 	    ct->day > days_in_month(year, ct->mon) ||
156 	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 ||
157 	    ct->year > 2037)		/* time_t overflow */
158 		return (EINVAL);
159 
160 	/*
161 	 * Compute days since start of time
162 	 * First from years, then from months.
163 	 */
164 	days = 0;
165 	for (i = POSIX_BASE_YEAR; i < year; i++)
166 		days += days_in_year(i);
167 
168 	/* Months */
169 	for (i = 1; i < ct->mon; i++)
170 	  	days += days_in_month(year, i);
171 	days += (ct->day - 1);
172 
173 	/* Another sanity check. */
174 	if (ct->dow != -1 && ct->dow != day_of_week(days))
175 		return (EINVAL);
176 
177 	/* Add hours, minutes, seconds. */
178 	secs = ((days * 24 + ct->hour) * 60 + ct->min) * 60 + ct->sec;
179 
180 	ts->tv_sec = secs;
181 	ts->tv_nsec = ct->nsec;
182 	return (0);
183 }
184 
185 void
186 clock_ts_to_ct(struct timespec *ts, struct clocktime *ct)
187 {
188 	int i, year, days;
189 	time_t rsec;	/* remainder seconds */
190 	time_t secs;
191 
192 	secs = ts->tv_sec;
193 	days = secs / SECDAY;
194 	rsec = secs % SECDAY;
195 
196 	ct->dow = day_of_week(days);
197 
198 	/* Subtract out whole years, counting them in i. */
199 	for (year = POSIX_BASE_YEAR; days >= days_in_year(year); year++)
200 		days -= days_in_year(year);
201 	ct->year = year;
202 
203 	/* Subtract out whole months, counting them in i. */
204 	for (i = 1; days >= days_in_month(year, i); i++)
205 		days -= days_in_month(year, i);
206 	ct->mon = i;
207 
208 	/* Days are what is left over (+1) from all that. */
209 	ct->day = days + 1;
210 
211 	/* Hours, minutes, seconds are easy */
212 	ct->hour = rsec / 3600;
213 	rsec = rsec % 3600;
214 	ct->min  = rsec / 60;
215 	rsec = rsec % 60;
216 	ct->sec  = rsec;
217 	ct->nsec = ts->tv_nsec;
218 }
219 
220 void
221 clock_register(device_t dev, long res)
222 {
223 
224 	if (clock_dev != NULL) {
225 		if (clock_res > res) {
226 			if (bootverbose) {
227 				device_printf(dev, "not installed as "
228 				    "time-of-day clock: clock %s has higher "
229 				    "resolution\n", device_get_name(clock_dev));
230 			}
231 			return;
232 		} else {
233 			if (bootverbose) {
234 				device_printf(clock_dev, "removed as "
235 				    "time-of-day clock: clock %s has higher "
236 				    "resolution\n", device_get_name(dev));
237 			}
238 		}
239 	}
240 	clock_dev = dev;
241 	clock_res = res;
242 	if (bootverbose) {
243 		device_printf(dev, "registered as a time-of-day clock "
244 		    "(resolution %ldus)\n", res);
245 	}
246 }
247 
248 /*
249  * inittodr and settodr derived from the i386 versions written
250  * by Christoph Robitschko <chmr@edvz.tu-graz.ac.at>,  reintroduced and
251  * updated by Chris Stenton <chris@gnome.co.uk> 8/10/94
252  */
253 
254 /*
255  * Initialize the time of day register, based on the time base which is, e.g.
256  * from a filesystem.
257  */
258 void
259 inittodr(time_t base)
260 {
261 	struct timespec diff, ref, ts;
262 	int error;
263 
264 	if (base) {
265 		ref.tv_sec = base;
266 		ref.tv_nsec = 0;
267 		tc_setclock(&ref);
268 	}
269 
270 	if (clock_dev == NULL) {
271 		printf("warning: no time-of-day clock registered, system time "
272 		    "will not be set accurately\n");
273 		return;
274 	}
275 	error = CLOCK_GETTIME(clock_dev, &ts);
276 	if (error != 0 && error != EINVAL) {
277 		printf("warning: clock_gettime failed (%d), the system time "
278 		    "will not be set accurately\n", error);
279 		return;
280 	}
281 	if (error == EINVAL || ts.tv_sec < 0) {
282 		printf("Invalid time in real time clock.\n");
283 		printf("Check and reset the date immediately!\n");
284 	}
285 
286 	ts.tv_sec += tz_minuteswest * 60 +
287 	    (wall_cmos_clock ? adjkerntz : 0);
288 
289 	if (timespeccmp(&ref, &ts, >)) {
290 		diff = ref;
291 		timespecsub(&ref, &ts);
292 	} else {
293 		diff = ts;
294 		timespecsub(&diff, &ref);
295 	}
296 	if (ts.tv_sec >= 2) {
297 		/* badly off, adjust it */
298 		tc_setclock(&ts);
299 	}
300 }
301 
302 /*
303  * Write system time back to RTC
304  */
305 void
306 resettodr()
307 {
308 	struct timespec ts;
309 	int error;
310 
311 	if (disable_rtc_set || clock_dev == NULL)
312 		return;
313 
314 	getnanotime(&ts);
315 	ts.tv_sec -= tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0);
316 	if ((error = CLOCK_SETTIME(clock_dev, &ts)) != 0) {
317 		printf("warning: clock_settime failed (%d), time-of-day clock "
318 		    "not adjusted to system time\n", error);
319 		return;
320 	}
321 }
322