Home | History | Annotate | Line # | Download | only in dev
clock.c revision 1.15
      1 /*	$NetBSD: clock.c,v 1.15 1996/12/16 22:03:23 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 (!atari_realconfig) {
    133 	    /*
    134 	     * Initialize Timer-B in the ST-MFP. This timer is used by
    135 	     * the 'delay' function below. This timer is setup to be
    136 	     * continueously counting from 255 back to zero at a
    137 	     * frequency of 614400Hz. We do this *early* in the
    138 	     * initialisation process.
    139 	     */
    140 	    MFP->mf_tbcr  = 0;		/* Stop timer			*/
    141 	    MFP->mf_iera &= ~IA_TIMB;	/* Disable timer interrupts	*/
    142 	    MFP->mf_tbdr  = 0;
    143 	    MFP->mf_tbcr  = T_Q004;	/* Start timer			*/
    144 
    145 	    /*
    146 	     * Initialize the time structure
    147 	     */
    148 	    time.tv_sec  = 0;
    149 	    time.tv_usec = 0;
    150 
    151 	    return 0;
    152 	}
    153 	if(!strcmp("clock", auxp))
    154 		return(1);
    155 	return(0);
    156 }
    157 
    158 /*
    159  * Start the real-time clock.
    160  */
    161 void clockattach(pdp, dp, auxp)
    162 struct device	*pdp, *dp;
    163 void		*auxp;
    164 {
    165 	struct clock_softc *sc = (void *)dp;
    166 
    167 	sc->sc_flags = 0;
    168 
    169 	/*
    170 	 * Initialize Timer-A in the ST-MFP. We use a divisor of 200.
    171 	 * The MFP clock runs at 2457600Hz. Therefore the timer runs
    172 	 * at an effective rate of: 2457600/200 = 12288Hz. The
    173 	 * following expression works for 48, 64 or 96 hz.
    174 	 */
    175 	divisor       = CLOCK_HZ/hz;
    176 	MFP->mf_tacr  = 0;		/* Stop timer			*/
    177 	MFP->mf_iera &= ~IA_TIMA;	/* Disable timer interrupts	*/
    178 	MFP->mf_tadr  = divisor;	/* Set divisor			*/
    179 
    180 	if (hz != 48 && hz != 64 && hz != 96) { /* XXX */
    181 		printf (": illegal value %d for systemclock, reset to %d\n\t",
    182 								hz, 64);
    183 		hz = 64;
    184 	}
    185 	printf(": system hz %d timer-A divisor 200/%d\n", hz, divisor);
    186 
    187 #ifdef STATCLOCK
    188 	if ((stathz == 0) || (stathz > hz) || (CLOCK_HZ % stathz))
    189 		stathz = hz;
    190 	if ((profhz == 0) || (profhz > (hz << 1)) || (CLOCK_HZ % profhz))
    191 		profhz = hz << 1;
    192 
    193 	MFP->mf_tcdcr &= 0x7;			/* Stop timer		*/
    194 	MFP->mf_ierb  &= ~IB_TIMC;		/* Disable timer inter.	*/
    195 	MFP->mf_tcdr   = CLOCK_HZ/stathz;	/* Set divisor		*/
    196 
    197 	statmin  = (CLOCK_HZ/stathz) - (statvar >> 1);
    198 	profmin  = (CLOCK_HZ/profhz) - (statvar >> 1);
    199 	clk2min  = statmin;
    200 #endif /* STATCLOCK */
    201 
    202 }
    203 
    204 void cpu_initclocks()
    205 {
    206 	MFP->mf_tacr  = T_Q200;		/* Start timer			*/
    207 	MFP->mf_ipra &= ~IA_TIMA;	/* Clear pending interrupts	*/
    208 	MFP->mf_iera |= IA_TIMA;	/* Enable timer interrupts	*/
    209 	MFP->mf_imra |= IA_TIMA;	/*    .....			*/
    210 
    211 #ifdef STATCLOCK
    212 	MFP->mf_tcdcr = (MFP->mf_tcdcr & 0x7) | (T_Q200<<4); /* Start	*/
    213 	MFP->mf_iprb &= ~IB_TIMC;	/* Clear pending interrupts	*/
    214 	MFP->mf_ierb |= IB_TIMC;	/* Enable timer interrupts	*/
    215 	MFP->mf_imrb |= IB_TIMC;	/*    .....			*/
    216 #endif /* STATCLOCK */
    217 }
    218 
    219 void
    220 setstatclockrate(newhz)
    221 	int newhz;
    222 {
    223 #ifdef STATCLOCK
    224 	if (newhz == stathz)
    225 		clk2min = statmin;
    226 	else clk2min = profmin;
    227 #endif /* STATCLOCK */
    228 }
    229 
    230 #ifdef STATCLOCK
    231 void
    232 statintr(frame)
    233 	register struct clockframe *frame;
    234 {
    235 	register int	var, r;
    236 
    237 	var = statvar - 1;
    238 	do {
    239 		r = random() & var;
    240 	} while(r == 0);
    241 
    242 	/*
    243 	 * Note that we are always lagging behind as the new divisor
    244 	 * value will not be loaded until the next interrupt. This
    245 	 * shouldn't disturb the median frequency (I think ;-) ) as
    246 	 * only the value used when switching frequencies is used
    247 	 * twice. This shouldn't happen very often.
    248 	 */
    249 	MFP->mf_tcdr = clk2min + r;
    250 
    251 	statclock(frame);
    252 }
    253 #endif /* STATCLOCK */
    254 
    255 /*
    256  * Returns number of usec since last recorded clock "tick"
    257  * (i.e. clock interrupt).
    258  */
    259 long
    260 clkread()
    261 {
    262 	u_int	delta;
    263 
    264 	delta = ((divisor - MFP->mf_tadr) * tick) / divisor;
    265 	/*
    266 	 * Account for pending clock interrupts
    267 	 */
    268 	if(MFP->mf_iera & IA_TIMA)
    269 		return(delta + tick);
    270 	return(delta);
    271 }
    272 
    273 #define TIMB_FREQ	614400
    274 #define TIMB_LIMIT	256
    275 
    276 /*
    277  * Wait "n" microseconds.
    278  * Relies on MFP-Timer B counting down from TIMB_LIMIT at TIMB_FREQ Hz.
    279  * Note: timer had better have been programmed before this is first used!
    280  */
    281 void
    282 delay(n)
    283 int	n;
    284 {
    285 	int	tick, otick;
    286 
    287 	/*
    288 	 * Read the counter first, so that the rest of the setup overhead is
    289 	 * counted.
    290 	 */
    291 	otick = MFP->mf_tbdr;
    292 
    293 	/*
    294 	 * Calculate ((n * TIMER_FREQ) / 1e6) using explicit assembler code so
    295 	 * we can take advantage of the intermediate 64-bit quantity to prevent
    296 	 * loss of significance.
    297 	 */
    298 	n -= 5;
    299 	if(n < 0)
    300 		return;
    301 	{
    302 	    u_int	temp;
    303 
    304 	    __asm __volatile ("mulul %2,%1:%0" : "=d" (n), "=d" (temp)
    305 					       : "d" (TIMB_FREQ));
    306 	    __asm __volatile ("divul %1,%2:%0" : "=d" (n)
    307 					       : "d"(1000000),"d"(temp),"0"(n));
    308 	}
    309 
    310 	while(n > 0) {
    311 		tick = MFP->mf_tbdr;
    312 		if(tick > otick)
    313 			n -= TIMB_LIMIT - (tick - otick);
    314 		else n -= otick - tick;
    315 		otick = tick;
    316 	}
    317 }
    318 
    319 #ifdef GPROF
    320 /*
    321  * profclock() is expanded in line in lev6intr() unless profiling kernel.
    322  * Assumes it is called with clock interrupts blocked.
    323  */
    324 profclock(pc, ps)
    325 	caddr_t pc;
    326 	int ps;
    327 {
    328 	/*
    329 	 * Came from user mode.
    330 	 * If this process is being profiled record the tick.
    331 	 */
    332 	if (USERMODE(ps)) {
    333 		if (p->p_stats.p_prof.pr_scale)
    334 			addupc(pc, &curproc->p_stats.p_prof, 1);
    335 	}
    336 	/*
    337 	 * Came from kernel (supervisor) mode.
    338 	 * If we are profiling the kernel, record the tick.
    339 	 */
    340 	else if (profiling < 2) {
    341 		register int s = pc - s_lowpc;
    342 
    343 		if (s < s_textsize)
    344 			kcount[s / (HISTFRACTION * sizeof (*kcount))]++;
    345 	}
    346 	/*
    347 	 * Kernel profiling was on but has been disabled.
    348 	 * Mark as no longer profiling kernel and if all profiling done,
    349 	 * disable the clock.
    350 	 */
    351 	if (profiling && (profon & PRF_KERNEL)) {
    352 		profon &= ~PRF_KERNEL;
    353 		if (profon == PRF_NONE)
    354 			stopprofclock();
    355 	}
    356 }
    357 #endif
    358 
    359 /***********************************************************************
    360  *                   Real Time Clock support                           *
    361  ***********************************************************************/
    362 
    363 u_int mc146818_read(rtc, regno)
    364 void	*rtc;
    365 u_int	regno;
    366 {
    367 	((struct rtc *)rtc)->rtc_regno = regno;
    368 	return(((struct rtc *)rtc)->rtc_data & 0377);
    369 }
    370 
    371 void mc146818_write(rtc, regno, value)
    372 void	*rtc;
    373 u_int	regno, value;
    374 {
    375 	((struct rtc *)rtc)->rtc_regno = regno;
    376 	((struct rtc *)rtc)->rtc_data  = value;
    377 }
    378 
    379 /*
    380  * Initialize the time of day register, assuming the RTC runs in UTC.
    381  * Since we've got the 'rtc' device, this functionality should be removed
    382  * from the kernel. The only problem to be solved before that can happen
    383  * is the possibility of init(1) providing a way (rc.boot?) to set
    384  * the RTC before single-user mode is entered.
    385  */
    386 void
    387 inittodr(base)
    388 time_t base;
    389 {
    390 	/* Battery clock does not store usec's, so forget about it. */
    391 	time.tv_sec  = gettod();
    392 	time.tv_usec = 0;
    393 }
    394 
    395 /*
    396  * Function turned into a No-op. Use /dev/rtc to update the RTC.
    397  */
    398 void
    399 resettodr()
    400 {
    401 	return;
    402 }
    403 
    404 static	char	dmsize[12] =
    405 {
    406 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    407 };
    408 
    409 static	char	ldmsize[12] =
    410 {
    411 	31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    412 };
    413 
    414 static u_long
    415 gettod()
    416 {
    417 	int		i, sps;
    418 	u_long		new_time = 0;
    419 	char		*msize;
    420 	mc_todregs	clkregs;
    421 
    422 	sps = splhigh();
    423 	MC146818_GETTOD(RTC, &clkregs);
    424 	splx(sps);
    425 
    426 	if(clkregs[MC_SEC] > 59)
    427 		return(0);
    428 	if(clkregs[MC_MIN] > 59)
    429 		return(0);
    430 	if(clkregs[MC_HOUR] > 23)
    431 		return(0);
    432 	if(range_test(clkregs[MC_DOM], 1, 31))
    433 		return(0);
    434 	if (range_test(clkregs[MC_MONTH], 1, 12))
    435 		return(0);
    436 	if(clkregs[MC_YEAR] > (2000 - GEMSTARTOFTIME))
    437 		return(0);
    438 	clkregs[MC_YEAR] += GEMSTARTOFTIME;
    439 
    440 	for(i = BSDSTARTOFTIME; i < clkregs[MC_YEAR]; i++) {
    441 		if(is_leap(i))
    442 			new_time += 366;
    443 		else new_time += 365;
    444 	}
    445 
    446 	msize = is_leap(clkregs[MC_YEAR]) ? ldmsize : dmsize;
    447 	for(i = 0; i < (clkregs[MC_MONTH] - 1); i++)
    448 		new_time += msize[i];
    449 	new_time += clkregs[MC_DOM] - 1;
    450 	new_time *= SECS_DAY;
    451 	new_time += (clkregs[MC_HOUR] * 3600) + (clkregs[MC_MIN] * 60);
    452 	return(new_time + clkregs[MC_SEC]);
    453 }
    454 /***********************************************************************
    455  *                   RTC-device support				       *
    456  ***********************************************************************/
    457 int
    458 rtcopen(dev, flag, mode, p)
    459 	dev_t		dev;
    460 	int		flag, mode;
    461 	struct proc	*p;
    462 {
    463 	int			unit = minor(dev);
    464 	struct clock_softc	*sc;
    465 
    466 	if (unit >= clock_cd.cd_ndevs)
    467 		return ENXIO;
    468 	sc = clock_cd.cd_devs[unit];
    469 	if (!sc)
    470 		return ENXIO;
    471 	if (sc->sc_flags & RTC_OPEN)
    472 		return EBUSY;
    473 
    474 	sc->sc_flags = RTC_OPEN;
    475 	return 0;
    476 }
    477 
    478 int
    479 rtcclose(dev, flag, mode, p)
    480 	dev_t		dev;
    481 	int		flag;
    482 	int		mode;
    483 	struct proc	*p;
    484 {
    485 	int			unit = minor(dev);
    486 	struct clock_softc	*sc = clock_cd.cd_devs[unit];
    487 
    488 	sc->sc_flags = 0;
    489 	return 0;
    490 }
    491 
    492 int
    493 rtcread(dev, uio, flags)
    494 	dev_t		dev;
    495 	struct uio	*uio;
    496 	int		flags;
    497 {
    498 	struct clock_softc	*sc;
    499 	mc_todregs		clkregs;
    500 	int			s, length;
    501 	char			buffer[16];
    502 
    503 	sc = clock_cd.cd_devs[minor(dev)];
    504 
    505 	s = splhigh();
    506 	MC146818_GETTOD(RTC, &clkregs);
    507 	splx(s);
    508 
    509 	sprintf(buffer, "%02d%02d%02d%02d%02d.%02d\n",
    510 	    clkregs[MC_YEAR] + GEMSTARTOFTIME - 1900,
    511 	    clkregs[MC_MONTH], clkregs[MC_DOM],
    512 	    clkregs[MC_HOUR], clkregs[MC_MIN], clkregs[MC_SEC]);
    513 
    514 	if (uio->uio_offset > strlen(buffer))
    515 		return 0;
    516 
    517 	length = strlen(buffer) - uio->uio_offset;
    518 	if (length > uio->uio_resid)
    519 		length = uio->uio_resid;
    520 
    521 	return(uiomove((caddr_t)buffer, length, uio));
    522 }
    523 
    524 static int
    525 twodigits(buffer, pos)
    526 	char *buffer;
    527 	int pos;
    528 {
    529 	int result = 0;
    530 
    531 	if (buffer[pos] >= '0' && buffer[pos] <= '9')
    532 		result = (buffer[pos] - '0') * 10;
    533 	if (buffer[pos+1] >= '0' && buffer[pos+1] <= '9')
    534 		result += (buffer[pos+1] - '0');
    535 	return(result);
    536 }
    537 
    538 int
    539 rtcwrite(dev, uio, flags)
    540 	dev_t		dev;
    541 	struct uio	*uio;
    542 	int		flags;
    543 {
    544 	mc_todregs		clkregs;
    545 	int			s, length, error;
    546 	char			buffer[14];
    547 
    548 	/*
    549 	 * We require atomic updates!
    550 	 */
    551 	length = uio->uio_resid;
    552 	if (uio->uio_offset || (length != sizeof(buffer)
    553 	  && length != sizeof(buffer - 1)))
    554 		return(EINVAL);
    555 
    556 	if ((error = uiomove((caddr_t)buffer, sizeof(buffer), uio)))
    557 		return(error);
    558 
    559 	if (length == sizeof(buffer) && buffer[sizeof(buffer) - 1] != '\n')
    560 		return(EINVAL);
    561 
    562 	s = splclock();
    563 	MC146818_GETTOD(RTC, &clkregs);
    564 	splx(s);
    565 
    566 	clkregs[MC_SEC]   = twodigits(buffer, 11);
    567 	clkregs[MC_MIN]   = twodigits(buffer, 8);
    568 	clkregs[MC_HOUR]  = twodigits(buffer, 6);
    569 	clkregs[MC_DOM]   = twodigits(buffer, 4);
    570 	clkregs[MC_MONTH] = twodigits(buffer, 2);
    571 	s = twodigits(buffer, 0);
    572 	s = (s < 70) ? s + 2000 : s + 1900;
    573 	clkregs[MC_YEAR]  = s - GEMSTARTOFTIME;
    574 
    575 	s = splclock();
    576 	MC146818_PUTTOD(RTC, &clkregs);
    577 	splx(s);
    578 
    579 	return(0);
    580 }
    581