xref: /freebsd/sys/kern/subr_clock.c (revision 8a0a413e)
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 int tz_minuteswest;
56 int tz_dsttime;
57 
58 /*
59  * The adjkerntz and wall_cmos_clock sysctls are in the "machdep" sysctl
60  * namespace because they were misplaced there originally.
61  */
62 static int adjkerntz;
63 static int
64 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
65 {
66 	int error;
67 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
68 	if (!error && req->newptr)
69 		resettodr();
70 	return (error);
71 }
72 SYSCTL_PROC(_machdep, OID_AUTO, adjkerntz, CTLTYPE_INT | CTLFLAG_RW |
73     CTLFLAG_MPSAFE, &adjkerntz, 0, sysctl_machdep_adjkerntz, "I",
74     "Local offset from UTC in seconds");
75 
76 static int ct_debug;
77 SYSCTL_INT(_debug, OID_AUTO, clocktime, CTLFLAG_RWTUN,
78     &ct_debug, 0, "Enable printing of clocktime debugging");
79 
80 static int wall_cmos_clock;
81 SYSCTL_INT(_machdep, OID_AUTO, wall_cmos_clock, CTLFLAG_RW,
82     &wall_cmos_clock, 0, "Enables application of machdep.adjkerntz");
83 
84 /*--------------------------------------------------------------------*
85  * Generic routines to convert between a POSIX date
86  * (seconds since 1/1/1970) and yr/mo/day/hr/min/sec
87  * Derived from NetBSD arch/hp300/hp300/clock.c
88  */
89 
90 
91 #define	FEBRUARY	2
92 #define	days_in_year(y) 	(leapyear(y) ? 366 : 365)
93 #define	days_in_month(y, m) \
94 	(month_days[(m) - 1] + (m == FEBRUARY ? leapyear(y) : 0))
95 /* Day of week. Days are counted from 1/1/1970, which was a Thursday */
96 #define	day_of_week(days)	(((days) + 4) % 7)
97 
98 static const int month_days[12] = {
99 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
100 };
101 
102 /*
103  * Optimization: using a precomputed count of days between POSIX_BASE_YEAR and
104  * some recent year avoids lots of unnecessary loop iterations in conversion.
105  * recent_base_days is the number of days before the start of recent_base_year.
106  */
107 static const int recent_base_year = 2017;
108 static const int recent_base_days = 17167;
109 
110 /*
111  * This inline avoids some unnecessary modulo operations
112  * as compared with the usual macro:
113  *   ( ((year % 4) == 0 &&
114  *      (year % 100) != 0) ||
115  *     ((year % 400) == 0) )
116  * It is otherwise equivalent.
117  */
118 static int
119 leapyear(int year)
120 {
121 	int rv = 0;
122 
123 	if ((year & 3) == 0) {
124 		rv = 1;
125 		if ((year % 100) == 0) {
126 			rv = 0;
127 			if ((year % 400) == 0)
128 				rv = 1;
129 		}
130 	}
131 	return (rv);
132 }
133 
134 static void
135 print_ct(struct clocktime *ct)
136 {
137 	printf("[%04d-%02d-%02d %02d:%02d:%02d]",
138 	    ct->year, ct->mon, ct->day,
139 	    ct->hour, ct->min, ct->sec);
140 }
141 
142 int
143 clock_ct_to_ts(struct clocktime *ct, struct timespec *ts)
144 {
145 	int i, year, days;
146 
147 	if (ct_debug) {
148 		printf("ct_to_ts(");
149 		print_ct(ct);
150 		printf(")");
151 	}
152 
153 	/*
154 	 * Many realtime clocks store the year as 2-digit BCD; pivot on 70 to
155 	 * determine century.  Some clocks have a "century bit" and drivers do
156 	 * year += 100, so interpret values between 70-199 as relative to 1900.
157 	 */
158 	year = ct->year;
159 	if (year < 70)
160 		year += 2000;
161 	else if (year < 200)
162 		year += 1900;
163 
164 	/* Sanity checks. */
165 	if (ct->mon < 1 || ct->mon > 12 || ct->day < 1 ||
166 	    ct->day > days_in_month(year, ct->mon) ||
167 	    ct->hour > 23 ||  ct->min > 59 || ct->sec > 59 || year < 1970 ||
168 	    (sizeof(time_t) == 4 && year > 2037)) {	/* time_t overflow */
169 		if (ct_debug)
170 			printf(" = EINVAL\n");
171 		return (EINVAL);
172 	}
173 
174 	/*
175 	 * Compute days since start of time
176 	 * First from years, then from months.
177 	 */
178 	if (year >= recent_base_year) {
179 		i = recent_base_year;
180 		days = recent_base_days;
181 	} else {
182 		i = POSIX_BASE_YEAR;
183 		days = 0;
184 	}
185 	for (; i < year; i++)
186 		days += days_in_year(i);
187 
188 	/* Months */
189 	for (i = 1; i < ct->mon; i++)
190 	  	days += days_in_month(year, i);
191 	days += (ct->day - 1);
192 
193 	ts->tv_sec = (((time_t)days * 24 + ct->hour) * 60 + ct->min) * 60 +
194 	    ct->sec;
195 	ts->tv_nsec = ct->nsec;
196 
197 	if (ct_debug)
198 		printf(" = %jd.%09ld\n", (intmax_t)ts->tv_sec, ts->tv_nsec);
199 	return (0);
200 }
201 
202 void
203 clock_ts_to_ct(struct timespec *ts, struct clocktime *ct)
204 {
205 	time_t i, year, days;
206 	time_t rsec;	/* remainder seconds */
207 	time_t secs;
208 
209 	secs = ts->tv_sec;
210 	days = secs / SECDAY;
211 	rsec = secs % SECDAY;
212 
213 	ct->dow = day_of_week(days);
214 
215 	/* Subtract out whole years. */
216 	if (days >= recent_base_days) {
217 		year = recent_base_year;
218 		days -= recent_base_days;
219 	} else {
220 		year = POSIX_BASE_YEAR;
221 	}
222 	for (; days >= days_in_year(year); year++)
223 		days -= days_in_year(year);
224 	ct->year = year;
225 
226 	/* Subtract out whole months, counting them in i. */
227 	for (i = 1; days >= days_in_month(year, i); i++)
228 		days -= days_in_month(year, i);
229 	ct->mon = i;
230 
231 	/* Days are what is left over (+1) from all that. */
232 	ct->day = days + 1;
233 
234 	/* Hours, minutes, seconds are easy */
235 	ct->hour = rsec / 3600;
236 	rsec = rsec % 3600;
237 	ct->min  = rsec / 60;
238 	rsec = rsec % 60;
239 	ct->sec  = rsec;
240 	ct->nsec = ts->tv_nsec;
241 	if (ct_debug) {
242 		printf("ts_to_ct(%jd.%09ld) = ",
243 		    (intmax_t)ts->tv_sec, ts->tv_nsec);
244 		print_ct(ct);
245 		printf("\n");
246 	}
247 
248 	KASSERT(ct->year >= 0 && ct->year < 10000,
249 	    ("year %d isn't a 4 digit year", ct->year));
250 	KASSERT(ct->mon >= 1 && ct->mon <= 12,
251 	    ("month %d not in 1-12", ct->mon));
252 	KASSERT(ct->day >= 1 && ct->day <= 31,
253 	    ("day %d not in 1-31", ct->day));
254 	KASSERT(ct->hour >= 0 && ct->hour <= 23,
255 	    ("hour %d not in 0-23", ct->hour));
256 	KASSERT(ct->min >= 0 && ct->min <= 59,
257 	    ("minute %d not in 0-59", ct->min));
258 	/* Not sure if this interface needs to handle leapseconds or not. */
259 	KASSERT(ct->sec >= 0 && ct->sec <= 60,
260 	    ("seconds %d not in 0-60", ct->sec));
261 }
262 
263 int
264 utc_offset(void)
265 {
266 
267 	return (tz_minuteswest * 60 + (wall_cmos_clock ? adjkerntz : 0));
268 }
269