xref: /freebsd/sys/kern/subr_clock.c (revision d93a896e)
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	from: Utah $Hdr: clock.c 1.18 91/01/21$
35  *	from: @(#)clock.c	8.2 (Berkeley) 1/12/94
36  *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
37  *	and
38  *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/bus.h>
48 #include <sys/clock.h>
49 #include <sys/limits.h>
50 #include <sys/sysctl.h>
51 #include <sys/timetc.h>
52 
53 int tz_minuteswest;
54 int tz_dsttime;
55 
56 /*
57  * The adjkerntz and wall_cmos_clock sysctls are in the "machdep" sysctl
58  * namespace because they were misplaced there originally.
59  */
60 static int adjkerntz;
61 static int
62 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
63 {
64 	int error;
65 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
66 	if (!error && req->newptr)
67 		resettodr();
68 	return (error);
69 }
70 SYSCTL_PROC(_machdep, OID_AUTO, adjkerntz, CTLTYPE_INT | CTLFLAG_RW |
71     CTLFLAG_MPSAFE, &adjkerntz, 0, sysctl_machdep_adjkerntz, "I",
72     "Local offset from UTC in seconds");
73 
74 static int ct_debug;
75 SYSCTL_INT(_debug, OID_AUTO, clocktime, CTLFLAG_RWTUN,
76     &ct_debug, 0, "Enable printing of clocktime debugging");
77 
78 static int wall_cmos_clock;
79 SYSCTL_INT(_machdep, OID_AUTO, wall_cmos_clock, CTLFLAG_RW,
80     &wall_cmos_clock, 0, "Enables application of machdep.adjkerntz");
81 
82 /*--------------------------------------------------------------------*
83  * Generic routines to convert between a POSIX date
84  * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
85  * Derived from NetBSD arch/hp300/hp300/clock.c
86  */
87 
88 
89 #define	FEBRUARY	2
90 #define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
91 #define	days_in_month(y, m) \
92 	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
93 /* Day of week. Days are counted from 1/1/1970, which was a Thursday */
94 #define	day_of_week(days)	(((days) + 4) % 7)
95 
96 static const int month_days[12] = {
97 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
98 };
99 
100 /*
101  * Optimization: using a precomputed count of days between POSIX_BASE_YEAR and
102  * some recent year avoids lots of unnecessary loop iterations in conversion.
103  * recent_base_days is the number of days before the start of recent_base_year.
104  */
105 static const int recent_base_year = 2017;
106 static const int recent_base_days = 17167;
107 
108 /*
109  * This inline avoids some unnecessary modulo operations
110  * as compared with the usual macro:
111  *   ( ((year % 4) == 0 &&
112  *      (year % 100) != 0) ||
113  *     ((year % 400) == 0) )
114  * It is otherwise equivalent.
115  */
116 static int
117 leapyear(int year)
118 {
119 	int rv = 0;
120 
121 	if ((year & 3) == 0) {
122 		rv = 1;
123 		if ((year % 100) == 0) {
124 			rv = 0;
125 			if ((year % 400) == 0)
126 				rv = 1;
127 		}
128 	}
129 	return (rv);
130 }
131 
132 static void
133 print_ct(struct clocktime *ct)
134 {
135 	printf("[%04d-%02d-%02d %02d:%02d:%02d]",
136 	    ct->year, ct->mon, ct->day,
137 	    ct->hour, ct->min, ct->sec);
138 }
139 
140 int
141 clock_ct_to_ts(struct clocktime *ct, struct timespec *ts)
142 {
143 	int i, year, days;
144 
145 	if (ct_debug) {
146 		printf("ct_to_ts(");
147 		print_ct(ct);
148 		printf(")");
149 	}
150 
151 	/*
152 	 * Many realtime clocks store the year as 2-digit BCD; pivot on 70 to
153 	 * determine century.  Some clocks have a "century bit" and drivers do
154 	 * year += 100, so interpret values between 70-199 as relative to 1900.
155 	 */
156 	year = ct->year;
157 	if (year < 70)
158 		year += 2000;
159 	else if (year < 200)
160 		year += 1900;
161 
162 	/* Sanity checks. */
163 	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
164 	    ct->day > days_in_month(year, ct->mon) ||
165 	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 || year < 1970 ||
166 	    (sizeof(time_t) == 4 && year > 2037)) {	/* time_t overflow */
167 		if (ct_debug)
168 			printf(" = EINVAL\n");
169 		return (EINVAL);
170 	}
171 
172 	/*
173 	 * Compute days since start of time
174 	 * First from years, then from months.
175 	 */
176 	if (year >= recent_base_year) {
177 		i = recent_base_year;
178 		days = recent_base_days;
179 	} else {
180 		i = POSIX_BASE_YEAR;
181 		days = 0;
182 	}
183 	for (; i < year; i++)
184 		days += days_in_year(i);
185 
186 	/* Months */
187 	for (i = 1; i < ct->mon; i++)
188 	  	days += days_in_month(year, i);
189 	days += (ct->day - 1);
190 
191 	ts->tv_sec = (((time_t)days * 24 + ct->hour) * 60 + ct->min) * 60 +
192 	    ct->sec;
193 	ts->tv_nsec = ct->nsec;
194 
195 	if (ct_debug)
196 		printf(" = %jd.%09ld\n", (intmax_t)ts->tv_sec, ts->tv_nsec);
197 	return (0);
198 }
199 
200 void
201 clock_ts_to_ct(struct timespec *ts, struct clocktime *ct)
202 {
203 	time_t i, year, days;
204 	time_t rsec;	/* remainder seconds */
205 	time_t secs;
206 
207 	secs = ts->tv_sec;
208 	days = secs / SECDAY;
209 	rsec = secs % SECDAY;
210 
211 	ct->dow = day_of_week(days);
212 
213 	/* Subtract out whole years. */
214 	if (days >= recent_base_days) {
215 		year = recent_base_year;
216 		days -= recent_base_days;
217 	} else {
218 		year = POSIX_BASE_YEAR;
219 	}
220 	for (; days >= days_in_year(year); year++)
221 		days -= days_in_year(year);
222 	ct->year = year;
223 
224 	/* Subtract out whole months, counting them in i. */
225 	for (i = 1; days >= days_in_month(year, i); i++)
226 		days -= days_in_month(year, i);
227 	ct->mon = i;
228 
229 	/* Days are what is left over (+1) from all that. */
230 	ct->day = days + 1;
231 
232 	/* Hours, minutes, seconds are easy */
233 	ct->hour = rsec / 3600;
234 	rsec = rsec % 3600;
235 	ct->min  = rsec / 60;
236 	rsec = rsec % 60;
237 	ct->sec  = rsec;
238 	ct->nsec = ts->tv_nsec;
239 	if (ct_debug) {
240 		printf("ts_to_ct(%jd.%09ld) = ",
241 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
242 		print_ct(ct);
243 		printf("\n");
244 	}
245 
246 	KASSERT(ct->year >= 0 && ct->year < 10000,
247 	    ("year %d isn't a 4 digit year", ct->year));
248 	KASSERT(ct->mon >= 1 && ct->mon <= 12,
249 	    ("month %d not in 1-12", ct->mon));
250 	KASSERT(ct->day >= 1 && ct->day <= 31,
251 	    ("day %d not in 1-31", ct->day));
252 	KASSERT(ct->hour >= 0 && ct->hour <= 23,
253 	    ("hour %d not in 0-23", ct->hour));
254 	KASSERT(ct->min >= 0 && ct->min <= 59,
255 	    ("minute %d not in 0-59", ct->min));
256 	/* Not sure if this interface needs to handle leapseconds or not. */
257 	KASSERT(ct->sec >= 0 && ct->sec <= 60,
258 	    ("seconds %d not in 0-60", ct->sec));
259 }
260 
261 int
262 utc_offset(void)
263 {
264 
265 	return (tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0));
266 }
267