1/*
2 *  linux/arch/alpha/kernel/time.c
3 *
4 *  Copyright (C) 1991, 1992, 1995, 1999, 2000  Linus Torvalds
5 *
6 * This file contains the PC-specific time handling details:
7 * reading the RTC at bootup, etc..
8 * 1994-07-02    Alan Modra
9 *	fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime
10 * 1995-03-26    Markus Kuhn
11 *      fixed 500 ms bug at call to set_rtc_mmss, fixed DS12887
12 *      precision CMOS clock update
13 * 1997-09-10	Updated NTP code according to technical memorandum Jan '96
14 *		"A Kernel Model for Precision Timekeeping" by Dave Mills
15 * 1997-01-09    Adrian Sun
16 *      use interval timer if CONFIG_RTC=y
17 * 1997-10-29    John Bowman (bowman@math.ualberta.ca)
18 *      fixed tick loss calculation in timer_interrupt
19 *      (round system clock to nearest tick instead of truncating)
20 *      fixed algorithm in time_init for getting time from CMOS clock
21 * 1999-04-16	Thorsten Kranzkowski (dl8bcu@gmx.net)
22 *	fixed algorithm in do_gettimeofday() for calculating the precise time
23 *	from processor cycle counter (now taking lost_ticks into account)
24 * 2000-08-13	Jan-Benedict Glaw <jbglaw@lug-owl.de>
25 * 	Fixed time_init to be aware of epoches != 1900. This prevents
26 * 	booting up in 2048 for me;) Code is stolen from rtc.c.
27 */
28#include <linux/config.h>
29#include <linux/errno.h>
30#include <linux/sched.h>
31#include <linux/kernel.h>
32#include <linux/param.h>
33#include <linux/string.h>
34#include <linux/mm.h>
35#include <linux/delay.h>
36#include <linux/ioport.h>
37#include <linux/irq.h>
38#include <linux/interrupt.h>
39#include <linux/init.h>
40
41#include <asm/uaccess.h>
42#include <asm/io.h>
43#include <asm/hwrpb.h>
44
45#include <linux/mc146818rtc.h>
46#include <linux/timex.h>
47
48#include "proto.h"
49#include "irq_impl.h"
50
51extern rwlock_t xtime_lock;
52extern unsigned long wall_jiffies;	/* kernel/timer.c */
53
54static int set_rtc_mmss(unsigned long);
55
56spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
57
58/*
59 * Shift amount by which scaled_ticks_per_cycle is scaled.  Shifting
60 * by 48 gives us 16 bits for HZ while keeping the accuracy good even
61 * for large CPU clock rates.
62 */
63#define FIX_SHIFT	48
64
65/* lump static variables together for more efficient access: */
66static struct {
67	/* cycle counter last time it got invoked */
68	__u32 last_time;
69	/* ticks/cycle * 2^48 */
70	unsigned long scaled_ticks_per_cycle;
71	/* last time the CMOS clock got updated */
72	time_t last_rtc_update;
73	/* partial unused tick */
74	unsigned long partial_tick;
75} state;
76
77unsigned long est_cycle_freq;
78
79
80static inline __u32 rpcc(void)
81{
82    __u32 result;
83    asm volatile ("rpcc %0" : "=r"(result));
84    return result;
85}
86
87
88/*
89 * timer_interrupt() needs to keep up the real-time clock,
90 * as well as call the "do_timer()" routine every clocktick
91 */
92void timer_interrupt(int irq, void *dev, struct pt_regs * regs)
93{
94	unsigned long delta;
95	__u32 now;
96	long nticks;
97
98#ifndef CONFIG_SMP
99	/* Not SMP, do kernel PC profiling here.  */
100	if (!user_mode(regs))
101		alpha_do_profile(regs->pc);
102#endif
103
104	write_lock(&xtime_lock);
105
106	/*
107	 * Calculate how many ticks have passed since the last update,
108	 * including any previous partial leftover.  Save any resulting
109	 * fraction for the next pass.
110	 */
111	now = rpcc();
112	delta = now - state.last_time;
113	state.last_time = now;
114	delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
115	state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1);
116	nticks = delta >> FIX_SHIFT;
117
118	while (nticks > 0) {
119		do_timer(regs);
120		nticks--;
121	}
122
123	/*
124	 * If we have an externally synchronized Linux clock, then update
125	 * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
126	 * called as close as possible to 500 ms before the new second starts.
127	 */
128	if ((time_status & STA_UNSYNC) == 0
129	    && xtime.tv_sec > state.last_rtc_update + 660
130	    && xtime.tv_usec >= 500000 - ((unsigned) tick) / 2
131	    && xtime.tv_usec <= 500000 + ((unsigned) tick) / 2) {
132		int tmp = set_rtc_mmss(xtime.tv_sec);
133		state.last_rtc_update = xtime.tv_sec - (tmp ? 600 : 0);
134	}
135
136	write_unlock(&xtime_lock);
137}
138
139void
140common_init_rtc(void)
141{
142	unsigned char x;
143
144	/* Reset periodic interrupt frequency.  */
145	x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
146	if (x != 0x26 && x != 0x19 && x != 0x06) {
147		printk("Setting RTC_FREQ to 1024 Hz (%x)\n", x);
148		CMOS_WRITE(0x26, RTC_FREQ_SELECT);
149	}
150
151	/* Turn on periodic interrupts.  */
152	x = CMOS_READ(RTC_CONTROL);
153	if (!(x & RTC_PIE)) {
154		printk("Turning on RTC interrupts.\n");
155		x |= RTC_PIE;
156		x &= ~(RTC_AIE | RTC_UIE);
157		CMOS_WRITE(x, RTC_CONTROL);
158	}
159	(void) CMOS_READ(RTC_INTR_FLAGS);
160
161	outb(0x36, 0x43);	/* pit counter 0: system timer */
162	outb(0x00, 0x40);
163	outb(0x00, 0x40);
164
165	outb(0xb6, 0x43);	/* pit counter 2: speaker */
166	outb(0x31, 0x42);
167	outb(0x13, 0x42);
168
169	init_rtc_irq();
170}
171
172
173/* Validate a computed cycle counter result against the known bounds for
174   the given processor core.  There's too much brokenness in the way of
175   timing hardware for any one method to work everywhere.  :-(
176
177   Return 0 if the result cannot be trusted, otherwise return the argument.  */
178
179static unsigned long __init
180validate_cc_value(unsigned long cc)
181{
182	static struct bounds {
183		unsigned int min, max;
184	} cpu_hz[] __initdata = {
185		[EV3_CPU]    = {   50000000,  200000000 },	/* guess */
186		[EV4_CPU]    = {  150000000,  300000000 },
187		[LCA4_CPU]   = {  150000000,  300000000 },	/* guess */
188		[EV45_CPU]   = {  200000000,  300000000 },
189		[EV5_CPU]    = {  250000000,  433000000 },
190		[EV56_CPU]   = {  333000000,  667000000 },
191		[PCA56_CPU]  = {  400000000,  600000000 },	/* guess */
192		[PCA57_CPU]  = {  500000000,  600000000 },	/* guess */
193		[EV6_CPU]    = {  466000000,  600000000 },
194		[EV67_CPU]   = {  600000000,  750000000 },
195		[EV68AL_CPU] = {  750000000,  940000000 },
196		[EV68CB_CPU] = { 1000000000, 1333333333 },
197		/* None of the following are shipping as of 2001-11-01.  */
198		[EV68CX_CPU] = { 1000000000, 1700000000 },	/* guess */
199		[EV69_CPU]   = { 1000000000, 1700000000 },	/* guess */
200		[EV7_CPU]    = {  800000000, 1400000000 },	/* guess */
201		[EV79_CPU]   = { 1000000000, 2000000000 },	/* guess */
202	};
203
204	/* Allow for some drift in the crystal.  10MHz is more than enough.  */
205	const unsigned int deviation = 10000000;
206
207	struct percpu_struct *cpu;
208	unsigned int index;
209
210	cpu = (struct percpu_struct *)((char*)hwrpb + hwrpb->processor_offset);
211	index = cpu->type & 0xffffffff;
212
213	/* If index out of bounds, no way to validate.  */
214	if (index >= sizeof(cpu_hz)/sizeof(cpu_hz[0]))
215		return cc;
216
217	/* If index contains no data, no way to validate.  */
218	if (cpu_hz[index].max == 0)
219		return cc;
220
221	if (cc < cpu_hz[index].min - deviation
222	    || cc > cpu_hz[index].max + deviation)
223		return 0;
224
225	return cc;
226}
227
228
229/*
230 * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
231 * arch/i386/time.c.
232 */
233
234#define CALIBRATE_LATCH	(52 * LATCH)
235#define CALIBRATE_TIME	(52 * 1000020 / HZ)
236
237static unsigned long __init
238calibrate_cc_with_pic(void)
239{
240	int cc, count = 0;
241
242	/* Set the Gate high, disable speaker */
243	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
244
245	/*
246	 * Now let's take care of CTC channel 2
247	 *
248	 * Set the Gate high, program CTC channel 2 for mode 0,
249	 * (interrupt on terminal count mode), binary count,
250	 * load 5 * LATCH count, (LSB and MSB) to begin countdown.
251	 */
252	outb(0xb0, 0x43);		/* binary, mode 0, LSB/MSB, Ch 2 */
253	outb(CALIBRATE_LATCH & 0xff, 0x42);	/* LSB of count */
254	outb(CALIBRATE_LATCH >> 8, 0x42);	/* MSB of count */
255
256	cc = rpcc();
257	do {
258		count++;
259	} while ((inb(0x61) & 0x20) == 0 && count > 0);
260	cc = rpcc() - cc;
261
262	/* Error: ECTCNEVERSET or ECPUTOOFAST.  */
263	if (count <= 1)
264		return 0;
265
266	/* Error: ECPUTOOSLOW.  */
267	if (cc <= CALIBRATE_TIME)
268		return 0;
269
270	return (cc * 1000000UL) / CALIBRATE_TIME;
271}
272
273/* The Linux interpretation of the CMOS clock register contents:
274   When the Update-In-Progress (UIP) flag goes from 1 to 0, the
275   RTC registers show the second which has precisely just started.
276   Let's hope other operating systems interpret the RTC the same way.  */
277
278static unsigned long __init
279rpcc_after_update_in_progress(void)
280{
281	do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
282	do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
283
284	return rpcc();
285}
286
287void __init
288time_init(void)
289{
290	unsigned int year, mon, day, hour, min, sec, cc1, cc2, epoch;
291	unsigned long cycle_freq, one_percent;
292	long diff;
293
294	/* Calibrate CPU clock -- attempt #1.  */
295	if (!est_cycle_freq)
296		est_cycle_freq = validate_cc_value(calibrate_cc_with_pic());
297
298	cc1 = rpcc_after_update_in_progress();
299
300	/* Calibrate CPU clock -- attempt #2.  */
301	if (!est_cycle_freq) {
302		cc2 = rpcc_after_update_in_progress();
303		est_cycle_freq = validate_cc_value(cc2 - cc1);
304		cc1 = cc2;
305	}
306
307	cycle_freq = hwrpb->cycle_freq;
308	if (est_cycle_freq) {
309		/* If the given value is within 1% of what we calculated,
310		   accept it.  Otherwise, use what we found.  */
311		one_percent = cycle_freq / 100;
312		diff = cycle_freq - est_cycle_freq;
313		if (diff < 0)
314			diff = -diff;
315		if (diff > one_percent) {
316			cycle_freq = est_cycle_freq;
317			printk("HWRPB cycle frequency bogus.  "
318			       "Estimated %lu Hz\n", cycle_freq);
319		} else {
320			est_cycle_freq = 0;
321		}
322	} else if (! validate_cc_value (cycle_freq)) {
323		printk("HWRPB cycle frequency bogus, "
324		       "and unable to estimate a proper value!\n");
325	}
326
327	/* From John Bowman <bowman@math.ualberta.ca>: allow the values
328	   to settle, as the Update-In-Progress bit going low isn't good
329	   enough on some hardware.  2ms is our guess; we havn't found
330	   bogomips yet, but this is close on a 500Mhz box.  */
331	__delay(1000000);
332
333	sec = CMOS_READ(RTC_SECONDS);
334	min = CMOS_READ(RTC_MINUTES);
335	hour = CMOS_READ(RTC_HOURS);
336	day = CMOS_READ(RTC_DAY_OF_MONTH);
337	mon = CMOS_READ(RTC_MONTH);
338	year = CMOS_READ(RTC_YEAR);
339
340	if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
341		BCD_TO_BIN(sec);
342		BCD_TO_BIN(min);
343		BCD_TO_BIN(hour);
344		BCD_TO_BIN(day);
345		BCD_TO_BIN(mon);
346		BCD_TO_BIN(year);
347	}
348
349	/* PC-like is standard; used for year < 20 || year >= 70 */
350	epoch = 1900;
351	if (year < 20)
352		epoch = 2000;
353	else if (year >= 20 && year < 48)
354		/* NT epoch */
355		epoch = 1980;
356	else if (year >= 48 && year < 70)
357		/* Digital UNIX epoch */
358		epoch = 1952;
359
360	printk(KERN_INFO "Using epoch = %d\n", epoch);
361
362	if ((year += epoch) < 1970)
363		year += 100;
364
365	xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
366	xtime.tv_usec = 0;
367
368	if (HZ > (1<<16)) {
369		extern void __you_loose (void);
370		__you_loose();
371	}
372
373	state.last_time = cc1;
374	state.scaled_ticks_per_cycle
375		= ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
376	state.last_rtc_update = 0;
377	state.partial_tick = 0L;
378
379	/* Startup the timer source. */
380	alpha_mv.init_rtc();
381
382	/*
383	 * If we had wanted SRM console printk echoing early, undo it now.
384	 *
385	 * "srmcons" specified in the boot command arguments allows us to
386	 * see kernel messages during the period of time before the true
387	 * console device is "registered" during console_init(). As of this
388	 * version (2.4.10), time_init() is the last Alpha-specific code
389	 * called before console_init(), so we put this "unregister" code
390	 * here to prevent schizophrenic console behavior later... ;-}
391	 */
392	if (alpha_using_srm && srmcons_output) {
393		unregister_srm_console();
394		srmcons_output = 0;
395	}
396}
397
398/*
399 * Use the cycle counter to estimate an displacement from the last time
400 * tick.  Unfortunately the Alpha designers made only the low 32-bits of
401 * the cycle counter active, so we overflow on 8.2 seconds on a 500MHz
402 * part.  So we can't do the "find absolute time in terms of cycles" thing
403 * that the other ports do.
404 */
405void
406do_gettimeofday(struct timeval *tv)
407{
408	unsigned long sec, usec, lost, flags;
409	unsigned long delta_cycles, delta_usec, partial_tick;
410
411	read_lock_irqsave(&xtime_lock, flags);
412
413	delta_cycles = rpcc() - state.last_time;
414	sec = xtime.tv_sec;
415	usec = xtime.tv_usec;
416	partial_tick = state.partial_tick;
417	lost = jiffies - wall_jiffies;
418
419	read_unlock_irqrestore(&xtime_lock, flags);
420
421#ifdef CONFIG_SMP
422	/* Until and unless we figure out how to get cpu cycle counters
423	   in sync and keep them there, we can't use the rpcc tricks.  */
424	delta_usec = lost * (1000000 / HZ);
425#else
426	/*
427	 * usec = cycles * ticks_per_cycle * 2**48 * 1e6 / (2**48 * ticks)
428	 *	= cycles * (s_t_p_c) * 1e6 / (2**48 * ticks)
429	 *	= cycles * (s_t_p_c) * 15625 / (2**42 * ticks)
430	 *
431	 * which, given a 600MHz cycle and a 1024Hz tick, has a
432	 * dynamic range of about 1.7e17, which is less than the
433	 * 1.8e19 in an unsigned long, so we are safe from overflow.
434	 *
435	 * Round, but with .5 up always, since .5 to even is harder
436	 * with no clear gain.
437	 */
438
439	delta_usec = (delta_cycles * state.scaled_ticks_per_cycle
440		      + partial_tick
441		      + (lost << FIX_SHIFT)) * 15625;
442	delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
443#endif
444
445	usec += delta_usec;
446	if (usec >= 1000000) {
447		sec += 1;
448		usec -= 1000000;
449	}
450
451	tv->tv_sec = sec;
452	tv->tv_usec = usec;
453}
454
455void
456do_settimeofday(struct timeval *tv)
457{
458	unsigned long delta_usec;
459	long sec, usec;
460
461	write_lock_irq(&xtime_lock);
462
463	/* The offset that is added into time in do_gettimeofday above
464	   must be subtracted out here to keep a coherent view of the
465	   time.  Without this, a full-tick error is possible.  */
466
467#ifdef CONFIG_SMP
468	delta_usec = (jiffies - wall_jiffies) * (1000000 / HZ);
469#else
470	delta_usec = rpcc() - state.last_time;
471	delta_usec = (delta_usec * state.scaled_ticks_per_cycle
472		      + state.partial_tick
473		      + ((jiffies - wall_jiffies) << FIX_SHIFT)) * 15625;
474	delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
475#endif
476
477	sec = tv->tv_sec;
478	usec = tv->tv_usec;
479	usec -= delta_usec;
480	if (usec < 0) {
481		usec += 1000000;
482		sec -= 1;
483	}
484
485	xtime.tv_sec = sec;
486	xtime.tv_usec = usec;
487	time_adjust = 0;		/* stop active adjtime() */
488	time_status |= STA_UNSYNC;
489	time_maxerror = NTP_PHASE_LIMIT;
490	time_esterror = NTP_PHASE_LIMIT;
491
492	write_unlock_irq(&xtime_lock);
493}
494
495
496/*
497 * In order to set the CMOS clock precisely, set_rtc_mmss has to be
498 * called 500 ms after the second nowtime has started, because when
499 * nowtime is written into the registers of the CMOS clock, it will
500 * jump to the next second precisely 500 ms later. Check the Motorola
501 * MC146818A or Dallas DS12887 data sheet for details.
502 *
503 * BUG: This routine does not handle hour overflow properly; it just
504 *      sets the minutes. Usually you won't notice until after reboot!
505 */
506
507extern int abs(int);
508
509static int
510set_rtc_mmss(unsigned long nowtime)
511{
512	int retval = 0;
513	int real_seconds, real_minutes, cmos_minutes;
514	unsigned char save_control, save_freq_select;
515
516	/* irq are locally disabled here */
517	spin_lock(&rtc_lock);
518	/* Tell the clock it's being set */
519	save_control = CMOS_READ(RTC_CONTROL);
520	CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
521
522	/* Stop and reset prescaler */
523	save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
524	CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
525
526	cmos_minutes = CMOS_READ(RTC_MINUTES);
527	if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
528		BCD_TO_BIN(cmos_minutes);
529
530	/*
531	 * since we're only adjusting minutes and seconds,
532	 * don't interfere with hour overflow. This avoids
533	 * messing with unknown time zones but requires your
534	 * RTC not to be off by more than 15 minutes
535	 */
536	real_seconds = nowtime % 60;
537	real_minutes = nowtime / 60;
538	if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) {
539		/* correct for half hour time zone */
540		real_minutes += 30;
541	}
542	real_minutes %= 60;
543
544	if (abs(real_minutes - cmos_minutes) < 30) {
545		if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
546			BIN_TO_BCD(real_seconds);
547			BIN_TO_BCD(real_minutes);
548		}
549		CMOS_WRITE(real_seconds,RTC_SECONDS);
550		CMOS_WRITE(real_minutes,RTC_MINUTES);
551	} else {
552		printk(KERN_WARNING
553		       "set_rtc_mmss: can't update from %d to %d\n",
554		       cmos_minutes, real_minutes);
555 		retval = -1;
556	}
557
558	/* The following flags have to be released exactly in this order,
559	 * otherwise the DS12887 (popular MC146818A clone with integrated
560	 * battery and quartz) will not reset the oscillator and will not
561	 * update precisely 500 ms later. You won't find this mentioned in
562	 * the Dallas Semiconductor data sheets, but who believes data
563	 * sheets anyway ...                           -- Markus Kuhn
564	 */
565	CMOS_WRITE(save_control, RTC_CONTROL);
566	CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
567	spin_unlock(&rtc_lock);
568
569	return retval;
570}
571