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 * 4. 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: stable/11/sys/kern/subr_clock.c 331722 2018-03-29 02:50:57Z eadler $");
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
53int tz_minuteswest;
54int 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 */
60static int adjkerntz;
61static int
62sysctl_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}
70SYSCTL_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
74static int ct_debug;
75SYSCTL_INT(_debug, OID_AUTO, clocktime, CTLFLAG_RWTUN,
76    &ct_debug, 0, "Enable printing of clocktime debugging");
77
78static int wall_cmos_clock;
79SYSCTL_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
96static 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 */
105static const int recent_base_year = 2017;
106static const int recent_base_days = 17167;
107
108/*
109 * Table to 'calculate' pow(10, 9 - nsdigits) via lookup of nsdigits.
110 * Before doing the lookup, the code asserts 0 <= nsdigits <= 9.
111 */
112static u_int nsdivisors[] = {
113    1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1
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 */
124static int
125leapyear(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
140int
141clock_ct_to_ts(const struct clocktime *ct, struct timespec *ts)
142{
143	int i, year, days;
144
145	if (ct_debug) {
146		printf("ct_to_ts([");
147		clock_print_ct(ct, 9);
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
200int
201clock_bcd_to_ts(const struct bcd_clocktime *bct, struct timespec *ts, bool ampm)
202{
203	struct clocktime ct;
204	int bcent, byear;
205
206	/*
207	 * Year may come in as 2-digit or 4-digit BCD.  Split the value into
208	 * separate BCD century and year values for validation and conversion.
209	 */
210	bcent = bct->year >> 8;
211	byear = bct->year & 0xff;
212
213	/*
214	 * Ensure that all values are valid BCD numbers, to avoid assertions in
215	 * the BCD-to-binary conversion routines.  clock_ct_to_ts() will further
216	 * validate the field ranges (such as 0 <= min <= 59) during conversion.
217	 */
218	if (!validbcd(bcent) || !validbcd(byear) || !validbcd(bct->mon) ||
219	    !validbcd(bct->day) || !validbcd(bct->hour) ||
220	    !validbcd(bct->min) || !validbcd(bct->sec)) {
221		if (ct_debug)
222			printf("clock_bcd_to_ts: bad BCD: "
223			    "[%04x-%02x-%02x %02x:%02x:%02x]\n",
224			    bct->year, bct->mon, bct->day,
225			    bct->hour, bct->min, bct->sec);
226		return (EINVAL);
227	}
228
229	ct.year = FROMBCD(byear) + FROMBCD(bcent) * 100;
230	ct.mon  = FROMBCD(bct->mon);
231	ct.day  = FROMBCD(bct->day);
232	ct.hour = FROMBCD(bct->hour);
233	ct.min  = FROMBCD(bct->min);
234	ct.sec  = FROMBCD(bct->sec);
235	ct.dow  = bct->dow;
236	ct.nsec = bct->nsec;
237
238	/* If asked to handle am/pm, convert from 12hr+pmflag to 24hr. */
239	if (ampm) {
240		if (ct.hour == 12)
241			ct.hour = 0;
242		if (bct->ispm)
243			ct.hour += 12;
244	}
245
246	return (clock_ct_to_ts(&ct, ts));
247}
248
249void
250clock_ts_to_ct(const struct timespec *ts, struct clocktime *ct)
251{
252	int i, year, days;
253	time_t rsec;	/* remainder seconds */
254	time_t secs;
255
256	secs = ts->tv_sec;
257	days = secs / SECDAY;
258	rsec = secs % SECDAY;
259
260	ct->dow = day_of_week(days);
261
262	/* Subtract out whole years. */
263	if (days >= recent_base_days) {
264		year = recent_base_year;
265		days -= recent_base_days;
266	} else {
267		year = POSIX_BASE_YEAR;
268	}
269	for (; days >= days_in_year(year); year++)
270		days -= days_in_year(year);
271	ct->year = year;
272
273	/* Subtract out whole months, counting them in i. */
274	for (i = 1; days >= days_in_month(year, i); i++)
275		days -= days_in_month(year, i);
276	ct->mon = i;
277
278	/* Days are what is left over (+1) from all that. */
279	ct->day = days + 1;
280
281	/* Hours, minutes, seconds are easy */
282	ct->hour = rsec / 3600;
283	rsec = rsec % 3600;
284	ct->min  = rsec / 60;
285	rsec = rsec % 60;
286	ct->sec  = rsec;
287	ct->nsec = ts->tv_nsec;
288	if (ct_debug) {
289		printf("ts_to_ct(%jd.%09ld) = [",
290		    (intmax_t)ts->tv_sec, ts->tv_nsec);
291		clock_print_ct(ct, 9);
292		printf("]\n");
293	}
294}
295
296void
297clock_ts_to_bcd(const struct timespec *ts, struct bcd_clocktime *bct, bool ampm)
298{
299	struct clocktime ct;
300
301	clock_ts_to_ct(ts, &ct);
302
303	/* If asked to handle am/pm, convert from 24hr to 12hr+pmflag. */
304	bct->ispm = false;
305	if (ampm) {
306		if (ct.hour >= 12) {
307			ct.hour -= 12;
308			bct->ispm = true;
309		}
310		if (ct.hour == 0)
311			ct.hour = 12;
312	}
313
314	bct->year = TOBCD(ct.year % 100) | (TOBCD(ct.year / 100) << 8);
315	bct->mon  = TOBCD(ct.mon);
316	bct->day  = TOBCD(ct.day);
317	bct->hour = TOBCD(ct.hour);
318	bct->min  = TOBCD(ct.min);
319	bct->sec  = TOBCD(ct.sec);
320	bct->dow  = ct.dow;
321	bct->nsec = ct.nsec;
322}
323
324void
325clock_print_bcd(const struct bcd_clocktime *bct, int nsdigits)
326{
327
328	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
329
330	if (nsdigits > 0) {
331		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x.%*.*ld",
332		    bct->year, bct->mon, bct->day,
333		    bct->hour, bct->min, bct->sec,
334		    nsdigits, nsdigits, bct->nsec / nsdivisors[nsdigits]);
335	} else {
336		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x",
337		    bct->year, bct->mon, bct->day,
338		    bct->hour, bct->min, bct->sec);
339	}
340}
341
342void
343clock_print_ct(const struct clocktime *ct, int nsdigits)
344{
345
346	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
347
348	if (nsdigits > 0) {
349		printf("%04d-%02d-%02d %02d:%02d:%02d.%*.*ld",
350		    ct->year, ct->mon, ct->day,
351		    ct->hour, ct->min, ct->sec,
352		    nsdigits, nsdigits, ct->nsec / nsdivisors[nsdigits]);
353	} else {
354		printf("%04d-%02d-%02d %02d:%02d:%02d",
355		    ct->year, ct->mon, ct->day,
356		    ct->hour, ct->min, ct->sec);
357	}
358}
359
360void
361clock_print_ts(const struct timespec *ts, int nsdigits)
362{
363	struct clocktime ct;
364
365	clock_ts_to_ct(ts, &ct);
366	clock_print_ct(&ct, nsdigits);
367}
368
369int
370utc_offset(void)
371{
372
373	return (tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0));
374}
375