xref: /freebsd/sys/kern/subr_clock.c (revision a2f733abcff64628b7771a47089628b7327a88bd)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1988 University of Utah.
5  * Copyright (c) 1982, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * the Systems Programming Group of the University of Utah Computer
10  * Science Department.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: Utah $Hdr: clock.c 1.18 91/01/21$
37  *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
38  *	and
39  *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
40  */
41 
42 #include <sys/cdefs.h>
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/bus.h>
47 #include <sys/clock.h>
48 #include <sys/limits.h>
49 #include <sys/sysctl.h>
50 #include <sys/timetc.h>
51 
52 /*
53  * The adjkerntz and wall_cmos_clock sysctls are in the "machdep" sysctl
54  * namespace because they were misplaced there originally.
55  */
56 static int adjkerntz;
57 static int
58 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
59 {
60 	int error;
61 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
62 	if (!error && req->newptr)
63 		resettodr();
64 	return (error);
65 }
66 SYSCTL_PROC(_machdep, OID_AUTO, adjkerntz, CTLTYPE_INT | CTLFLAG_RW |
67     CTLFLAG_MPSAFE, &adjkerntz, 0, sysctl_machdep_adjkerntz, "I",
68     "Local offset from UTC in seconds");
69 
70 static int ct_debug;
71 SYSCTL_INT(_debug, OID_AUTO, clocktime, CTLFLAG_RWTUN,
72     &ct_debug, 0, "Enable printing of clocktime debugging");
73 
74 static int wall_cmos_clock;
75 SYSCTL_INT(_machdep, OID_AUTO, wall_cmos_clock, CTLFLAG_RW,
76     &wall_cmos_clock, 0, "Enables application of machdep.adjkerntz");
77 
78 /*--------------------------------------------------------------------*
79  * Generic routines to convert between a POSIX date
80  * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
81  * Derived from NetBSD arch/hp300/hp300/clock.c
82  */
83 
84 #define	FEBRUARY	2
85 #define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
86 #define	days_in_month(y, m) \
87 	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
88 /* Day of week. Days are counted from 1/1/1970, which was a Thursday */
89 #define	day_of_week(days)	(((days) + 4) % 7)
90 
91 static const int month_days[12] = {
92 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
93 };
94 
95 /*
96  * Optimization: using a precomputed count of days between POSIX_BASE_YEAR and
97  * some recent year avoids lots of unnecessary loop iterations in conversion.
98  * recent_base_days is the number of days before the start of recent_base_year.
99  */
100 static const int recent_base_year = 2017;
101 static const int recent_base_days = 17167;
102 
103 /*
104  * Table to 'calculate' pow(10, 9 - nsdigits) via lookup of nsdigits.
105  * Before doing the lookup, the code asserts 0 <= nsdigits <= 9.
106  */
107 static u_int nsdivisors[] = {
108     1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1
109 };
110 
111 /*
112  * This inline avoids some unnecessary modulo operations
113  * as compared with the usual macro:
114  *   ( ((year % 4) == 0 &&
115  *      (year % 100) != 0) ||
116  *     ((year % 400) == 0) )
117  * It is otherwise equivalent.
118  */
119 static int
120 leapyear(int year)
121 {
122 	int rv = 0;
123 
124 	if ((year & 3) == 0) {
125 		rv = 1;
126 		if ((year % 100) == 0) {
127 			rv = 0;
128 			if ((year % 400) == 0)
129 				rv = 1;
130 		}
131 	}
132 	return (rv);
133 }
134 
135 int
136 clock_ct_to_ts(const struct clocktime *ct, struct timespec *ts)
137 {
138 	int i, year, days;
139 
140 	if (ct_debug) {
141 		printf("ct_to_ts([");
142 		clock_print_ct(ct, 9);
143 		printf("])");
144 	}
145 
146 	/*
147 	 * Many realtime clocks store the year as 2-digit BCD; pivot on 70 to
148 	 * determine century.  Some clocks have a "century bit" and drivers do
149 	 * year += 100, so interpret values between 70-199 as relative to 1900.
150 	 */
151 	year = ct->year;
152 	if (year < 70)
153 		year += 2000;
154 	else if (year < 200)
155 		year += 1900;
156 
157 	/* Sanity checks. */
158 	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
159 	    ct->day > days_in_month(year, ct->mon) ||
160 	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 || year < 1970 ||
161 	    (sizeof(time_t) == 4 && year > 2037)) {	/* time_t overflow */
162 		if (ct_debug)
163 			printf(" = EINVAL\n");
164 		return (EINVAL);
165 	}
166 
167 	/*
168 	 * Compute days since start of time
169 	 * First from years, then from months.
170 	 */
171 	if (year >= recent_base_year) {
172 		i = recent_base_year;
173 		days = recent_base_days;
174 	} else {
175 		i = POSIX_BASE_YEAR;
176 		days = 0;
177 	}
178 	for (; i < year; i++)
179 		days += days_in_year(i);
180 
181 	/* Months */
182 	for (i = 1; i < ct->mon; i++)
183 	  	days += days_in_month(year, i);
184 	days += (ct->day - 1);
185 
186 	ts->tv_sec = (((time_t)days * 24 + ct->hour) * 60 + ct->min) * 60 +
187 	    ct->sec;
188 	ts->tv_nsec = ct->nsec;
189 
190 	if (ct_debug)
191 		printf(" = %jd.%09ld\n", (intmax_t)ts->tv_sec, ts->tv_nsec);
192 	return (0);
193 }
194 
195 int
196 clock_bcd_to_ts(const struct bcd_clocktime *bct, struct timespec *ts, bool ampm)
197 {
198 	struct clocktime ct;
199 	int bcent, byear;
200 
201 	/*
202 	 * Year may come in as 2-digit or 4-digit BCD.  Split the value into
203 	 * separate BCD century and year values for validation and conversion.
204 	 */
205 	bcent = bct->year >> 8;
206 	byear = bct->year & 0xff;
207 
208 	/*
209 	 * Ensure that all values are valid BCD numbers, to avoid assertions in
210 	 * the BCD-to-binary conversion routines.  clock_ct_to_ts() will further
211 	 * validate the field ranges (such as 0 <= min <= 59) during conversion.
212 	 */
213 	if (!validbcd(bcent) || !validbcd(byear) || !validbcd(bct->mon) ||
214 	    !validbcd(bct->day) || !validbcd(bct->hour) ||
215 	    !validbcd(bct->min) || !validbcd(bct->sec)) {
216 		if (ct_debug)
217 			printf("clock_bcd_to_ts: bad BCD: "
218 			    "[%04x-%02x-%02x %02x:%02x:%02x]\n",
219 			    bct->year, bct->mon, bct->day,
220 			    bct->hour, bct->min, bct->sec);
221 		return (EINVAL);
222 	}
223 
224 	ct.year = FROMBCD(byear) + FROMBCD(bcent) * 100;
225 	ct.mon  = FROMBCD(bct->mon);
226 	ct.day  = FROMBCD(bct->day);
227 	ct.hour = FROMBCD(bct->hour);
228 	ct.min  = FROMBCD(bct->min);
229 	ct.sec  = FROMBCD(bct->sec);
230 	ct.dow  = bct->dow;
231 	ct.nsec = bct->nsec;
232 
233 	/* If asked to handle am/pm, convert from 12hr+pmflag to 24hr. */
234 	if (ampm) {
235 		if (ct.hour == 12)
236 			ct.hour = 0;
237 		if (bct->ispm)
238 			ct.hour += 12;
239 	}
240 
241 	return (clock_ct_to_ts(&ct, ts));
242 }
243 
244 void
245 clock_ts_to_ct(const struct timespec *ts, struct clocktime *ct)
246 {
247 	time_t i, year, days;
248 	time_t rsec;	/* remainder seconds */
249 	time_t secs;
250 
251 	secs = ts->tv_sec;
252 	days = secs / SECDAY;
253 	rsec = secs % SECDAY;
254 
255 	ct->dow = day_of_week(days);
256 
257 	/* Subtract out whole years. */
258 	if (days >= recent_base_days) {
259 		year = recent_base_year;
260 		days -= recent_base_days;
261 	} else {
262 		year = POSIX_BASE_YEAR;
263 	}
264 	for (; days >= days_in_year(year); year++)
265 		days -= days_in_year(year);
266 	ct->year = year;
267 
268 	/* Subtract out whole months, counting them in i. */
269 	for (i = 1; days >= days_in_month(year, i); i++)
270 		days -= days_in_month(year, i);
271 	ct->mon = i;
272 
273 	/* Days are what is left over (+1) from all that. */
274 	ct->day = days + 1;
275 
276 	/* Hours, minutes, seconds are easy */
277 	ct->hour = rsec / 3600;
278 	rsec = rsec % 3600;
279 	ct->min  = rsec / 60;
280 	rsec = rsec % 60;
281 	ct->sec  = rsec;
282 	ct->nsec = ts->tv_nsec;
283 	if (ct_debug) {
284 		printf("ts_to_ct(%jd.%09ld) = [",
285 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
286 		clock_print_ct(ct, 9);
287 		printf("]\n");
288 	}
289 
290 	KASSERT(ct->year >= 0 && ct->year < 10000,
291 	    ("year %d isn't a 4 digit year", ct->year));
292 	KASSERT(ct->mon >= 1 && ct->mon <= 12,
293 	    ("month %d not in 1-12", ct->mon));
294 	KASSERT(ct->day >= 1 && ct->day <= 31,
295 	    ("day %d not in 1-31", ct->day));
296 	KASSERT(ct->hour >= 0 && ct->hour <= 23,
297 	    ("hour %d not in 0-23", ct->hour));
298 	KASSERT(ct->min >= 0 && ct->min <= 59,
299 	    ("minute %d not in 0-59", ct->min));
300 	/* Not sure if this interface needs to handle leapseconds or not. */
301 	KASSERT(ct->sec >= 0 && ct->sec <= 60,
302 	    ("seconds %d not in 0-60", ct->sec));
303 }
304 
305 void
306 clock_ts_to_bcd(const struct timespec *ts, struct bcd_clocktime *bct, bool ampm)
307 {
308 	struct clocktime ct;
309 
310 	clock_ts_to_ct(ts, &ct);
311 
312 	/* If asked to handle am/pm, convert from 24hr to 12hr+pmflag. */
313 	bct->ispm = false;
314 	if (ampm) {
315 		if (ct.hour >= 12) {
316 			ct.hour -= 12;
317 			bct->ispm = true;
318 		}
319 		if (ct.hour == 0)
320 			ct.hour = 12;
321 	}
322 
323 	bct->year = TOBCD(ct.year % 100) | (TOBCD(ct.year / 100) << 8);
324 	bct->mon  = TOBCD(ct.mon);
325 	bct->day  = TOBCD(ct.day);
326 	bct->hour = TOBCD(ct.hour);
327 	bct->min  = TOBCD(ct.min);
328 	bct->sec  = TOBCD(ct.sec);
329 	bct->dow  = ct.dow;
330 	bct->nsec = ct.nsec;
331 }
332 
333 void
334 clock_print_bcd(const struct bcd_clocktime *bct, int nsdigits)
335 {
336 
337 	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
338 
339 	if (nsdigits > 0) {
340 		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x.%*.*ld",
341 		    bct->year, bct->mon, bct->day,
342 		    bct->hour, bct->min, bct->sec,
343 		    nsdigits, nsdigits, bct->nsec / nsdivisors[nsdigits]);
344 	} else {
345 		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x",
346 		    bct->year, bct->mon, bct->day,
347 		    bct->hour, bct->min, bct->sec);
348 	}
349 }
350 
351 void
352 clock_print_ct(const struct clocktime *ct, int nsdigits)
353 {
354 
355 	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
356 
357 	if (nsdigits > 0) {
358 		printf("%04d-%02d-%02d %02d:%02d:%02d.%*.*ld",
359 		    ct->year, ct->mon, ct->day,
360 		    ct->hour, ct->min, ct->sec,
361 		    nsdigits, nsdigits, ct->nsec / nsdivisors[nsdigits]);
362 	} else {
363 		printf("%04d-%02d-%02d %02d:%02d:%02d",
364 		    ct->year, ct->mon, ct->day,
365 		    ct->hour, ct->min, ct->sec);
366 	}
367 }
368 
369 void
370 clock_print_ts(const struct timespec *ts, int nsdigits)
371 {
372 	struct clocktime ct;
373 
374 	clock_ts_to_ct(ts, &ct);
375 	clock_print_ct(&ct, nsdigits);
376 }
377 
378 int
379 utc_offset(void)
380 {
381 
382 	return (wall_cmos_clock ? adjkerntz : 0);
383 }
384