xref: /freebsd/sys/kern/subr_clock.c (revision cddbc3b40812213ff00041f79174cac0be360a2a)
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: @(#)clock.c	8.2 (Berkeley) 1/12/94
38  *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
39  *	and
40  *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
41  */
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/bus.h>
50 #include <sys/clock.h>
51 #include <sys/limits.h>
52 #include <sys/sysctl.h>
53 #include <sys/timetc.h>
54 
55 /*
56  * The adjkerntz and wall_cmos_clock sysctls are in the "machdep" sysctl
57  * namespace because they were misplaced there originally.
58  */
59 static int adjkerntz;
60 static int
61 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
62 {
63 	int error;
64 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
65 	if (!error && req->newptr)
66 		resettodr();
67 	return (error);
68 }
69 SYSCTL_PROC(_machdep, OID_AUTO, adjkerntz, CTLTYPE_INT | CTLFLAG_RW |
70     CTLFLAG_MPSAFE, &adjkerntz, 0, sysctl_machdep_adjkerntz, "I",
71     "Local offset from UTC in seconds");
72 
73 static int ct_debug;
74 SYSCTL_INT(_debug, OID_AUTO, clocktime, CTLFLAG_RWTUN,
75     &ct_debug, 0, "Enable printing of clocktime debugging");
76 
77 static int wall_cmos_clock;
78 SYSCTL_INT(_machdep, OID_AUTO, wall_cmos_clock, CTLFLAG_RW,
79     &wall_cmos_clock, 0, "Enables application of machdep.adjkerntz");
80 
81 /*--------------------------------------------------------------------*
82  * Generic routines to convert between a POSIX date
83  * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
84  * Derived from NetBSD arch/hp300/hp300/clock.c
85  */
86 
87 
88 #define	FEBRUARY	2
89 #define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
90 #define	days_in_month(y, m) \
91 	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
92 /* Day of week. Days are counted from 1/1/1970, which was a Thursday */
93 #define	day_of_week(days)	(((days) + 4) % 7)
94 
95 static const int month_days[12] = {
96 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
97 };
98 
99 /*
100  * Optimization: using a precomputed count of days between POSIX_BASE_YEAR and
101  * some recent year avoids lots of unnecessary loop iterations in conversion.
102  * recent_base_days is the number of days before the start of recent_base_year.
103  */
104 static const int recent_base_year = 2017;
105 static const int recent_base_days = 17167;
106 
107 /*
108  * Table to 'calculate' pow(10, 9 - nsdigits) via lookup of nsdigits.
109  * Before doing the lookup, the code asserts 0 <= nsdigits <= 9.
110  */
111 static u_int nsdivisors[] = {
112     1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1
113 };
114 
115 /*
116  * This inline avoids some unnecessary modulo operations
117  * as compared with the usual macro:
118  *   ( ((year % 4) == 0 &&
119  *      (year % 100) != 0) ||
120  *     ((year % 400) == 0) )
121  * It is otherwise equivalent.
122  */
123 static int
124 leapyear(int year)
125 {
126 	int rv = 0;
127 
128 	if ((year & 3) == 0) {
129 		rv = 1;
130 		if ((year % 100) == 0) {
131 			rv = 0;
132 			if ((year % 400) == 0)
133 				rv = 1;
134 		}
135 	}
136 	return (rv);
137 }
138 
139 int
140 clock_ct_to_ts(const struct clocktime *ct, struct timespec *ts)
141 {
142 	int i, year, days;
143 
144 	if (ct_debug) {
145 		printf("ct_to_ts([");
146 		clock_print_ct(ct, 9);
147 		printf("])");
148 	}
149 
150 	/*
151 	 * Many realtime clocks store the year as 2-digit BCD; pivot on 70 to
152 	 * determine century.  Some clocks have a "century bit" and drivers do
153 	 * year += 100, so interpret values between 70-199 as relative to 1900.
154 	 */
155 	year = ct->year;
156 	if (year < 70)
157 		year += 2000;
158 	else if (year < 200)
159 		year += 1900;
160 
161 	/* Sanity checks. */
162 	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
163 	    ct->day > days_in_month(year, ct->mon) ||
164 	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 || year < 1970 ||
165 	    (sizeof(time_t) == 4 && year > 2037)) {	/* time_t overflow */
166 		if (ct_debug)
167 			printf(" = EINVAL\n");
168 		return (EINVAL);
169 	}
170 
171 	/*
172 	 * Compute days since start of time
173 	 * First from years, then from months.
174 	 */
175 	if (year >= recent_base_year) {
176 		i = recent_base_year;
177 		days = recent_base_days;
178 	} else {
179 		i = POSIX_BASE_YEAR;
180 		days = 0;
181 	}
182 	for (; i < year; i++)
183 		days += days_in_year(i);
184 
185 	/* Months */
186 	for (i = 1; i < ct->mon; i++)
187 	  	days += days_in_month(year, i);
188 	days += (ct->day - 1);
189 
190 	ts->tv_sec = (((time_t)days * 24 + ct->hour) * 60 + ct->min) * 60 +
191 	    ct->sec;
192 	ts->tv_nsec = ct->nsec;
193 
194 	if (ct_debug)
195 		printf(" = %jd.%09ld\n", (intmax_t)ts->tv_sec, ts->tv_nsec);
196 	return (0);
197 }
198 
199 int
200 clock_bcd_to_ts(const struct bcd_clocktime *bct, struct timespec *ts, bool ampm)
201 {
202 	struct clocktime ct;
203 	int bcent, byear;
204 
205 	/*
206 	 * Year may come in as 2-digit or 4-digit BCD.  Split the value into
207 	 * separate BCD century and year values for validation and conversion.
208 	 */
209 	bcent = bct->year >> 8;
210 	byear = bct->year & 0xff;
211 
212 	/*
213 	 * Ensure that all values are valid BCD numbers, to avoid assertions in
214 	 * the BCD-to-binary conversion routines.  clock_ct_to_ts() will further
215 	 * validate the field ranges (such as 0 <= min <= 59) during conversion.
216 	 */
217 	if (!validbcd(bcent) || !validbcd(byear) || !validbcd(bct->mon) ||
218 	    !validbcd(bct->day) || !validbcd(bct->hour) ||
219 	    !validbcd(bct->min) || !validbcd(bct->sec)) {
220 		if (ct_debug)
221 			printf("clock_bcd_to_ts: bad BCD: "
222 			    "[%04x-%02x-%02x %02x:%02x:%02x]\n",
223 			    bct->year, bct->mon, bct->day,
224 			    bct->hour, bct->min, bct->sec);
225 		return (EINVAL);
226 	}
227 
228 	ct.year = FROMBCD(byear) + FROMBCD(bcent) * 100;
229 	ct.mon  = FROMBCD(bct->mon);
230 	ct.day  = FROMBCD(bct->day);
231 	ct.hour = FROMBCD(bct->hour);
232 	ct.min  = FROMBCD(bct->min);
233 	ct.sec  = FROMBCD(bct->sec);
234 	ct.dow  = bct->dow;
235 	ct.nsec = bct->nsec;
236 
237 	/* If asked to handle am/pm, convert from 12hr+pmflag to 24hr. */
238 	if (ampm) {
239 		if (ct.hour == 12)
240 			ct.hour = 0;
241 		if (bct->ispm)
242 			ct.hour += 12;
243 	}
244 
245 	return (clock_ct_to_ts(&ct, ts));
246 }
247 
248 void
249 clock_ts_to_ct(const struct timespec *ts, struct clocktime *ct)
250 {
251 	time_t i, year, days;
252 	time_t rsec;	/* remainder seconds */
253 	time_t secs;
254 
255 	secs = ts->tv_sec;
256 	days = secs / SECDAY;
257 	rsec = secs % SECDAY;
258 
259 	ct->dow = day_of_week(days);
260 
261 	/* Subtract out whole years. */
262 	if (days >= recent_base_days) {
263 		year = recent_base_year;
264 		days -= recent_base_days;
265 	} else {
266 		year = POSIX_BASE_YEAR;
267 	}
268 	for (; days >= days_in_year(year); year++)
269 		days -= days_in_year(year);
270 	ct->year = year;
271 
272 	/* Subtract out whole months, counting them in i. */
273 	for (i = 1; days >= days_in_month(year, i); i++)
274 		days -= days_in_month(year, i);
275 	ct->mon = i;
276 
277 	/* Days are what is left over (+1) from all that. */
278 	ct->day = days + 1;
279 
280 	/* Hours, minutes, seconds are easy */
281 	ct->hour = rsec / 3600;
282 	rsec = rsec % 3600;
283 	ct->min  = rsec / 60;
284 	rsec = rsec % 60;
285 	ct->sec  = rsec;
286 	ct->nsec = ts->tv_nsec;
287 	if (ct_debug) {
288 		printf("ts_to_ct(%jd.%09ld) = [",
289 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
290 		clock_print_ct(ct, 9);
291 		printf("]\n");
292 	}
293 
294 	KASSERT(ct->year >= 0 && ct->year < 10000,
295 	    ("year %d isn't a 4 digit year", ct->year));
296 	KASSERT(ct->mon >= 1 && ct->mon <= 12,
297 	    ("month %d not in 1-12", ct->mon));
298 	KASSERT(ct->day >= 1 && ct->day <= 31,
299 	    ("day %d not in 1-31", ct->day));
300 	KASSERT(ct->hour >= 0 && ct->hour <= 23,
301 	    ("hour %d not in 0-23", ct->hour));
302 	KASSERT(ct->min >= 0 && ct->min <= 59,
303 	    ("minute %d not in 0-59", ct->min));
304 	/* Not sure if this interface needs to handle leapseconds or not. */
305 	KASSERT(ct->sec >= 0 && ct->sec <= 60,
306 	    ("seconds %d not in 0-60", ct->sec));
307 }
308 
309 void
310 clock_ts_to_bcd(const struct timespec *ts, struct bcd_clocktime *bct, bool ampm)
311 {
312 	struct clocktime ct;
313 
314 	clock_ts_to_ct(ts, &ct);
315 
316 	/* If asked to handle am/pm, convert from 24hr to 12hr+pmflag. */
317 	bct->ispm = false;
318 	if (ampm) {
319 		if (ct.hour >= 12) {
320 			ct.hour -= 12;
321 			bct->ispm = true;
322 		}
323 		if (ct.hour == 0)
324 			ct.hour = 12;
325 	}
326 
327 	bct->year = TOBCD(ct.year % 100) | (TOBCD(ct.year / 100) << 8);
328 	bct->mon  = TOBCD(ct.mon);
329 	bct->day  = TOBCD(ct.day);
330 	bct->hour = TOBCD(ct.hour);
331 	bct->min  = TOBCD(ct.min);
332 	bct->sec  = TOBCD(ct.sec);
333 	bct->dow  = ct.dow;
334 	bct->nsec = ct.nsec;
335 }
336 
337 void
338 clock_print_bcd(const struct bcd_clocktime *bct, int nsdigits)
339 {
340 
341 	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
342 
343 	if (nsdigits > 0) {
344 		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x.%*.*ld",
345 		    bct->year, bct->mon, bct->day,
346 		    bct->hour, bct->min, bct->sec,
347 		    nsdigits, nsdigits, bct->nsec / nsdivisors[nsdigits]);
348 	} else {
349 		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x",
350 		    bct->year, bct->mon, bct->day,
351 		    bct->hour, bct->min, bct->sec);
352 	}
353 }
354 
355 void
356 clock_print_ct(const struct clocktime *ct, int nsdigits)
357 {
358 
359 	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
360 
361 	if (nsdigits > 0) {
362 		printf("%04d-%02d-%02d %02d:%02d:%02d.%*.*ld",
363 		    ct->year, ct->mon, ct->day,
364 		    ct->hour, ct->min, ct->sec,
365 		    nsdigits, nsdigits, ct->nsec / nsdivisors[nsdigits]);
366 	} else {
367 		printf("%04d-%02d-%02d %02d:%02d:%02d",
368 		    ct->year, ct->mon, ct->day,
369 		    ct->hour, ct->min, ct->sec);
370 	}
371 }
372 
373 void
374 clock_print_ts(const struct timespec *ts, int nsdigits)
375 {
376 	struct clocktime ct;
377 
378 	clock_ts_to_ct(ts, &ct);
379 	clock_print_ct(&ct, nsdigits);
380 }
381 
382 int
383 utc_offset(void)
384 {
385 
386 	return (wall_cmos_clock ? adjkerntz : 0);
387 }
388