155714Skris/*-
255714Skris * SPDX-License-Identifier: BSD-3-Clause
355714Skris *
4280304Sjkim * Copyright (c) 1988 University of Utah.
5280304Sjkim * Copyright (c) 1982, 1990, 1993
6280304Sjkim *	The Regents of the University of California.  All rights reserved.
755714Skris *
855714Skris * This code is derived from software contributed to Berkeley by
9280304Sjkim * the Systems Programming Group of the University of Utah Computer
1055714Skris * Science Department.
1155714Skris *
12280304Sjkim * Redistribution and use in source and binary forms, with or without
13280304Sjkim * modification, are permitted provided that the following conditions
14280304Sjkim * are met:
1555714Skris * 1. Redistributions of source code must retain the above copyright
1655714Skris *    notice, this list of conditions and the following disclaimer.
17280304Sjkim * 2. Redistributions in binary form must reproduce the above copyright
18280304Sjkim *    notice, this list of conditions and the following disclaimer in the
19280304Sjkim *    documentation and/or other materials provided with the distribution.
20280304Sjkim * 3. Neither the name of the University nor the names of its contributors
21280304Sjkim *    may be used to endorse or promote products derived from this software
22280304Sjkim *    without specific prior written permission.
2355714Skris *
2455714Skris * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2555714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2655714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27280304Sjkim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28280304Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29280304Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3055714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31280304Sjkim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32280304Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33280304Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34280304Sjkim * SUCH DAMAGE.
35280304Sjkim *
36280304Sjkim *	from: Utah $Hdr: clock.c 1.18 91/01/21$
37280304Sjkim *	from: NetBSD: clock_subr.c,v 1.6 2001/07/07 17:04:02 thorpej Exp
38280304Sjkim *	and
39280304Sjkim *	from: src/sys/i386/isa/clock.c,v 1.176 2001/09/04
40280304Sjkim */
41280304Sjkim
42280304Sjkim#include <sys/param.h>
43280304Sjkim#include <sys/systm.h>
44280304Sjkim#include <sys/kernel.h>
45280304Sjkim#include <sys/bus.h>
46280304Sjkim#include <sys/clock.h>
47280304Sjkim#include <sys/limits.h>
4855714Skris#include <sys/sysctl.h>
4955714Skris#include <sys/timetc.h>
50280304Sjkim
51280304Sjkim/*
52280304Sjkim * The adjkerntz and wall_cmos_clock sysctls are in the "machdep" sysctl
53280304Sjkim * namespace because they were misplaced there originally.
54280304Sjkim */
55280304Sjkimstatic int adjkerntz;
56280304Sjkimstatic int
57280304Sjkimsysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
58280304Sjkim{
5955714Skris	int error;
6055714Skris	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
61109998Smarkm	if (!error && req->newptr)
62280304Sjkim		resettodr();
63280304Sjkim	return (error);
6455714Skris}
6555714SkrisSYSCTL_PROC(_machdep, OID_AUTO, adjkerntz, CTLTYPE_INT | CTLFLAG_RW |
66280304Sjkim    CTLFLAG_MPSAFE, &adjkerntz, 0, sysctl_machdep_adjkerntz, "I",
6755714Skris    "Local offset from UTC in seconds");
68280304Sjkim
69280304Sjkimstatic int ct_debug;
70280304SjkimSYSCTL_INT(_debug, OID_AUTO, clocktime, CTLFLAG_RWTUN,
7155714Skris    &ct_debug, 0, "Enable printing of clocktime debugging");
72280304Sjkim
73280304Sjkimstatic int wall_cmos_clock;
74280304SjkimSYSCTL_INT(_machdep, OID_AUTO, wall_cmos_clock, CTLFLAG_RW,
7555714Skris    &wall_cmos_clock, 0, "Enables application of machdep.adjkerntz");
76280304Sjkim
77280304Sjkim/*--------------------------------------------------------------------*
7855714Skris * Generic routines to convert between a POSIX date
79280304Sjkim * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
80280304Sjkim * Derived from NetBSD arch/hp300/hp300/clock.c
8155714Skris */
82280304Sjkim
83280304Sjkim#define	FEBRUARY	2
8455714Skris#define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
85280304Sjkim#define	days_in_month(y, m) \
86280304Sjkim	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
8755714Skris/* Day of week. Days are counted from 1/1/1970, which was a Thursday */
88280304Sjkim#define	day_of_week(days)	(((days) + 4) % 7)
89280304Sjkim
9055714Skrisstatic const int month_days[12] = {
91280304Sjkim	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
92280304Sjkim};
93280304Sjkim
94280304Sjkim/*
9555714Skris * Optimization: using a precomputed count of days between POSIX_BASE_YEAR and
96280304Sjkim * some recent year avoids lots of unnecessary loop iterations in conversion.
9755714Skris * recent_base_days is the number of days before the start of recent_base_year.
98109998Smarkm */
99280304Sjkimstatic const int recent_base_year = 2017;
100280304Sjkimstatic const int recent_base_days = 17167;
101280304Sjkim
102280304Sjkim/*
103280304Sjkim * Table to 'calculate' pow(10, 9 - nsdigits) via lookup of nsdigits.
104280304Sjkim * Before doing the lookup, the code asserts 0 <= nsdigits <= 9.
105280304Sjkim */
106280304Sjkimstatic u_int nsdivisors[] = {
107280304Sjkim    1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1
10855714Skris};
109280304Sjkim
110280304Sjkim/*
111280304Sjkim * This inline avoids some unnecessary modulo operations
112280304Sjkim * as compared with the usual macro:
113280304Sjkim *   ( ((year % 4) == 0 &&
114280304Sjkim *      (year % 100) != 0) ||
115280304Sjkim *     ((year % 400) == 0) )
116280304Sjkim * It is otherwise equivalent.
11755714Skris */
118280304Sjkimstatic int
119280304Sjkimleapyear(int year)
120280304Sjkim{
121280304Sjkim	int rv = 0;
12255714Skris
123280304Sjkim	if ((year & 3) == 0) {
124280304Sjkim		rv = 1;
125280304Sjkim		if ((year % 100) == 0) {
126280304Sjkim			rv = 0;
12755714Skris			if ((year % 400) == 0)
12855714Skris				rv = 1;
129280304Sjkim		}
130280304Sjkim	}
131280304Sjkim	return (rv);
132280304Sjkim}
133280304Sjkim
134280304Sjkimint
135280304Sjkimclock_ct_to_ts(const struct clocktime *ct, struct timespec *ts)
136280304Sjkim{
137280304Sjkim	int i, year, days;
138280304Sjkim
139280304Sjkim	if (ct_debug) {
14055714Skris		printf("ct_to_ts([");
141280304Sjkim		clock_print_ct(ct, 9);
142280304Sjkim		printf("])");
14355714Skris	}
144280304Sjkim
145280304Sjkim	/*
146280304Sjkim	 * Many realtime clocks store the year as 2-digit BCD; pivot on 70 to
147280304Sjkim	 * determine century.  Some clocks have a "century bit" and drivers do
148280304Sjkim	 * year += 100, so interpret values between 70-199 as relative to 1900.
149280304Sjkim	 */
150280304Sjkim	year = ct->year;
151280304Sjkim	if (year < 70)
152280304Sjkim		year += 2000;
153280304Sjkim	else if (year < 200)
154280304Sjkim		year += 1900;
155280304Sjkim
156280304Sjkim	/* Sanity checks. */
157280304Sjkim	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
158280304Sjkim	    ct->day > days_in_month(year, ct->mon) ||
159280304Sjkim	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 || year < 1970 ||
160280304Sjkim	    (sizeof(time_t) == 4 && year > 2037)) {	/* time_t overflow */
161280304Sjkim		if (ct_debug)
162280304Sjkim			printf(" = EINVAL\n");
163280304Sjkim		return (EINVAL);
164280304Sjkim	}
165280304Sjkim
166280304Sjkim	/*
167280304Sjkim	 * Compute days since start of time
168	 * First from years, then from months.
169	 */
170	if (year >= recent_base_year) {
171		i = recent_base_year;
172		days = recent_base_days;
173	} else {
174		i = POSIX_BASE_YEAR;
175		days = 0;
176	}
177	for (; i < year; i++)
178		days += days_in_year(i);
179
180	/* Months */
181	for (i = 1; i < ct->mon; i++)
182	  	days += days_in_month(year, i);
183	days += (ct->day - 1);
184
185	ts->tv_sec = (((time_t)days * 24 + ct->hour) * 60 + ct->min) * 60 +
186	    ct->sec;
187	ts->tv_nsec = ct->nsec;
188
189	if (ct_debug)
190		printf(" = %jd.%09ld\n", (intmax_t)ts->tv_sec, ts->tv_nsec);
191	return (0);
192}
193
194int
195clock_bcd_to_ts(const struct bcd_clocktime *bct, struct timespec *ts, bool ampm)
196{
197	struct clocktime ct;
198	int bcent, byear;
199
200	/*
201	 * Year may come in as 2-digit or 4-digit BCD.  Split the value into
202	 * separate BCD century and year values for validation and conversion.
203	 */
204	bcent = bct->year >> 8;
205	byear = bct->year & 0xff;
206
207	/*
208	 * Ensure that all values are valid BCD numbers, to avoid assertions in
209	 * the BCD-to-binary conversion routines.  clock_ct_to_ts() will further
210	 * validate the field ranges (such as 0 <= min <= 59) during conversion.
211	 */
212	if (!validbcd(bcent) || !validbcd(byear) || !validbcd(bct->mon) ||
213	    !validbcd(bct->day) || !validbcd(bct->hour) ||
214	    !validbcd(bct->min) || !validbcd(bct->sec)) {
215		if (ct_debug)
216			printf("clock_bcd_to_ts: bad BCD: "
217			    "[%04x-%02x-%02x %02x:%02x:%02x]\n",
218			    bct->year, bct->mon, bct->day,
219			    bct->hour, bct->min, bct->sec);
220		return (EINVAL);
221	}
222
223	ct.year = FROMBCD(byear) + FROMBCD(bcent) * 100;
224	ct.mon  = FROMBCD(bct->mon);
225	ct.day  = FROMBCD(bct->day);
226	ct.hour = FROMBCD(bct->hour);
227	ct.min  = FROMBCD(bct->min);
228	ct.sec  = FROMBCD(bct->sec);
229	ct.dow  = bct->dow;
230	ct.nsec = bct->nsec;
231
232	/* If asked to handle am/pm, convert from 12hr+pmflag to 24hr. */
233	if (ampm) {
234		if (ct.hour == 12)
235			ct.hour = 0;
236		if (bct->ispm)
237			ct.hour += 12;
238	}
239
240	return (clock_ct_to_ts(&ct, ts));
241}
242
243void
244clock_ts_to_ct(const struct timespec *ts, struct clocktime *ct)
245{
246	time_t i, year, days;
247	time_t rsec;	/* remainder seconds */
248	time_t secs;
249
250	secs = ts->tv_sec;
251	days = secs / SECDAY;
252	rsec = secs % SECDAY;
253
254	ct->dow = day_of_week(days);
255
256	/* Subtract out whole years. */
257	if (days >= recent_base_days) {
258		year = recent_base_year;
259		days -= recent_base_days;
260	} else {
261		year = POSIX_BASE_YEAR;
262	}
263	for (; days >= days_in_year(year); year++)
264		days -= days_in_year(year);
265	ct->year = year;
266
267	/* Subtract out whole months, counting them in i. */
268	for (i = 1; days >= days_in_month(year, i); i++)
269		days -= days_in_month(year, i);
270	ct->mon = i;
271
272	/* Days are what is left over (+1) from all that. */
273	ct->day = days + 1;
274
275	/* Hours, minutes, seconds are easy */
276	ct->hour = rsec / 3600;
277	rsec = rsec % 3600;
278	ct->min  = rsec / 60;
279	rsec = rsec % 60;
280	ct->sec  = rsec;
281	ct->nsec = ts->tv_nsec;
282	if (ct_debug) {
283		printf("ts_to_ct(%jd.%09ld) = [",
284		    (intmax_t)ts->tv_sec, ts->tv_nsec);
285		clock_print_ct(ct, 9);
286		printf("]\n");
287	}
288
289	KASSERT(ct->year >= 0 && ct->year < 10000,
290	    ("year %d isn't a 4 digit year", ct->year));
291	KASSERT(ct->mon >= 1 && ct->mon <= 12,
292	    ("month %d not in 1-12", ct->mon));
293	KASSERT(ct->day >= 1 && ct->day <= 31,
294	    ("day %d not in 1-31", ct->day));
295	KASSERT(ct->hour >= 0 && ct->hour <= 23,
296	    ("hour %d not in 0-23", ct->hour));
297	KASSERT(ct->min >= 0 && ct->min <= 59,
298	    ("minute %d not in 0-59", ct->min));
299	/* Not sure if this interface needs to handle leapseconds or not. */
300	KASSERT(ct->sec >= 0 && ct->sec <= 60,
301	    ("seconds %d not in 0-60", ct->sec));
302}
303
304void
305clock_ts_to_bcd(const struct timespec *ts, struct bcd_clocktime *bct, bool ampm)
306{
307	struct clocktime ct;
308
309	clock_ts_to_ct(ts, &ct);
310
311	/* If asked to handle am/pm, convert from 24hr to 12hr+pmflag. */
312	bct->ispm = false;
313	if (ampm) {
314		if (ct.hour >= 12) {
315			ct.hour -= 12;
316			bct->ispm = true;
317		}
318		if (ct.hour == 0)
319			ct.hour = 12;
320	}
321
322	bct->year = TOBCD(ct.year % 100) | (TOBCD(ct.year / 100) << 8);
323	bct->mon  = TOBCD(ct.mon);
324	bct->day  = TOBCD(ct.day);
325	bct->hour = TOBCD(ct.hour);
326	bct->min  = TOBCD(ct.min);
327	bct->sec  = TOBCD(ct.sec);
328	bct->dow  = ct.dow;
329	bct->nsec = ct.nsec;
330}
331
332void
333clock_print_bcd(const struct bcd_clocktime *bct, int nsdigits)
334{
335
336	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
337
338	if (nsdigits > 0) {
339		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x.%*.*ld",
340		    bct->year, bct->mon, bct->day,
341		    bct->hour, bct->min, bct->sec,
342		    nsdigits, nsdigits, bct->nsec / nsdivisors[nsdigits]);
343	} else {
344		printf("%4.4x-%2.2x-%2.2x %2.2x:%2.2x:%2.2x",
345		    bct->year, bct->mon, bct->day,
346		    bct->hour, bct->min, bct->sec);
347	}
348}
349
350void
351clock_print_ct(const struct clocktime *ct, int nsdigits)
352{
353
354	KASSERT(nsdigits >= 0 && nsdigits <= 9, ("bad nsdigits %d", nsdigits));
355
356	if (nsdigits > 0) {
357		printf("%04d-%02d-%02d %02d:%02d:%02d.%*.*ld",
358		    ct->year, ct->mon, ct->day,
359		    ct->hour, ct->min, ct->sec,
360		    nsdigits, nsdigits, ct->nsec / nsdivisors[nsdigits]);
361	} else {
362		printf("%04d-%02d-%02d %02d:%02d:%02d",
363		    ct->year, ct->mon, ct->day,
364		    ct->hour, ct->min, ct->sec);
365	}
366}
367
368void
369clock_print_ts(const struct timespec *ts, int nsdigits)
370{
371	struct clocktime ct;
372
373	clock_ts_to_ct(ts, &ct);
374	clock_print_ct(&ct, nsdigits);
375}
376
377int
378utc_offset(void)
379{
380
381	return (wall_cmos_clock ? adjkerntz : 0);
382}
383