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