Home | History | Annotate | Line # | Download | only in dev
clock.c revision 1.14
      1 /*	$NetBSD: clock.c,v 1.14 1996/12/16 21:24:32 leo Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988 University of Utah.
      5  * Copyright (c) 1982, 1990 The Regents of the University of California.
      6  * 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. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  * from: Utah $Hdr: clock.c 1.18 91/01/21$
     41  *
     42  *	@(#)clock.c	7.6 (Berkeley) 5/7/91
     43  */
     44 
     45 #include <sys/param.h>
     46 #include <sys/kernel.h>
     47 #include <sys/systm.h>
     48 #include <sys/device.h>
     49 #include <sys/uio.h>
     50 #include <sys/conf.h>
     51 #include <machine/psl.h>
     52 #include <machine/cpu.h>
     53 #include <machine/iomap.h>
     54 #include <machine/mfp.h>
     55 #include <atari/dev/clockreg.h>
     56 #include <atari/atari/device.h>
     57 
     58 #if defined(GPROF) && defined(PROFTIMER)
     59 #include <machine/profile.h>
     60 #endif
     61 
     62 /*
     63  * The MFP clock runs at 2457600Hz. We use a {system,stat,prof}clock divider
     64  * of 200. Therefore the timer runs at an effective rate of:
     65  * 2457600/200 = 12288Hz.
     66  */
     67 #define CLOCK_HZ	12288
     68 
     69 /*
     70  * Machine-dependent clock routines.
     71  *
     72  * Inittodr initializes the time of day hardware which provides
     73  * date functions.
     74  *
     75  * Resettodr restores the time of day hardware after a time change.
     76  */
     77 
     78 struct clock_softc {
     79 	struct device	sc_dev;
     80 	int		sc_flags;
     81 };
     82 
     83 /*
     84  *  'sc_flags' state info. Only used by the rtc-device functions.
     85  */
     86 #define	RTC_OPEN	1
     87 
     88 /* {b,c}devsw[] function prototypes for rtc functions */
     89 dev_type_open(rtcopen);
     90 dev_type_close(rtcclose);
     91 dev_type_read(rtcread);
     92 dev_type_write(rtcwrite);
     93 
     94 static void	clockattach __P((struct device *, struct device *, void *));
     95 static int	clockmatch __P((struct device *, void *, void *));
     96 
     97 struct cfattach clock_ca = {
     98 	sizeof(struct clock_softc), clockmatch, clockattach
     99 };
    100 
    101 struct cfdriver clock_cd = {
    102 	NULL, "clock", DV_DULL, NULL, 0
    103 };
    104 
    105 void statintr __P((struct clockframe *));
    106 
    107 static u_long	gettod __P((void));
    108 static int	twodigits __P((char *, int));
    109 
    110 static int	divisor;	/* Systemclock divisor	*/
    111 
    112 /*
    113  * Statistics and profile clock intervals and variances. Variance must
    114  * be a power of 2. Since this gives us an even number, not an odd number,
    115  * we discard one case and compensate. That is, a variance of 64 would
    116  * give us offsets in [0..63]. Instead, we take offsets in [1..63].
    117  * This is symetric around the point 32, or statvar/2, and thus averages
    118  * to that value (assuming uniform random numbers).
    119  */
    120 #ifdef STATCLOCK
    121 static int	statvar = 32;	/* {stat,prof}clock variance		*/
    122 static int	statmin;	/* statclock divisor - variance/2	*/
    123 static int	profmin;	/* profclock divisor - variance/2	*/
    124 static int	clk2min;	/* current, from above choises		*/
    125 #endif
    126 
    127 int
    128 clockmatch(pdp, match, auxp)
    129 struct device	*pdp;
    130 void		*match, *auxp;
    131 {
    132 	if(!strcmp("clock", auxp))
    133 		return(1);
    134 	return(0);
    135 }
    136 
    137 /*
    138  * Start the real-time clock.
    139  */
    140 void clockattach(pdp, dp, auxp)
    141 struct device	*pdp, *dp;
    142 void		*auxp;
    143 {
    144 	struct clock_softc *sc = (void *)dp;
    145 
    146 	sc->sc_flags = 0;
    147 
    148 	/*
    149 	 * Initialize Timer-A in the ST-MFP. We use a divisor of 200.
    150 	 * The MFP clock runs at 2457600Hz. Therefore the timer runs
    151 	 * at an effective rate of: 2457600/200 = 12288Hz. The
    152 	 * following expression works for 48, 64 or 96 hz.
    153 	 */
    154 	divisor       = CLOCK_HZ/hz;
    155 	MFP->mf_tacr  = 0;		/* Stop timer			*/
    156 	MFP->mf_iera &= ~IA_TIMA;	/* Disable timer interrupts	*/
    157 	MFP->mf_tadr  = divisor;	/* Set divisor			*/
    158 
    159 	if (hz != 48 && hz != 64 && hz != 96) { /* XXX */
    160 		printf (": illegal value %d for systemclock, reset to %d\n\t",
    161 								hz, 64);
    162 		hz = 64;
    163 	}
    164 	printf(": system hz %d timer-A divisor 200/%d\n", hz, divisor);
    165 
    166 #ifdef STATCLOCK
    167 	if ((stathz == 0) || (stathz > hz) || (CLOCK_HZ % stathz))
    168 		stathz = hz;
    169 	if ((profhz == 0) || (profhz > (hz << 1)) || (CLOCK_HZ % profhz))
    170 		profhz = hz << 1;
    171 
    172 	MFP->mf_tcdcr &= 0x7;			/* Stop timer		*/
    173 	MFP->mf_ierb  &= ~IB_TIMC;		/* Disable timer inter.	*/
    174 	MFP->mf_tcdr   = CLOCK_HZ/stathz;	/* Set divisor		*/
    175 
    176 	statmin  = (CLOCK_HZ/stathz) - (statvar >> 1);
    177 	profmin  = (CLOCK_HZ/profhz) - (statvar >> 1);
    178 	clk2min  = statmin;
    179 #endif /* STATCLOCK */
    180 
    181 	/*
    182 	 * Initialize Timer-B in the ST-MFP. This timer is used by
    183 	 * the 'delay' function below. This timer is setup to be
    184 	 * continueously counting from 255 back to zero at a
    185 	 * frequency of 614400Hz. We do this *early* in the
    186 	 * initialisation process.
    187 	 */
    188 	MFP->mf_tbcr  = 0;		/* Stop timer			*/
    189 	MFP->mf_iera &= ~IA_TIMB;	/* Disable timer interrupts	*/
    190 	MFP->mf_tbdr  = 0;
    191 	MFP->mf_tbcr  = T_Q004;	/* Start timer			*/
    192 
    193 }
    194 
    195 void cpu_initclocks()
    196 {
    197 	MFP->mf_tacr  = T_Q200;		/* Start timer			*/
    198 	MFP->mf_ipra &= ~IA_TIMA;	/* Clear pending interrupts	*/
    199 	MFP->mf_iera |= IA_TIMA;	/* Enable timer interrupts	*/
    200 	MFP->mf_imra |= IA_TIMA;	/*    .....			*/
    201 
    202 #ifdef STATCLOCK
    203 	MFP->mf_tcdcr = (MFP->mf_tcdcr & 0x7) | (T_Q200<<4); /* Start	*/
    204 	MFP->mf_iprb &= ~IB_TIMC;	/* Clear pending interrupts	*/
    205 	MFP->mf_ierb |= IB_TIMC;	/* Enable timer interrupts	*/
    206 	MFP->mf_imrb |= IB_TIMC;	/*    .....			*/
    207 #endif /* STATCLOCK */
    208 }
    209 
    210 void
    211 setstatclockrate(newhz)
    212 	int newhz;
    213 {
    214 #ifdef STATCLOCK
    215 	if (newhz == stathz)
    216 		clk2min = statmin;
    217 	else clk2min = profmin;
    218 #endif /* STATCLOCK */
    219 }
    220 
    221 #ifdef STATCLOCK
    222 void
    223 statintr(frame)
    224 	register struct clockframe *frame;
    225 {
    226 	register int	var, r;
    227 
    228 	var = statvar - 1;
    229 	do {
    230 		r = random() & var;
    231 	} while(r == 0);
    232 
    233 	/*
    234 	 * Note that we are always lagging behind as the new divisor
    235 	 * value will not be loaded until the next interrupt. This
    236 	 * shouldn't disturb the median frequency (I think ;-) ) as
    237 	 * only the value used when switching frequencies is used
    238 	 * twice. This shouldn't happen very often.
    239 	 */
    240 	MFP->mf_tcdr = clk2min + r;
    241 
    242 	statclock(frame);
    243 }
    244 #endif /* STATCLOCK */
    245 
    246 /*
    247  * Returns number of usec since last recorded clock "tick"
    248  * (i.e. clock interrupt).
    249  */
    250 long
    251 clkread()
    252 {
    253 	u_int	delta;
    254 
    255 	delta = ((divisor - MFP->mf_tadr) * tick) / divisor;
    256 	/*
    257 	 * Account for pending clock interrupts
    258 	 */
    259 	if(MFP->mf_iera & IA_TIMA)
    260 		return(delta + tick);
    261 	return(delta);
    262 }
    263 
    264 #define TIMB_FREQ	614400
    265 #define TIMB_LIMIT	256
    266 
    267 /*
    268  * Wait "n" microseconds.
    269  * Relies on MFP-Timer B counting down from TIMB_LIMIT at TIMB_FREQ Hz.
    270  * Note: timer had better have been programmed before this is first used!
    271  */
    272 void
    273 delay(n)
    274 int	n;
    275 {
    276 	int	tick, otick;
    277 
    278 	/*
    279 	 * Read the counter first, so that the rest of the setup overhead is
    280 	 * counted.
    281 	 */
    282 	otick = MFP->mf_tbdr;
    283 
    284 	/*
    285 	 * Calculate ((n * TIMER_FREQ) / 1e6) using explicit assembler code so
    286 	 * we can take advantage of the intermediate 64-bit quantity to prevent
    287 	 * loss of significance.
    288 	 */
    289 	n -= 5;
    290 	if(n < 0)
    291 		return;
    292 	{
    293 	    u_int	temp;
    294 
    295 	    __asm __volatile ("mulul %2,%1:%0" : "=d" (n), "=d" (temp)
    296 					       : "d" (TIMB_FREQ));
    297 	    __asm __volatile ("divul %1,%2:%0" : "=d" (n)
    298 					       : "d"(1000000),"d"(temp),"0"(n));
    299 	}
    300 
    301 	while(n > 0) {
    302 		tick = MFP->mf_tbdr;
    303 		if(tick > otick)
    304 			n -= TIMB_LIMIT - (tick - otick);
    305 		else n -= otick - tick;
    306 		otick = tick;
    307 	}
    308 }
    309 
    310 #ifdef GPROF
    311 /*
    312  * profclock() is expanded in line in lev6intr() unless profiling kernel.
    313  * Assumes it is called with clock interrupts blocked.
    314  */
    315 profclock(pc, ps)
    316 	caddr_t pc;
    317 	int ps;
    318 {
    319 	/*
    320 	 * Came from user mode.
    321 	 * If this process is being profiled record the tick.
    322 	 */
    323 	if (USERMODE(ps)) {
    324 		if (p->p_stats.p_prof.pr_scale)
    325 			addupc(pc, &curproc->p_stats.p_prof, 1);
    326 	}
    327 	/*
    328 	 * Came from kernel (supervisor) mode.
    329 	 * If we are profiling the kernel, record the tick.
    330 	 */
    331 	else if (profiling < 2) {
    332 		register int s = pc - s_lowpc;
    333 
    334 		if (s < s_textsize)
    335 			kcount[s / (HISTFRACTION * sizeof (*kcount))]++;
    336 	}
    337 	/*
    338 	 * Kernel profiling was on but has been disabled.
    339 	 * Mark as no longer profiling kernel and if all profiling done,
    340 	 * disable the clock.
    341 	 */
    342 	if (profiling && (profon & PRF_KERNEL)) {
    343 		profon &= ~PRF_KERNEL;
    344 		if (profon == PRF_NONE)
    345 			stopprofclock();
    346 	}
    347 }
    348 #endif
    349 
    350 /***********************************************************************
    351  *                   Real Time Clock support                           *
    352  ***********************************************************************/
    353 
    354 u_int mc146818_read(rtc, regno)
    355 void	*rtc;
    356 u_int	regno;
    357 {
    358 	((struct rtc *)rtc)->rtc_regno = regno;
    359 	return(((struct rtc *)rtc)->rtc_data & 0377);
    360 }
    361 
    362 void mc146818_write(rtc, regno, value)
    363 void	*rtc;
    364 u_int	regno, value;
    365 {
    366 	((struct rtc *)rtc)->rtc_regno = regno;
    367 	((struct rtc *)rtc)->rtc_data  = value;
    368 }
    369 
    370 /*
    371  * Initialize the time of day register, assuming the RTC runs in UTC.
    372  * Since we've got the 'rtc' device, this functionality should be removed
    373  * from the kernel. The only problem to be solved before that can happen
    374  * is the possibility of init(1) providing a way (rc.boot?) to set
    375  * the RTC before single-user mode is entered.
    376  */
    377 void
    378 inittodr(base)
    379 time_t base;
    380 {
    381 	/* Battery clock does not store usec's, so forget about it. */
    382 	time.tv_sec  = gettod();
    383 	time.tv_usec = 0;
    384 }
    385 
    386 /*
    387  * Function turned into a No-op. Use /dev/rtc to update the RTC.
    388  */
    389 void
    390 resettodr()
    391 {
    392 	return;
    393 }
    394 
    395 static	char	dmsize[12] =
    396 {
    397 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    398 };
    399 
    400 static	char	ldmsize[12] =
    401 {
    402 	31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    403 };
    404 
    405 static u_long
    406 gettod()
    407 {
    408 	int		i, sps;
    409 	u_long		new_time = 0;
    410 	char		*msize;
    411 	mc_todregs	clkregs;
    412 
    413 	sps = splhigh();
    414 	MC146818_GETTOD(RTC, &clkregs);
    415 	splx(sps);
    416 
    417 	if(clkregs[MC_SEC] > 59)
    418 		return(0);
    419 	if(clkregs[MC_MIN] > 59)
    420 		return(0);
    421 	if(clkregs[MC_HOUR] > 23)
    422 		return(0);
    423 	if(range_test(clkregs[MC_DOM], 1, 31))
    424 		return(0);
    425 	if (range_test(clkregs[MC_MONTH], 1, 12))
    426 		return(0);
    427 	if(clkregs[MC_YEAR] > (2000 - GEMSTARTOFTIME))
    428 		return(0);
    429 	clkregs[MC_YEAR] += GEMSTARTOFTIME;
    430 
    431 	for(i = BSDSTARTOFTIME; i < clkregs[MC_YEAR]; i++) {
    432 		if(is_leap(i))
    433 			new_time += 366;
    434 		else new_time += 365;
    435 	}
    436 
    437 	msize = is_leap(clkregs[MC_YEAR]) ? ldmsize : dmsize;
    438 	for(i = 0; i < (clkregs[MC_MONTH] - 1); i++)
    439 		new_time += msize[i];
    440 	new_time += clkregs[MC_DOM] - 1;
    441 	new_time *= SECS_DAY;
    442 	new_time += (clkregs[MC_HOUR] * 3600) + (clkregs[MC_MIN] * 60);
    443 	return(new_time + clkregs[MC_SEC]);
    444 }
    445 /***********************************************************************
    446  *                   RTC-device support				       *
    447  ***********************************************************************/
    448 int
    449 rtcopen(dev, flag, mode, p)
    450 	dev_t		dev;
    451 	int		flag, mode;
    452 	struct proc	*p;
    453 {
    454 	int			unit = minor(dev);
    455 	struct clock_softc	*sc;
    456 
    457 	if (unit >= clock_cd.cd_ndevs)
    458 		return ENXIO;
    459 	sc = clock_cd.cd_devs[unit];
    460 	if (!sc)
    461 		return ENXIO;
    462 	if (sc->sc_flags & RTC_OPEN)
    463 		return EBUSY;
    464 
    465 	sc->sc_flags = RTC_OPEN;
    466 	return 0;
    467 }
    468 
    469 int
    470 rtcclose(dev, flag, mode, p)
    471 	dev_t		dev;
    472 	int		flag;
    473 	int		mode;
    474 	struct proc	*p;
    475 {
    476 	int			unit = minor(dev);
    477 	struct clock_softc	*sc = clock_cd.cd_devs[unit];
    478 
    479 	sc->sc_flags = 0;
    480 	return 0;
    481 }
    482 
    483 int
    484 rtcread(dev, uio, flags)
    485 	dev_t		dev;
    486 	struct uio	*uio;
    487 	int		flags;
    488 {
    489 	struct clock_softc	*sc;
    490 	mc_todregs		clkregs;
    491 	int			s, length;
    492 	char			buffer[16];
    493 
    494 	sc = clock_cd.cd_devs[minor(dev)];
    495 
    496 	s = splhigh();
    497 	MC146818_GETTOD(RTC, &clkregs);
    498 	splx(s);
    499 
    500 	sprintf(buffer, "%02d%02d%02d%02d%02d.%02d\n",
    501 	    clkregs[MC_YEAR] + GEMSTARTOFTIME - 1900,
    502 	    clkregs[MC_MONTH], clkregs[MC_DOM],
    503 	    clkregs[MC_HOUR], clkregs[MC_MIN], clkregs[MC_SEC]);
    504 
    505 	if (uio->uio_offset > strlen(buffer))
    506 		return 0;
    507 
    508 	length = strlen(buffer) - uio->uio_offset;
    509 	if (length > uio->uio_resid)
    510 		length = uio->uio_resid;
    511 
    512 	return(uiomove((caddr_t)buffer, length, uio));
    513 }
    514 
    515 static int
    516 twodigits(buffer, pos)
    517 	char *buffer;
    518 	int pos;
    519 {
    520 	int result = 0;
    521 
    522 	if (buffer[pos] >= '0' && buffer[pos] <= '9')
    523 		result = (buffer[pos] - '0') * 10;
    524 	if (buffer[pos+1] >= '0' && buffer[pos+1] <= '9')
    525 		result += (buffer[pos+1] - '0');
    526 	return(result);
    527 }
    528 
    529 int
    530 rtcwrite(dev, uio, flags)
    531 	dev_t		dev;
    532 	struct uio	*uio;
    533 	int		flags;
    534 {
    535 	mc_todregs		clkregs;
    536 	int			s, length, error;
    537 	char			buffer[14];
    538 
    539 	/*
    540 	 * We require atomic updates!
    541 	 */
    542 	length = uio->uio_resid;
    543 	if (uio->uio_offset || (length != sizeof(buffer)
    544 	  && length != sizeof(buffer - 1)))
    545 		return(EINVAL);
    546 
    547 	if ((error = uiomove((caddr_t)buffer, sizeof(buffer), uio)))
    548 		return(error);
    549 
    550 	if (length == sizeof(buffer) && buffer[sizeof(buffer) - 1] != '\n')
    551 		return(EINVAL);
    552 
    553 	s = splclock();
    554 	MC146818_GETTOD(RTC, &clkregs);
    555 	splx(s);
    556 
    557 	clkregs[MC_SEC]   = twodigits(buffer, 11);
    558 	clkregs[MC_MIN]   = twodigits(buffer, 8);
    559 	clkregs[MC_HOUR]  = twodigits(buffer, 6);
    560 	clkregs[MC_DOM]   = twodigits(buffer, 4);
    561 	clkregs[MC_MONTH] = twodigits(buffer, 2);
    562 	s = twodigits(buffer, 0);
    563 	s = (s < 70) ? s + 2000 : s + 1900;
    564 	clkregs[MC_YEAR]  = s - GEMSTARTOFTIME;
    565 
    566 	s = splclock();
    567 	MC146818_PUTTOD(RTC, &clkregs);
    568 	splx(s);
    569 
    570 	return(0);
    571 }
    572