xref: /netbsd/sys/arch/atari/dev/clock.c (revision c4a72b64)
1 /*	$NetBSD: clock.c,v 1.31 2002/10/23 09:10:48 jdolecek 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 <sys/event.h>
52 
53 #include <dev/clock_subr.h>
54 
55 #include <machine/psl.h>
56 #include <machine/cpu.h>
57 #include <machine/iomap.h>
58 #include <machine/mfp.h>
59 #include <atari/dev/clockreg.h>
60 #include <atari/atari/device.h>
61 
62 #if defined(GPROF) && defined(PROFTIMER)
63 #include <machine/profile.h>
64 #endif
65 
66 /*
67  * The MFP clock runs at 2457600Hz. We use a {system,stat,prof}clock divider
68  * of 200. Therefore the timer runs at an effective rate of:
69  * 2457600/200 = 12288Hz.
70  */
71 #define CLOCK_HZ	12288
72 
73 /*
74  * Machine-dependent clock routines.
75  *
76  * Inittodr initializes the time of day hardware which provides
77  * date functions.
78  *
79  * Resettodr restores the time of day hardware after a time change.
80  */
81 
82 struct clock_softc {
83 	struct device	sc_dev;
84 	int		sc_flags;
85 };
86 
87 /*
88  *  'sc_flags' state info. Only used by the rtc-device functions.
89  */
90 #define	RTC_OPEN	1
91 
92 dev_type_open(rtcopen);
93 dev_type_close(rtcclose);
94 dev_type_read(rtcread);
95 dev_type_write(rtcwrite);
96 
97 static void	clockattach __P((struct device *, struct device *, void *));
98 static int	clockmatch __P((struct device *, struct cfdata *, void *));
99 
100 CFATTACH_DECL(clock, sizeof(struct clock_softc),
101     clockmatch, clockattach, NULL, NULL);
102 
103 extern struct cfdriver clock_cd;
104 
105 const struct cdevsw rtc_cdevsw = {
106 	rtcopen, rtcclose, rtcread, rtcwrite, noioctl,
107 	nostop, notty, nopoll, nommap, nokqfilter,
108 };
109 
110 void statintr __P((struct clockframe));
111 
112 static u_long	gettod __P((void));
113 static int	twodigits __P((char *, int));
114 
115 static int	divisor;	/* Systemclock divisor	*/
116 
117 /*
118  * Statistics and profile clock intervals and variances. Variance must
119  * be a power of 2. Since this gives us an even number, not an odd number,
120  * we discard one case and compensate. That is, a variance of 64 would
121  * give us offsets in [0..63]. Instead, we take offsets in [1..63].
122  * This is symmetric around the point 32, or statvar/2, and thus averages
123  * to that value (assuming uniform random numbers).
124  */
125 #ifdef STATCLOCK
126 static int	statvar = 32;	/* {stat,prof}clock variance		*/
127 static int	statmin;	/* statclock divisor - variance/2	*/
128 static int	profmin;	/* profclock divisor - variance/2	*/
129 static int	clk2min;	/* current, from above choices		*/
130 #endif
131 
132 int
133 clockmatch(pdp, cfp, auxp)
134 struct device	*pdp;
135 struct cfdata	*cfp;
136 void		*auxp;
137 {
138 	if (!atari_realconfig) {
139 	    /*
140 	     * Initialize Timer-B in the ST-MFP. This timer is used by
141 	     * the 'delay' function below. This timer is setup to be
142 	     * continueously counting from 255 back to zero at a
143 	     * frequency of 614400Hz. We do this *early* in the
144 	     * initialisation process.
145 	     */
146 	    MFP->mf_tbcr  = 0;		/* Stop timer			*/
147 	    MFP->mf_iera &= ~IA_TIMB;	/* Disable timer interrupts	*/
148 	    MFP->mf_tbdr  = 0;
149 	    MFP->mf_tbcr  = T_Q004;	/* Start timer			*/
150 
151 	    /*
152 	     * Initialize the time structure
153 	     */
154 	    time.tv_sec  = 0;
155 	    time.tv_usec = 0;
156 
157 	    return 0;
158 	}
159 	if(!strcmp("clock", auxp))
160 		return(1);
161 	return(0);
162 }
163 
164 /*
165  * Start the real-time clock.
166  */
167 void clockattach(pdp, dp, auxp)
168 struct device	*pdp, *dp;
169 void		*auxp;
170 {
171 	struct clock_softc *sc = (void *)dp;
172 
173 	sc->sc_flags = 0;
174 
175 	/*
176 	 * Initialize Timer-A in the ST-MFP. We use a divisor of 200.
177 	 * The MFP clock runs at 2457600Hz. Therefore the timer runs
178 	 * at an effective rate of: 2457600/200 = 12288Hz. The
179 	 * following expression works for 48, 64 or 96 hz.
180 	 */
181 	divisor       = CLOCK_HZ/hz;
182 	MFP->mf_tacr  = 0;		/* Stop timer			*/
183 	MFP->mf_iera &= ~IA_TIMA;	/* Disable timer interrupts	*/
184 	MFP->mf_tadr  = divisor;	/* Set divisor			*/
185 
186 	if (hz != 48 && hz != 64 && hz != 96) { /* XXX */
187 		printf (": illegal value %d for systemclock, reset to %d\n\t",
188 								hz, 64);
189 		hz = 64;
190 	}
191 	printf(": system hz %d timer-A divisor 200/%d\n", hz, divisor);
192 
193 #ifdef STATCLOCK
194 	if ((stathz == 0) || (stathz > hz) || (CLOCK_HZ % stathz))
195 		stathz = hz;
196 	if ((profhz == 0) || (profhz > (hz << 1)) || (CLOCK_HZ % profhz))
197 		profhz = hz << 1;
198 
199 	MFP->mf_tcdcr &= 0x7;			/* Stop timer		*/
200 	MFP->mf_ierb  &= ~IB_TIMC;		/* Disable timer inter.	*/
201 	MFP->mf_tcdr   = CLOCK_HZ/stathz;	/* Set divisor		*/
202 
203 	statmin  = (CLOCK_HZ/stathz) - (statvar >> 1);
204 	profmin  = (CLOCK_HZ/profhz) - (statvar >> 1);
205 	clk2min  = statmin;
206 #endif /* STATCLOCK */
207 
208 }
209 
210 void cpu_initclocks()
211 {
212 	MFP->mf_tacr  = T_Q200;		/* Start timer			*/
213 	MFP->mf_ipra  = (u_int8_t)~IA_TIMA;/* Clear pending interrupts	*/
214 	MFP->mf_iera |= IA_TIMA;	/* Enable timer interrupts	*/
215 	MFP->mf_imra |= IA_TIMA;	/*    .....			*/
216 
217 #ifdef STATCLOCK
218 	MFP->mf_tcdcr = (MFP->mf_tcdcr & 0x7) | (T_Q200<<4); /* Start	*/
219 	MFP->mf_iprb  = (u_int8_t)~IB_TIMC;/* Clear pending interrupts	*/
220 	MFP->mf_ierb |= IB_TIMC;	/* Enable timer interrupts	*/
221 	MFP->mf_imrb |= IB_TIMC;	/*    .....			*/
222 #endif /* STATCLOCK */
223 }
224 
225 void
226 setstatclockrate(newhz)
227 	int newhz;
228 {
229 #ifdef STATCLOCK
230 	if (newhz == stathz)
231 		clk2min = statmin;
232 	else clk2min = profmin;
233 #endif /* STATCLOCK */
234 }
235 
236 #ifdef STATCLOCK
237 void
238 statintr(frame)
239 	struct clockframe frame;
240 {
241 	register int	var, r;
242 
243 	var = statvar - 1;
244 	do {
245 		r = random() & var;
246 	} while(r == 0);
247 
248 	/*
249 	 * Note that we are always lagging behind as the new divisor
250 	 * value will not be loaded until the next interrupt. This
251 	 * shouldn't disturb the median frequency (I think ;-) ) as
252 	 * only the value used when switching frequencies is used
253 	 * twice. This shouldn't happen very often.
254 	 */
255 	MFP->mf_tcdr = clk2min + r;
256 
257 	statclock(&frame);
258 }
259 #endif /* STATCLOCK */
260 
261 /*
262  * Returns number of usec since last recorded clock "tick"
263  * (i.e. clock interrupt).
264  */
265 long
266 clkread()
267 {
268 	u_int	delta;
269 	u_char	ipra, tadr;
270 
271 	/*
272 	 * Note: Order is important!
273 	 * By reading 'ipra' before 'tadr' and caching the data, I try to avoid
274 	 * the situation that very low value in 'tadr' is read (== a big delta)
275 	 * while also acccounting for a full 'tick' because the counter went
276 	 * through zero during the calculations.
277 	 */
278 	ipra = MFP->mf_ipra; tadr = MFP->mf_tadr;
279 
280 	delta = ((divisor - tadr) * tick) / divisor;
281 	/*
282 	 * Account for pending clock interrupts
283 	 */
284 	if(ipra & IA_TIMA)
285 		return(delta + tick);
286 	return(delta);
287 }
288 
289 #define TIMB_FREQ	614400
290 #define TIMB_LIMIT	256
291 
292 /*
293  * Wait "n" microseconds.
294  * Relies on MFP-Timer B counting down from TIMB_LIMIT at TIMB_FREQ Hz.
295  * Note: timer had better have been programmed before this is first used!
296  */
297 void
298 delay(n)
299 int	n;
300 {
301 	int	tick, otick;
302 
303 	/*
304 	 * Read the counter first, so that the rest of the setup overhead is
305 	 * counted.
306 	 */
307 	otick = MFP->mf_tbdr;
308 
309 	/*
310 	 * Calculate ((n * TIMER_FREQ) / 1e6) using explicit assembler code so
311 	 * we can take advantage of the intermediate 64-bit quantity to prevent
312 	 * loss of significance.
313 	 */
314 	n -= 5;
315 	if(n < 0)
316 		return;
317 	{
318 	    u_int	temp;
319 
320 	    __asm __volatile ("mulul %2,%1:%0" : "=d" (n), "=d" (temp)
321 					       : "d" (TIMB_FREQ), "d" (n));
322 	    __asm __volatile ("divul %1,%2:%0" : "=d" (n)
323 					       : "d"(1000000),"d"(temp),"0"(n));
324 	}
325 
326 	while(n > 0) {
327 		tick = MFP->mf_tbdr;
328 		if(tick > otick)
329 			n -= TIMB_LIMIT - (tick - otick);
330 		else n -= otick - tick;
331 		otick = tick;
332 	}
333 }
334 
335 #ifdef GPROF
336 /*
337  * profclock() is expanded in line in lev6intr() unless profiling kernel.
338  * Assumes it is called with clock interrupts blocked.
339  */
340 profclock(pc, ps)
341 	caddr_t pc;
342 	int ps;
343 {
344 	/*
345 	 * Came from user mode.
346 	 * If this process is being profiled record the tick.
347 	 */
348 	if (USERMODE(ps)) {
349 		if (p->p_stats.p_prof.pr_scale)
350 			addupc(pc, &curproc->p_stats.p_prof, 1);
351 	}
352 	/*
353 	 * Came from kernel (supervisor) mode.
354 	 * If we are profiling the kernel, record the tick.
355 	 */
356 	else if (profiling < 2) {
357 		register int s = pc - s_lowpc;
358 
359 		if (s < s_textsize)
360 			kcount[s / (HISTFRACTION * sizeof (*kcount))]++;
361 	}
362 	/*
363 	 * Kernel profiling was on but has been disabled.
364 	 * Mark as no longer profiling kernel and if all profiling done,
365 	 * disable the clock.
366 	 */
367 	if (profiling && (profon & PRF_KERNEL)) {
368 		profon &= ~PRF_KERNEL;
369 		if (profon == PRF_NONE)
370 			stopprofclock();
371 	}
372 }
373 #endif
374 
375 /***********************************************************************
376  *                   Real Time Clock support                           *
377  ***********************************************************************/
378 
379 u_int mc146818_read(rtc, regno)
380 void	*rtc;
381 u_int	regno;
382 {
383 	((struct rtc *)rtc)->rtc_regno = regno;
384 	return(((struct rtc *)rtc)->rtc_data & 0377);
385 }
386 
387 void mc146818_write(rtc, regno, value)
388 void	*rtc;
389 u_int	regno, value;
390 {
391 	((struct rtc *)rtc)->rtc_regno = regno;
392 	((struct rtc *)rtc)->rtc_data  = value;
393 }
394 
395 /*
396  * Initialize the time of day register, assuming the RTC runs in UTC.
397  * Since we've got the 'rtc' device, this functionality should be removed
398  * from the kernel. The only problem to be solved before that can happen
399  * is the possibility of init(1) providing a way (rc.boot?) to set
400  * the RTC before single-user mode is entered.
401  */
402 void
403 inittodr(base)
404 time_t base;
405 {
406 	/* Battery clock does not store usec's, so forget about it. */
407 	time.tv_sec  = gettod();
408 	time.tv_usec = 0;
409 }
410 
411 /*
412  * Function turned into a No-op. Use /dev/rtc to update the RTC.
413  */
414 void
415 resettodr()
416 {
417 	return;
418 }
419 
420 static u_long
421 gettod()
422 {
423 	int			sps;
424 	mc_todregs		clkregs;
425 	u_int			regb;
426 	struct clock_ymdhms	dt;
427 
428 	sps = splhigh();
429 	regb = mc146818_read(RTC, MC_REGB);
430 	MC146818_GETTOD(RTC, &clkregs);
431 	splx(sps);
432 
433 	regb &= MC_REGB_24HR|MC_REGB_BINARY;
434 	if (regb != (MC_REGB_24HR|MC_REGB_BINARY)) {
435 		printf("Error: Nonstandard RealTimeClock Configuration -"
436 			" value ignored\n"
437 			"       A write to /dev/rtc will correct this.\n");
438 			return(0);
439 	}
440 	if(clkregs[MC_SEC] > 59)
441 		return(0);
442 	if(clkregs[MC_MIN] > 59)
443 		return(0);
444 	if(clkregs[MC_HOUR] > 23)
445 		return(0);
446 	if(range_test(clkregs[MC_DOM], 1, 31))
447 		return(0);
448 	if (range_test(clkregs[MC_MONTH], 1, 12))
449 		return(0);
450 	if(clkregs[MC_YEAR] > 99)
451 		return(0);
452 
453 	dt.dt_year = clkregs[MC_YEAR] + GEMSTARTOFTIME;
454 	dt.dt_mon  = clkregs[MC_MONTH];
455 	dt.dt_day  = clkregs[MC_DOM];
456 	dt.dt_hour = clkregs[MC_HOUR];
457 	dt.dt_min  = clkregs[MC_MIN];
458 	dt.dt_sec  = clkregs[MC_SEC];
459 
460 	return(clock_ymdhms_to_secs(&dt));
461 }
462 /***********************************************************************
463  *                   RTC-device support				       *
464  ***********************************************************************/
465 int
466 rtcopen(dev, flag, mode, p)
467 	dev_t		dev;
468 	int		flag, mode;
469 	struct proc	*p;
470 {
471 	int			unit = minor(dev);
472 	struct clock_softc	*sc;
473 
474 	if (unit >= clock_cd.cd_ndevs)
475 		return ENXIO;
476 	sc = clock_cd.cd_devs[unit];
477 	if (!sc)
478 		return ENXIO;
479 	if (sc->sc_flags & RTC_OPEN)
480 		return EBUSY;
481 
482 	sc->sc_flags = RTC_OPEN;
483 	return 0;
484 }
485 
486 int
487 rtcclose(dev, flag, mode, p)
488 	dev_t		dev;
489 	int		flag;
490 	int		mode;
491 	struct proc	*p;
492 {
493 	int			unit = minor(dev);
494 	struct clock_softc	*sc = clock_cd.cd_devs[unit];
495 
496 	sc->sc_flags = 0;
497 	return 0;
498 }
499 
500 int
501 rtcread(dev, uio, flags)
502 	dev_t		dev;
503 	struct uio	*uio;
504 	int		flags;
505 {
506 	struct clock_softc	*sc;
507 	mc_todregs		clkregs;
508 	int			s, length;
509 	char			buffer[16];
510 
511 	sc = clock_cd.cd_devs[minor(dev)];
512 
513 	s = splhigh();
514 	MC146818_GETTOD(RTC, &clkregs);
515 	splx(s);
516 
517 	sprintf(buffer, "%4d%02d%02d%02d%02d.%02d\n",
518 	    clkregs[MC_YEAR] + GEMSTARTOFTIME,
519 	    clkregs[MC_MONTH], clkregs[MC_DOM],
520 	    clkregs[MC_HOUR], clkregs[MC_MIN], clkregs[MC_SEC]);
521 
522 	if (uio->uio_offset > strlen(buffer))
523 		return 0;
524 
525 	length = strlen(buffer) - uio->uio_offset;
526 	if (length > uio->uio_resid)
527 		length = uio->uio_resid;
528 
529 	return(uiomove((caddr_t)buffer, length, uio));
530 }
531 
532 static int
533 twodigits(buffer, pos)
534 	char *buffer;
535 	int pos;
536 {
537 	int result = 0;
538 
539 	if (buffer[pos] >= '0' && buffer[pos] <= '9')
540 		result = (buffer[pos] - '0') * 10;
541 	if (buffer[pos+1] >= '0' && buffer[pos+1] <= '9')
542 		result += (buffer[pos+1] - '0');
543 	return(result);
544 }
545 
546 int
547 rtcwrite(dev, uio, flags)
548 	dev_t		dev;
549 	struct uio	*uio;
550 	int		flags;
551 {
552 	mc_todregs		clkregs;
553 	int			s, length, error;
554 	char			buffer[16];
555 
556 	/*
557 	 * We require atomic updates!
558 	 */
559 	length = uio->uio_resid;
560 	if (uio->uio_offset || (length != sizeof(buffer)
561 	  && length != sizeof(buffer - 1)))
562 		return(EINVAL);
563 
564 	if ((error = uiomove((caddr_t)buffer, sizeof(buffer), uio)))
565 		return(error);
566 
567 	if (length == sizeof(buffer) && buffer[sizeof(buffer) - 1] != '\n')
568 		return(EINVAL);
569 
570 	s = splclock();
571 	mc146818_write(RTC, MC_REGB,
572 		mc146818_read(RTC, MC_REGB) | MC_REGB_24HR | MC_REGB_BINARY);
573 	MC146818_GETTOD(RTC, &clkregs);
574 	splx(s);
575 
576 	clkregs[MC_SEC]   = twodigits(buffer, 13);
577 	clkregs[MC_MIN]   = twodigits(buffer, 10);
578 	clkregs[MC_HOUR]  = twodigits(buffer, 8);
579 	clkregs[MC_DOM]   = twodigits(buffer, 6);
580 	clkregs[MC_MONTH] = twodigits(buffer, 4);
581 	s = twodigits(buffer, 0) * 100 + twodigits(buffer, 2);
582 	clkregs[MC_YEAR]  = s - GEMSTARTOFTIME;
583 
584 	s = splclock();
585 	MC146818_PUTTOD(RTC, &clkregs);
586 	splx(s);
587 
588 	return(0);
589 }
590