Home | History | Annotate | Line # | Download | only in kern
kern_todr.c revision 1.39.18.1
      1 /*	$NetBSD: kern_todr.c,v 1.39.18.1 2020/04/08 14:08:51 martin 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.39.18.1 2020/04/08 14:08:51 martin 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 	if ((todr_handle == NULL) ||
    213 	    (todr_gettime(todr_handle, &tv) != 0) ||
    214 	    (tv.tv_sec < (25 * SECS_PER_COMMON_YEAR))) {
    215 
    216 		if (todr_handle != NULL)
    217 			printf("WARNING: preposterous TOD clock time\n");
    218 		else
    219 			printf("WARNING: no TOD clock present\n");
    220 		badrtc = true;
    221 	} else {
    222 		time_t deltat = tv.tv_sec - base;
    223 
    224 		if (deltat < 0)
    225 			deltat = -deltat;
    226 
    227 		if (!badbase && deltat >= 2 * SECS_PER_DAY) {
    228 
    229 			if (tv.tv_sec < base) {
    230 				/*
    231 				 * The clock should never go backwards
    232 				 * relative to filesystem time.  If it
    233 				 * does by more than the threshold,
    234 				 * believe the filesystem.
    235 				 */
    236 				printf("WARNING: clock lost %" PRId64 " days\n",
    237 				    deltat / SECS_PER_DAY);
    238 				badrtc = true;
    239 			} else {
    240 				aprint_verbose("WARNING: clock gained %" PRId64
    241 				    " days\n", deltat / SECS_PER_DAY);
    242 				goodtime = true;
    243 			}
    244 		} else {
    245 			goodtime = true;
    246 		}
    247 
    248 		rnd_add_data(NULL, &tv, sizeof(tv), 0);
    249 	}
    250 
    251 	/* if the rtc time is bad, use the filesystem time */
    252 	if (badrtc) {
    253 		if (badbase) {
    254 			printf("WARNING: using default initial time\n");
    255 		} else {
    256 			printf("WARNING: using filesystem time\n");
    257 		}
    258 		tv.tv_sec = base;
    259 		tv.tv_usec = 0;
    260 	}
    261 
    262 	timeset = true;
    263 
    264 	ts.tv_sec = tv.tv_sec;
    265 	ts.tv_nsec = tv.tv_usec * 1000;
    266 	tc_setclock(&ts);
    267 
    268 	if (waszero || goodtime)
    269 		return;
    270 
    271 	printf("WARNING: CHECK AND RESET THE DATE!\n");
    272 }
    273 
    274 /*
    275  * todr_save_systime:
    276  *	Save the current system time back to the TOD clock.
    277  *	Must be called with the TODR lock held.
    278  */
    279 void
    280 todr_save_systime(void)
    281 {
    282 	struct timeval tv;
    283 
    284 	KASSERT(todr_lock_owned());
    285 
    286 	/*
    287 	 * We might have been called by boot() due to a crash early
    288 	 * on.  Don't reset the clock chip if we don't know what time
    289 	 * it is.
    290 	 */
    291 	if (!timeset)
    292 		return;
    293 
    294 	getmicrotime(&tv);
    295 
    296 	if (tv.tv_sec == 0)
    297 		return;
    298 
    299 	if (todr_handle)
    300 		if (todr_settime(todr_handle, &tv) != 0)
    301 			printf("Cannot set TOD clock time\n");
    302 }
    303 
    304 /*
    305  * inittodr:
    306  *	Legacy wrapper around todr_set_systime().
    307  */
    308 void
    309 inittodr(time_t base)
    310 {
    311 
    312 	todr_lock();
    313 	todr_set_systime(base);
    314 	todr_unlock();
    315 }
    316 
    317 /*
    318  * resettodr:
    319  *	Legacy wrapper around todr_save_systime().
    320  */
    321 void
    322 resettodr(void)
    323 {
    324 
    325 	/*
    326 	 * If we're shutting down, we don't want to get stuck in case
    327 	 * someone was already fiddling with the TOD clock.
    328 	 */
    329 	if (shutting_down) {
    330 		if (mutex_tryenter(&todr_mutex) == 0) {
    331 			printf("WARNING: Cannot set TOD clock time (busy)\n");
    332 			return;
    333 		}
    334 	} else {
    335 		todr_lock();
    336 	}
    337 	todr_save_systime();
    338 	todr_unlock();
    339 }
    340 
    341 #ifdef	TODR_DEBUG
    342 static void
    343 todr_debug(const char *prefix, int rv, struct clock_ymdhms *dt,
    344     struct timeval *tvp)
    345 {
    346 	struct timeval tv_val;
    347 	struct clock_ymdhms dt_val;
    348 
    349 	if (dt == NULL) {
    350 		clock_secs_to_ymdhms(tvp->tv_sec, &dt_val);
    351 		dt = &dt_val;
    352 	}
    353 	if (tvp == NULL) {
    354 		tvp = &tv_val;
    355 		tvp->tv_sec = clock_ymdhms_to_secs(dt);
    356 		tvp->tv_usec = 0;
    357 	}
    358 	printf("%s: rv = %d\n", prefix, rv);
    359 	printf("%s: rtc_offset = %d\n", prefix, rtc_offset);
    360 	printf("%s: %4u/%02u/%02u %02u:%02u:%02u, (wday %d) (epoch %u.%06u)\n",
    361 	    prefix,
    362 	    (unsigned)dt->dt_year, dt->dt_mon, dt->dt_day,
    363 	    dt->dt_hour, dt->dt_min, dt->dt_sec,
    364 	    dt->dt_wday, (unsigned)tvp->tv_sec, (unsigned)tvp->tv_usec);
    365 }
    366 #else	/* !TODR_DEBUG */
    367 #define	todr_debug(prefix, rv, dt, tvp)
    368 #endif	/* TODR_DEBUG */
    369 
    370 static int
    371 todr_wenable(todr_chip_handle_t todr, int onoff)
    372 {
    373 
    374 	if (todr->todr_setwen != NULL)
    375 		return todr->todr_setwen(todr, onoff);
    376 
    377 	return 0;
    378 }
    379 
    380 #define	ENABLE_TODR_WRITES()						\
    381 do {									\
    382 	if ((rv = todr_wenable(tch, 1)) != 0) {				\
    383 		printf("%s: cannot enable TODR writes\n", __func__);	\
    384 		return rv;						\
    385 	}								\
    386 } while (/*CONSTCOND*/0)
    387 
    388 #define	DISABLE_TODR_WRITES()						\
    389 do {									\
    390 	if (todr_wenable(tch, 0) != 0)					\
    391 		printf("%s: WARNING: cannot disable TODR writes\n",	\
    392 		    __func__);						\
    393 } while (/*CONSTCOND*/0)
    394 
    395 static int
    396 todr_gettime(todr_chip_handle_t tch, struct timeval *tvp)
    397 {
    398 	int rv;
    399 
    400 	/*
    401 	 * Write-enable is used even when reading the TODR because
    402 	 * writing to registers may be required in order to do so.
    403 	 */
    404 
    405 	if (tch->todr_gettime) {
    406 		ENABLE_TODR_WRITES();
    407 		rv = tch->todr_gettime(tch, tvp);
    408 		DISABLE_TODR_WRITES();
    409 		/*
    410 		 * Some unconverted ports have their own references to
    411 		 * rtc_offset.   A converted port must not do that.
    412 		 */
    413 		if (rv == 0)
    414 			tvp->tv_sec += rtc_offset * 60;
    415 		todr_debug("TODR-GET-SECS", rv, NULL, tvp);
    416 		return rv;
    417 	} else if (tch->todr_gettime_ymdhms) {
    418 		struct clock_ymdhms dt = { 0 };
    419 		ENABLE_TODR_WRITES();
    420 		rv = tch->todr_gettime_ymdhms(tch, &dt);
    421 		DISABLE_TODR_WRITES();
    422 		todr_debug("TODR-GET-YMDHMS", rv, &dt, NULL);
    423 		if (rv)
    424 			return rv;
    425 
    426 		/*
    427 		 * Simple sanity checks.  Note that this includes a
    428 		 * value for clocks that can return a leap second.
    429 		 * Note that we don't support double leap seconds,
    430 		 * since this was apparently an error/misunderstanding
    431 		 * on the part of the ISO C committee, and can never
    432 		 * actually occur.  If your clock issues us a double
    433 		 * leap second, it must be broken.  Ultimately, you'd
    434 		 * have to be trying to read time at precisely that
    435 		 * instant to even notice, so even broken clocks will
    436 		 * work the vast majority of the time.  In such a case
    437 		 * it is recommended correction be applied in the
    438 		 * clock driver.
    439 		 */
    440 		if (dt.dt_mon < 1 || dt.dt_mon > 12 ||
    441 		    dt.dt_day < 1 || dt.dt_day > 31 ||
    442 		    dt.dt_hour > 23 || dt.dt_min > 59 || dt.dt_sec > 60) {
    443 			return EINVAL;
    444 		}
    445 		tvp->tv_sec = clock_ymdhms_to_secs(&dt) + rtc_offset * 60;
    446 		tvp->tv_usec = 0;
    447 		return tvp->tv_sec < 0 ? EINVAL : 0;
    448 	}
    449 
    450 	return ENXIO;
    451 }
    452 
    453 static int
    454 todr_settime(todr_chip_handle_t tch, struct timeval *tvp)
    455 {
    456 	int rv;
    457 
    458 	if (tch->todr_settime) {
    459 		struct timeval copy = *tvp;
    460 		copy.tv_sec -= rtc_offset * 60;
    461 		ENABLE_TODR_WRITES();
    462 		rv = tch->todr_settime(tch, &copy);
    463 		DISABLE_TODR_WRITES();
    464 		todr_debug("TODR-SET-SECS", rv, NULL, tvp);
    465 		return rv;
    466 	} else if (tch->todr_settime_ymdhms) {
    467 		struct clock_ymdhms dt;
    468 		time_t sec = tvp->tv_sec - rtc_offset * 60;
    469 		if (tvp->tv_usec >= 500000)
    470 			sec++;
    471 		clock_secs_to_ymdhms(sec, &dt);
    472 		ENABLE_TODR_WRITES();
    473 		rv = tch->todr_settime_ymdhms(tch, &dt);
    474 		DISABLE_TODR_WRITES();
    475 		todr_debug("TODR-SET-YMDHMS", rv, &dt, NULL);
    476 		return rv;
    477 	}
    478 
    479 	return ENXIO;
    480 }
    481