xref: /netbsd-src/sys/kern/kern_todr.c (revision 154bfe8e089c1a0a4e9ed8414f08d3da90949162)
1 /*	$NetBSD: kern_todr.c,v 1.46 2020/01/03 01:24:48 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 2020 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe.
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  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1988 University of Utah.
34  * Copyright (c) 1992, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * This code is derived from software contributed to Berkeley by
38  * the Systems Programming Group of the University of Utah Computer
39  * Science Department and Ralph Campbell.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  * from: Utah Hdr: clock.c 1.18 91/01/21
66  *
67  *	@(#)clock.c	8.1 (Berkeley) 6/10/93
68  */
69 
70 #include "opt_todr.h"
71 
72 #include <sys/cdefs.h>
73 __KERNEL_RCSID(0, "$NetBSD: kern_todr.c,v 1.46 2020/01/03 01:24:48 thorpej Exp $");
74 
75 #include <sys/param.h>
76 #include <sys/kernel.h>
77 #include <sys/systm.h>
78 #include <sys/device.h>
79 #include <sys/timetc.h>
80 #include <sys/intr.h>
81 #include <sys/rndsource.h>
82 #include <sys/mutex.h>
83 
84 #include <dev/clock_subr.h>	/* hmm.. this should probably move to sys */
85 
86 static int todr_gettime(todr_chip_handle_t, struct timeval *);
87 static int todr_settime(todr_chip_handle_t, struct timeval *);
88 
89 static kmutex_t todr_mutex;
90 static todr_chip_handle_t todr_handle;
91 static bool todr_initialized;
92 
93 /*
94  * todr_init:
95  *	Initialize TOD clock data.
96  */
97 void
98 todr_init(void)
99 {
100 
101 	mutex_init(&todr_mutex, MUTEX_DEFAULT, IPL_NONE);
102 	todr_initialized = true;
103 }
104 
105 /*
106  * todr_lock:
107  *	Acquire the TODR lock.
108  */
109 void
110 todr_lock(void)
111 {
112 
113 	mutex_enter(&todr_mutex);
114 }
115 
116 /*
117  * todr_unlock:
118  *	Release the TODR lock.
119  */
120 void
121 todr_unlock(void)
122 {
123 
124 	mutex_exit(&todr_mutex);
125 }
126 
127 /*
128  * todr_lock_owned:
129  *	Return true if the current thread owns the TODR lock.
130  *	This is to be used by diagnostic assertions only.
131  */
132 bool
133 todr_lock_owned(void)
134 {
135 
136 	return mutex_owned(&todr_mutex) ? true : false;
137 }
138 
139 /*
140  * todr_attach:
141  *	Attach the clock device to todr_handle.
142  */
143 void
144 todr_attach(todr_chip_handle_t todr)
145 {
146 
147 	/*
148 	 * todr_init() is called very early in main(), but this is
149 	 * here to catch a case where todr_attach() is called before
150 	 * main().
151 	 */
152 	KASSERT(todr_initialized);
153 
154 	todr_lock();
155 	if (todr_handle) {
156 		todr_unlock();
157 		printf("todr_attach: TOD already configured\n");
158 		return;
159 	}
160 	todr_handle = todr;
161 	todr_unlock();
162 }
163 
164 static bool timeset = false;
165 
166 /*
167  * todr_set_systime:
168  *	Set up the system's time.  The "base" argument is a best-guess
169  *	close-enough value to use if the TOD clock is unavailable or
170  *	contains garbage.  Must be called with the TODR lock held.
171  */
172 void
173 todr_set_systime(time_t base)
174 {
175 	bool badbase = false;
176 	bool waszero = (base == 0);
177 	bool goodtime = false;
178 	bool badrtc = false;
179 	struct timespec ts;
180 	struct timeval tv;
181 
182 	KASSERT(todr_lock_owned());
183 
184 	rnd_add_data(NULL, &base, sizeof(base), 0);
185 
186 	if (base < 5 * SECS_PER_COMMON_YEAR) {
187 		struct clock_ymdhms basedate;
188 
189 		/*
190 		 * If base is 0, assume filesystem time is just unknown
191 		 * instead of preposterous. Don't bark.
192 		 */
193 		if (base != 0)
194 			printf("WARNING: preposterous time in file system\n");
195 		/* not going to use it anyway, if the chip is readable */
196 		basedate.dt_year = 2010;
197 		basedate.dt_mon = 1;
198 		basedate.dt_day = 1;
199 		basedate.dt_hour = 12;
200 		basedate.dt_min = 0;
201 		basedate.dt_sec = 0;
202 		base = clock_ymdhms_to_secs(&basedate);
203 		badbase = true;
204 	}
205 
206 	/*
207 	 * Some ports need to be supplied base in order to fabricate a time_t.
208 	 */
209 	if (todr_handle)
210 		todr_handle->base_time = base;
211 
212 	memset(&tv, 0, sizeof(tv));
213 
214 	if ((todr_handle == NULL) ||
215 	    (todr_gettime(todr_handle, &tv) != 0) ||
216 	    (tv.tv_sec < (25 * SECS_PER_COMMON_YEAR))) {
217 
218 		if (todr_handle != NULL)
219 			printf("WARNING: preposterous TOD clock time\n");
220 		else
221 			printf("WARNING: no TOD clock present\n");
222 		badrtc = true;
223 	} else {
224 		time_t deltat = tv.tv_sec - base;
225 
226 		if (deltat < 0)
227 			deltat = -deltat;
228 
229 		if (!badbase && deltat >= 2 * SECS_PER_DAY) {
230 
231 			if (tv.tv_sec < base) {
232 				/*
233 				 * The clock should never go backwards
234 				 * relative to filesystem time.  If it
235 				 * does by more than the threshold,
236 				 * believe the filesystem.
237 				 */
238 				printf("WARNING: clock lost %" PRId64 " days\n",
239 				    deltat / SECS_PER_DAY);
240 				badrtc = true;
241 			} else {
242 				aprint_verbose("WARNING: clock gained %" PRId64
243 				    " days\n", deltat / SECS_PER_DAY);
244 				goodtime = true;
245 			}
246 		} else {
247 			goodtime = true;
248 		}
249 
250 		rnd_add_data(NULL, &tv, sizeof(tv), 0);
251 	}
252 
253 	/* if the rtc time is bad, use the filesystem time */
254 	if (badrtc) {
255 		if (badbase) {
256 			printf("WARNING: using default initial time\n");
257 		} else {
258 			printf("WARNING: using filesystem time\n");
259 		}
260 		tv.tv_sec = base;
261 		tv.tv_usec = 0;
262 	}
263 
264 	timeset = true;
265 
266 	ts.tv_sec = tv.tv_sec;
267 	ts.tv_nsec = tv.tv_usec * 1000;
268 	tc_setclock(&ts);
269 
270 	if (waszero || goodtime)
271 		return;
272 
273 	printf("WARNING: CHECK AND RESET THE DATE!\n");
274 }
275 
276 /*
277  * todr_save_systime:
278  *	Save the current system time back to the TOD clock.
279  *	Must be called with the TODR lock held.
280  */
281 void
282 todr_save_systime(void)
283 {
284 	struct timeval tv;
285 
286 	KASSERT(todr_lock_owned());
287 
288 	/*
289 	 * We might have been called by boot() due to a crash early
290 	 * on.  Don't reset the clock chip if we don't know what time
291 	 * it is.
292 	 */
293 	if (!timeset)
294 		return;
295 
296 	getmicrotime(&tv);
297 
298 	if (tv.tv_sec == 0)
299 		return;
300 
301 	if (todr_handle)
302 		if (todr_settime(todr_handle, &tv) != 0)
303 			printf("Cannot set TOD clock time\n");
304 }
305 
306 /*
307  * inittodr:
308  *	Legacy wrapper around todr_set_systime().
309  */
310 void
311 inittodr(time_t base)
312 {
313 
314 	todr_lock();
315 	todr_set_systime(base);
316 	todr_unlock();
317 }
318 
319 /*
320  * resettodr:
321  *	Legacy wrapper around todr_save_systime().
322  */
323 void
324 resettodr(void)
325 {
326 
327 	/*
328 	 * If we're shutting down, we don't want to get stuck in case
329 	 * someone was already fiddling with the TOD clock.
330 	 */
331 	if (shutting_down) {
332 		if (mutex_tryenter(&todr_mutex) == 0) {
333 			printf("WARNING: Cannot set TOD clock time (busy)\n");
334 			return;
335 		}
336 	} else {
337 		todr_lock();
338 	}
339 	todr_save_systime();
340 	todr_unlock();
341 }
342 
343 #ifdef	TODR_DEBUG
344 static void
345 todr_debug(const char *prefix, int rv, struct clock_ymdhms *dt,
346     struct timeval *tvp)
347 {
348 	struct timeval tv_val;
349 	struct clock_ymdhms dt_val;
350 
351 	if (dt == NULL) {
352 		clock_secs_to_ymdhms(tvp->tv_sec, &dt_val);
353 		dt = &dt_val;
354 	}
355 	if (tvp == NULL) {
356 		tvp = &tv_val;
357 		tvp->tv_sec = clock_ymdhms_to_secs(dt);
358 		tvp->tv_usec = 0;
359 	}
360 	printf("%s: rv = %d\n", prefix, rv);
361 	printf("%s: rtc_offset = %d\n", prefix, rtc_offset);
362 	printf("%s: %4u/%02u/%02u %02u:%02u:%02u, (wday %d) (epoch %u.%06u)\n",
363 	    prefix,
364 	    (unsigned)dt->dt_year, dt->dt_mon, dt->dt_day,
365 	    dt->dt_hour, dt->dt_min, dt->dt_sec,
366 	    dt->dt_wday, (unsigned)tvp->tv_sec, (unsigned)tvp->tv_usec);
367 }
368 #else	/* !TODR_DEBUG */
369 #define	todr_debug(prefix, rv, dt, tvp)
370 #endif	/* TODR_DEBUG */
371 
372 static int
373 todr_wenable(todr_chip_handle_t todr, int onoff)
374 {
375 
376 	if (todr->todr_setwen != NULL)
377 		return todr->todr_setwen(todr, onoff);
378 
379 	return 0;
380 }
381 
382 #define	ENABLE_TODR_WRITES()						\
383 do {									\
384 	if ((rv = todr_wenable(tch, 1)) != 0) {				\
385 		printf("%s: cannot enable TODR writes\n", __func__);	\
386 		return rv;						\
387 	}								\
388 } while (/*CONSTCOND*/0)
389 
390 #define	DISABLE_TODR_WRITES()						\
391 do {									\
392 	if (todr_wenable(tch, 0) != 0)					\
393 		printf("%s: WARNING: cannot disable TODR writes\n",	\
394 		    __func__);						\
395 } while (/*CONSTCOND*/0)
396 
397 static int
398 todr_gettime(todr_chip_handle_t tch, struct timeval *tvp)
399 {
400 	int rv;
401 
402 	/*
403 	 * Write-enable is used even when reading the TODR because
404 	 * writing to registers may be required in order to do so.
405 	 */
406 
407 	if (tch->todr_gettime) {
408 		ENABLE_TODR_WRITES();
409 		rv = tch->todr_gettime(tch, tvp);
410 		DISABLE_TODR_WRITES();
411 		/*
412 		 * Some unconverted ports have their own references to
413 		 * rtc_offset.   A converted port must not do that.
414 		 */
415 		if (rv == 0)
416 			tvp->tv_sec += rtc_offset * 60;
417 		todr_debug("TODR-GET-SECS", rv, NULL, tvp);
418 		return rv;
419 	} else if (tch->todr_gettime_ymdhms) {
420 		struct clock_ymdhms dt = { 0 };
421 		ENABLE_TODR_WRITES();
422 		rv = tch->todr_gettime_ymdhms(tch, &dt);
423 		DISABLE_TODR_WRITES();
424 		todr_debug("TODR-GET-YMDHMS", rv, &dt, NULL);
425 		if (rv)
426 			return rv;
427 
428 		/*
429 		 * Simple sanity checks.  Note that this includes a
430 		 * value for clocks that can return a leap second.
431 		 * Note that we don't support double leap seconds,
432 		 * since this was apparently an error/misunderstanding
433 		 * on the part of the ISO C committee, and can never
434 		 * actually occur.  If your clock issues us a double
435 		 * leap second, it must be broken.  Ultimately, you'd
436 		 * have to be trying to read time at precisely that
437 		 * instant to even notice, so even broken clocks will
438 		 * work the vast majority of the time.  In such a case
439 		 * it is recommended correction be applied in the
440 		 * clock driver.
441 		 */
442 		if (dt.dt_mon < 1 || dt.dt_mon > 12 ||
443 		    dt.dt_day < 1 || dt.dt_day > 31 ||
444 		    dt.dt_hour > 23 || dt.dt_min > 59 || dt.dt_sec > 60) {
445 			return EINVAL;
446 		}
447 		tvp->tv_sec = clock_ymdhms_to_secs(&dt) + rtc_offset * 60;
448 		tvp->tv_usec = 0;
449 		return tvp->tv_sec < 0 ? EINVAL : 0;
450 	}
451 
452 	return ENXIO;
453 }
454 
455 static int
456 todr_settime(todr_chip_handle_t tch, struct timeval *tvp)
457 {
458 	int rv;
459 
460 	if (tch->todr_settime) {
461 		struct timeval copy = *tvp;
462 		copy.tv_sec -= rtc_offset * 60;
463 		ENABLE_TODR_WRITES();
464 		rv = tch->todr_settime(tch, &copy);
465 		DISABLE_TODR_WRITES();
466 		todr_debug("TODR-SET-SECS", rv, NULL, tvp);
467 		return rv;
468 	} else if (tch->todr_settime_ymdhms) {
469 		struct clock_ymdhms dt;
470 		time_t sec = tvp->tv_sec - rtc_offset * 60;
471 		if (tvp->tv_usec >= 500000)
472 			sec++;
473 		clock_secs_to_ymdhms(sec, &dt);
474 		ENABLE_TODR_WRITES();
475 		rv = tch->todr_settime_ymdhms(tch, &dt);
476 		DISABLE_TODR_WRITES();
477 		todr_debug("TODR-SET-YMDHMS", rv, &dt, NULL);
478 		return rv;
479 	}
480 
481 	return ENXIO;
482 }
483