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